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 |
|---|---|---|---|---|---|---|
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodThreadLocal.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/LocaleThreadLocal.java
// public class LocaleThreadLocal {
//
// public static final ThreadLocal<LocaleThreadLocal> localeThreadLocal = new ThreadLocal<>();
// private final Locale locale;
//
// public LocaleThreadLocal(Locale locale) {
// this.locale = locale;
// }
//
// public Locale getLocale() {
// return locale;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/servlet/TestServlet.java
// @WebServlet(urlPatterns = "/testservlet")
// public class TestServlet extends HttpServlet {
//
// private static final long serialVersionUID = 1L;
//
// @EJB
// private OtherService otherService;
//
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Assert.assertEquals(Integer.class, otherService.getInteger().getClass());
// Assert.assertEquals(new Integer(2), otherService.getInteger());
// req.setAttribute("result", otherService.getText());
// req.setAttribute("integer", otherService.getInteger());
// req.getRequestDispatcher("test.jsp").forward(req, resp);
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/IntegrationTestDeploymentUtils.java
// public static class DeploymentAppenderFactory {
//
// private DeploymentAppenderFactory() {
// }
//
// public static WebDeploymentAppender create(WebArchive archive) {
// return new WebDeploymentAppender(archive);
// }
//
// public static JavaDeploymentAppender create(JavaArchive archive) {
// return new JavaDeploymentAppender(archive);
// }
//
// public static EnterpriseDeploymentAppender create(EnterpriseArchive archive) {
// return new EnterpriseDeploymentAppender(archive);
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherService.java
// @Local
// public interface OtherService extends Serializable {
//
// String getText();
//
// Integer getInteger();
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherServiceBean.java
// @Stateless
// public class OtherServiceBean implements OtherService {
//
// private static final long serialVersionUID = 1L;
//
// @Property("hello.world")
// private String text;
//
// @Property("some.integer")
// private Integer integer;
//
// @Override
// public String getText() {
// return text;
// }
//
// @Override
// public Integer getInteger() {
// return integer;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ProvidedLocaleMethodResolverThreadLocal.java
// @ApplicationScoped
// public class ProvidedLocaleMethodResolverThreadLocal implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @LocaleResolver
// public Locale resolveLocale() {
// return LocaleThreadLocal.localeThreadLocal.get().getLocale();
// }
//
// }
| import java.io.IOException;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import com.byteslounge.cdi.test.common.LocaleThreadLocal;
import com.byteslounge.cdi.test.common.servlet.TestServlet;
import com.byteslounge.cdi.test.it.common.IntegrationTestDeploymentUtils.DeploymentAppenderFactory;
import com.byteslounge.cdi.test.wpm.OtherService;
import com.byteslounge.cdi.test.wpm.OtherServiceBean;
import com.byteslounge.cdi.test.wpm.ProvidedLocaleMethodResolverThreadLocal; | /*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it.common;
/**
* Base class for Integration Tests which resolve the current locale from a ThreadLocal variable
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public abstract class AbstractWarProvidedLocaleMethodThreadLocal {
protected static WebArchive createArchive() throws IOException {
WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses(
ProvidedLocaleMethodResolverThreadLocal.class, OtherService.class, OtherServiceBean.class, | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/LocaleThreadLocal.java
// public class LocaleThreadLocal {
//
// public static final ThreadLocal<LocaleThreadLocal> localeThreadLocal = new ThreadLocal<>();
// private final Locale locale;
//
// public LocaleThreadLocal(Locale locale) {
// this.locale = locale;
// }
//
// public Locale getLocale() {
// return locale;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/servlet/TestServlet.java
// @WebServlet(urlPatterns = "/testservlet")
// public class TestServlet extends HttpServlet {
//
// private static final long serialVersionUID = 1L;
//
// @EJB
// private OtherService otherService;
//
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Assert.assertEquals(Integer.class, otherService.getInteger().getClass());
// Assert.assertEquals(new Integer(2), otherService.getInteger());
// req.setAttribute("result", otherService.getText());
// req.setAttribute("integer", otherService.getInteger());
// req.getRequestDispatcher("test.jsp").forward(req, resp);
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/IntegrationTestDeploymentUtils.java
// public static class DeploymentAppenderFactory {
//
// private DeploymentAppenderFactory() {
// }
//
// public static WebDeploymentAppender create(WebArchive archive) {
// return new WebDeploymentAppender(archive);
// }
//
// public static JavaDeploymentAppender create(JavaArchive archive) {
// return new JavaDeploymentAppender(archive);
// }
//
// public static EnterpriseDeploymentAppender create(EnterpriseArchive archive) {
// return new EnterpriseDeploymentAppender(archive);
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherService.java
// @Local
// public interface OtherService extends Serializable {
//
// String getText();
//
// Integer getInteger();
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherServiceBean.java
// @Stateless
// public class OtherServiceBean implements OtherService {
//
// private static final long serialVersionUID = 1L;
//
// @Property("hello.world")
// private String text;
//
// @Property("some.integer")
// private Integer integer;
//
// @Override
// public String getText() {
// return text;
// }
//
// @Override
// public Integer getInteger() {
// return integer;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ProvidedLocaleMethodResolverThreadLocal.java
// @ApplicationScoped
// public class ProvidedLocaleMethodResolverThreadLocal implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @LocaleResolver
// public Locale resolveLocale() {
// return LocaleThreadLocal.localeThreadLocal.get().getLocale();
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodThreadLocal.java
import java.io.IOException;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import com.byteslounge.cdi.test.common.LocaleThreadLocal;
import com.byteslounge.cdi.test.common.servlet.TestServlet;
import com.byteslounge.cdi.test.it.common.IntegrationTestDeploymentUtils.DeploymentAppenderFactory;
import com.byteslounge.cdi.test.wpm.OtherService;
import com.byteslounge.cdi.test.wpm.OtherServiceBean;
import com.byteslounge.cdi.test.wpm.ProvidedLocaleMethodResolverThreadLocal;
/*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it.common;
/**
* Base class for Integration Tests which resolve the current locale from a ThreadLocal variable
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public abstract class AbstractWarProvidedLocaleMethodThreadLocal {
protected static WebArchive createArchive() throws IOException {
WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses(
ProvidedLocaleMethodResolverThreadLocal.class, OtherService.class, OtherServiceBean.class, | TestServlet.class, LocaleThreadLocal.class); |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodThreadLocal.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/LocaleThreadLocal.java
// public class LocaleThreadLocal {
//
// public static final ThreadLocal<LocaleThreadLocal> localeThreadLocal = new ThreadLocal<>();
// private final Locale locale;
//
// public LocaleThreadLocal(Locale locale) {
// this.locale = locale;
// }
//
// public Locale getLocale() {
// return locale;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/servlet/TestServlet.java
// @WebServlet(urlPatterns = "/testservlet")
// public class TestServlet extends HttpServlet {
//
// private static final long serialVersionUID = 1L;
//
// @EJB
// private OtherService otherService;
//
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Assert.assertEquals(Integer.class, otherService.getInteger().getClass());
// Assert.assertEquals(new Integer(2), otherService.getInteger());
// req.setAttribute("result", otherService.getText());
// req.setAttribute("integer", otherService.getInteger());
// req.getRequestDispatcher("test.jsp").forward(req, resp);
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/IntegrationTestDeploymentUtils.java
// public static class DeploymentAppenderFactory {
//
// private DeploymentAppenderFactory() {
// }
//
// public static WebDeploymentAppender create(WebArchive archive) {
// return new WebDeploymentAppender(archive);
// }
//
// public static JavaDeploymentAppender create(JavaArchive archive) {
// return new JavaDeploymentAppender(archive);
// }
//
// public static EnterpriseDeploymentAppender create(EnterpriseArchive archive) {
// return new EnterpriseDeploymentAppender(archive);
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherService.java
// @Local
// public interface OtherService extends Serializable {
//
// String getText();
//
// Integer getInteger();
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherServiceBean.java
// @Stateless
// public class OtherServiceBean implements OtherService {
//
// private static final long serialVersionUID = 1L;
//
// @Property("hello.world")
// private String text;
//
// @Property("some.integer")
// private Integer integer;
//
// @Override
// public String getText() {
// return text;
// }
//
// @Override
// public Integer getInteger() {
// return integer;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ProvidedLocaleMethodResolverThreadLocal.java
// @ApplicationScoped
// public class ProvidedLocaleMethodResolverThreadLocal implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @LocaleResolver
// public Locale resolveLocale() {
// return LocaleThreadLocal.localeThreadLocal.get().getLocale();
// }
//
// }
| import java.io.IOException;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import com.byteslounge.cdi.test.common.LocaleThreadLocal;
import com.byteslounge.cdi.test.common.servlet.TestServlet;
import com.byteslounge.cdi.test.it.common.IntegrationTestDeploymentUtils.DeploymentAppenderFactory;
import com.byteslounge.cdi.test.wpm.OtherService;
import com.byteslounge.cdi.test.wpm.OtherServiceBean;
import com.byteslounge.cdi.test.wpm.ProvidedLocaleMethodResolverThreadLocal; | /*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it.common;
/**
* Base class for Integration Tests which resolve the current locale from a ThreadLocal variable
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public abstract class AbstractWarProvidedLocaleMethodThreadLocal {
protected static WebArchive createArchive() throws IOException {
WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses(
ProvidedLocaleMethodResolverThreadLocal.class, OtherService.class, OtherServiceBean.class, | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/LocaleThreadLocal.java
// public class LocaleThreadLocal {
//
// public static final ThreadLocal<LocaleThreadLocal> localeThreadLocal = new ThreadLocal<>();
// private final Locale locale;
//
// public LocaleThreadLocal(Locale locale) {
// this.locale = locale;
// }
//
// public Locale getLocale() {
// return locale;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/servlet/TestServlet.java
// @WebServlet(urlPatterns = "/testservlet")
// public class TestServlet extends HttpServlet {
//
// private static final long serialVersionUID = 1L;
//
// @EJB
// private OtherService otherService;
//
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Assert.assertEquals(Integer.class, otherService.getInteger().getClass());
// Assert.assertEquals(new Integer(2), otherService.getInteger());
// req.setAttribute("result", otherService.getText());
// req.setAttribute("integer", otherService.getInteger());
// req.getRequestDispatcher("test.jsp").forward(req, resp);
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/IntegrationTestDeploymentUtils.java
// public static class DeploymentAppenderFactory {
//
// private DeploymentAppenderFactory() {
// }
//
// public static WebDeploymentAppender create(WebArchive archive) {
// return new WebDeploymentAppender(archive);
// }
//
// public static JavaDeploymentAppender create(JavaArchive archive) {
// return new JavaDeploymentAppender(archive);
// }
//
// public static EnterpriseDeploymentAppender create(EnterpriseArchive archive) {
// return new EnterpriseDeploymentAppender(archive);
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherService.java
// @Local
// public interface OtherService extends Serializable {
//
// String getText();
//
// Integer getInteger();
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherServiceBean.java
// @Stateless
// public class OtherServiceBean implements OtherService {
//
// private static final long serialVersionUID = 1L;
//
// @Property("hello.world")
// private String text;
//
// @Property("some.integer")
// private Integer integer;
//
// @Override
// public String getText() {
// return text;
// }
//
// @Override
// public Integer getInteger() {
// return integer;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ProvidedLocaleMethodResolverThreadLocal.java
// @ApplicationScoped
// public class ProvidedLocaleMethodResolverThreadLocal implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @LocaleResolver
// public Locale resolveLocale() {
// return LocaleThreadLocal.localeThreadLocal.get().getLocale();
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodThreadLocal.java
import java.io.IOException;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import com.byteslounge.cdi.test.common.LocaleThreadLocal;
import com.byteslounge.cdi.test.common.servlet.TestServlet;
import com.byteslounge.cdi.test.it.common.IntegrationTestDeploymentUtils.DeploymentAppenderFactory;
import com.byteslounge.cdi.test.wpm.OtherService;
import com.byteslounge.cdi.test.wpm.OtherServiceBean;
import com.byteslounge.cdi.test.wpm.ProvidedLocaleMethodResolverThreadLocal;
/*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it.common;
/**
* Base class for Integration Tests which resolve the current locale from a ThreadLocal variable
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public abstract class AbstractWarProvidedLocaleMethodThreadLocal {
protected static WebArchive createArchive() throws IOException {
WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses(
ProvidedLocaleMethodResolverThreadLocal.class, OtherService.class, OtherServiceBean.class, | TestServlet.class, LocaleThreadLocal.class); |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodThreadLocal.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/LocaleThreadLocal.java
// public class LocaleThreadLocal {
//
// public static final ThreadLocal<LocaleThreadLocal> localeThreadLocal = new ThreadLocal<>();
// private final Locale locale;
//
// public LocaleThreadLocal(Locale locale) {
// this.locale = locale;
// }
//
// public Locale getLocale() {
// return locale;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/servlet/TestServlet.java
// @WebServlet(urlPatterns = "/testservlet")
// public class TestServlet extends HttpServlet {
//
// private static final long serialVersionUID = 1L;
//
// @EJB
// private OtherService otherService;
//
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Assert.assertEquals(Integer.class, otherService.getInteger().getClass());
// Assert.assertEquals(new Integer(2), otherService.getInteger());
// req.setAttribute("result", otherService.getText());
// req.setAttribute("integer", otherService.getInteger());
// req.getRequestDispatcher("test.jsp").forward(req, resp);
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/IntegrationTestDeploymentUtils.java
// public static class DeploymentAppenderFactory {
//
// private DeploymentAppenderFactory() {
// }
//
// public static WebDeploymentAppender create(WebArchive archive) {
// return new WebDeploymentAppender(archive);
// }
//
// public static JavaDeploymentAppender create(JavaArchive archive) {
// return new JavaDeploymentAppender(archive);
// }
//
// public static EnterpriseDeploymentAppender create(EnterpriseArchive archive) {
// return new EnterpriseDeploymentAppender(archive);
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherService.java
// @Local
// public interface OtherService extends Serializable {
//
// String getText();
//
// Integer getInteger();
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherServiceBean.java
// @Stateless
// public class OtherServiceBean implements OtherService {
//
// private static final long serialVersionUID = 1L;
//
// @Property("hello.world")
// private String text;
//
// @Property("some.integer")
// private Integer integer;
//
// @Override
// public String getText() {
// return text;
// }
//
// @Override
// public Integer getInteger() {
// return integer;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ProvidedLocaleMethodResolverThreadLocal.java
// @ApplicationScoped
// public class ProvidedLocaleMethodResolverThreadLocal implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @LocaleResolver
// public Locale resolveLocale() {
// return LocaleThreadLocal.localeThreadLocal.get().getLocale();
// }
//
// }
| import java.io.IOException;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import com.byteslounge.cdi.test.common.LocaleThreadLocal;
import com.byteslounge.cdi.test.common.servlet.TestServlet;
import com.byteslounge.cdi.test.it.common.IntegrationTestDeploymentUtils.DeploymentAppenderFactory;
import com.byteslounge.cdi.test.wpm.OtherService;
import com.byteslounge.cdi.test.wpm.OtherServiceBean;
import com.byteslounge.cdi.test.wpm.ProvidedLocaleMethodResolverThreadLocal; | /*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it.common;
/**
* Base class for Integration Tests which resolve the current locale from a ThreadLocal variable
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public abstract class AbstractWarProvidedLocaleMethodThreadLocal {
protected static WebArchive createArchive() throws IOException {
WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses(
ProvidedLocaleMethodResolverThreadLocal.class, OtherService.class, OtherServiceBean.class,
TestServlet.class, LocaleThreadLocal.class); | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/LocaleThreadLocal.java
// public class LocaleThreadLocal {
//
// public static final ThreadLocal<LocaleThreadLocal> localeThreadLocal = new ThreadLocal<>();
// private final Locale locale;
//
// public LocaleThreadLocal(Locale locale) {
// this.locale = locale;
// }
//
// public Locale getLocale() {
// return locale;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/servlet/TestServlet.java
// @WebServlet(urlPatterns = "/testservlet")
// public class TestServlet extends HttpServlet {
//
// private static final long serialVersionUID = 1L;
//
// @EJB
// private OtherService otherService;
//
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Assert.assertEquals(Integer.class, otherService.getInteger().getClass());
// Assert.assertEquals(new Integer(2), otherService.getInteger());
// req.setAttribute("result", otherService.getText());
// req.setAttribute("integer", otherService.getInteger());
// req.getRequestDispatcher("test.jsp").forward(req, resp);
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/IntegrationTestDeploymentUtils.java
// public static class DeploymentAppenderFactory {
//
// private DeploymentAppenderFactory() {
// }
//
// public static WebDeploymentAppender create(WebArchive archive) {
// return new WebDeploymentAppender(archive);
// }
//
// public static JavaDeploymentAppender create(JavaArchive archive) {
// return new JavaDeploymentAppender(archive);
// }
//
// public static EnterpriseDeploymentAppender create(EnterpriseArchive archive) {
// return new EnterpriseDeploymentAppender(archive);
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherService.java
// @Local
// public interface OtherService extends Serializable {
//
// String getText();
//
// Integer getInteger();
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherServiceBean.java
// @Stateless
// public class OtherServiceBean implements OtherService {
//
// private static final long serialVersionUID = 1L;
//
// @Property("hello.world")
// private String text;
//
// @Property("some.integer")
// private Integer integer;
//
// @Override
// public String getText() {
// return text;
// }
//
// @Override
// public Integer getInteger() {
// return integer;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ProvidedLocaleMethodResolverThreadLocal.java
// @ApplicationScoped
// public class ProvidedLocaleMethodResolverThreadLocal implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @LocaleResolver
// public Locale resolveLocale() {
// return LocaleThreadLocal.localeThreadLocal.get().getLocale();
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodThreadLocal.java
import java.io.IOException;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import com.byteslounge.cdi.test.common.LocaleThreadLocal;
import com.byteslounge.cdi.test.common.servlet.TestServlet;
import com.byteslounge.cdi.test.it.common.IntegrationTestDeploymentUtils.DeploymentAppenderFactory;
import com.byteslounge.cdi.test.wpm.OtherService;
import com.byteslounge.cdi.test.wpm.OtherServiceBean;
import com.byteslounge.cdi.test.wpm.ProvidedLocaleMethodResolverThreadLocal;
/*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it.common;
/**
* Base class for Integration Tests which resolve the current locale from a ThreadLocal variable
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public abstract class AbstractWarProvidedLocaleMethodThreadLocal {
protected static WebArchive createArchive() throws IOException {
WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses(
ProvidedLocaleMethodResolverThreadLocal.class, OtherService.class, OtherServiceBean.class,
TestServlet.class, LocaleThreadLocal.class); | DeploymentAppenderFactory.create(webArchive) |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/edm/ServiceEjbDefaultMethodBean.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/InjectedBean.java
// public class InjectedBean implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// public String getText() {
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
| import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.Assert;
import com.byteslounge.cdi.annotation.Property;
import com.byteslounge.cdi.test.common.InjectedBean;
import com.byteslounge.cdi.test.configuration.TestConstants;
import com.byteslounge.cdi.test.model.TestEntity; | /*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.edm;
/**
* Used in CDI Properties integration tests. See WarDefaultMethodIT.java,
* WarProvidedMethodIT.java, EjbDefaultMethodIT.java and
* EjbProvidedMethodIT.java.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
@Stateless
public class ServiceEjbDefaultMethodBean implements ServiceEjbDefaultMethod {
private static final long serialVersionUID = 1L;
@Property("hello.world")
private String helloWorld;
@Property(value = "system.linux.box", parameters = { "Linux", "16" })
private String systemBox;
| // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/InjectedBean.java
// public class InjectedBean implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// public String getText() {
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/edm/ServiceEjbDefaultMethodBean.java
import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.Assert;
import com.byteslounge.cdi.annotation.Property;
import com.byteslounge.cdi.test.common.InjectedBean;
import com.byteslounge.cdi.test.configuration.TestConstants;
import com.byteslounge.cdi.test.model.TestEntity;
/*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.edm;
/**
* Used in CDI Properties integration tests. See WarDefaultMethodIT.java,
* WarProvidedMethodIT.java, EjbDefaultMethodIT.java and
* EjbProvidedMethodIT.java.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
@Stateless
public class ServiceEjbDefaultMethodBean implements ServiceEjbDefaultMethod {
private static final long serialVersionUID = 1L;
@Property("hello.world")
private String helloWorld;
@Property(value = "system.linux.box", parameters = { "Linux", "16" })
private String systemBox;
| @Property(value = "other.message", resourceBundleBaseName = TestConstants.OTHER_RESOURCE_BUNDLE_NAME) |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/edm/ServiceEjbDefaultMethodBean.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/InjectedBean.java
// public class InjectedBean implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// public String getText() {
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
| import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.Assert;
import com.byteslounge.cdi.annotation.Property;
import com.byteslounge.cdi.test.common.InjectedBean;
import com.byteslounge.cdi.test.configuration.TestConstants;
import com.byteslounge.cdi.test.model.TestEntity; | /*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.edm;
/**
* Used in CDI Properties integration tests. See WarDefaultMethodIT.java,
* WarProvidedMethodIT.java, EjbDefaultMethodIT.java and
* EjbProvidedMethodIT.java.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
@Stateless
public class ServiceEjbDefaultMethodBean implements ServiceEjbDefaultMethod {
private static final long serialVersionUID = 1L;
@Property("hello.world")
private String helloWorld;
@Property(value = "system.linux.box", parameters = { "Linux", "16" })
private String systemBox;
@Property(value = "other.message", resourceBundleBaseName = TestConstants.OTHER_RESOURCE_BUNDLE_NAME)
private String other;
@Property(value = "other.parameter", parameters = { "B" }, resourceBundleBaseName = TestConstants.OTHER_RESOURCE_BUNDLE_NAME)
private String otherAbc;
@Inject | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/InjectedBean.java
// public class InjectedBean implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// public String getText() {
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/edm/ServiceEjbDefaultMethodBean.java
import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.Assert;
import com.byteslounge.cdi.annotation.Property;
import com.byteslounge.cdi.test.common.InjectedBean;
import com.byteslounge.cdi.test.configuration.TestConstants;
import com.byteslounge.cdi.test.model.TestEntity;
/*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.edm;
/**
* Used in CDI Properties integration tests. See WarDefaultMethodIT.java,
* WarProvidedMethodIT.java, EjbDefaultMethodIT.java and
* EjbProvidedMethodIT.java.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
@Stateless
public class ServiceEjbDefaultMethodBean implements ServiceEjbDefaultMethod {
private static final long serialVersionUID = 1L;
@Property("hello.world")
private String helloWorld;
@Property(value = "system.linux.box", parameters = { "Linux", "16" })
private String systemBox;
@Property(value = "other.message", resourceBundleBaseName = TestConstants.OTHER_RESOURCE_BUNDLE_NAME)
private String other;
@Property(value = "other.parameter", parameters = { "B" }, resourceBundleBaseName = TestConstants.OTHER_RESOURCE_BUNDLE_NAME)
private String otherAbc;
@Inject | private InjectedBean injectedBean; |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/edm/ServiceEjbDefaultMethodBean.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/InjectedBean.java
// public class InjectedBean implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// public String getText() {
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
| import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.Assert;
import com.byteslounge.cdi.annotation.Property;
import com.byteslounge.cdi.test.common.InjectedBean;
import com.byteslounge.cdi.test.configuration.TestConstants;
import com.byteslounge.cdi.test.model.TestEntity; | /*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.edm;
/**
* Used in CDI Properties integration tests. See WarDefaultMethodIT.java,
* WarProvidedMethodIT.java, EjbDefaultMethodIT.java and
* EjbProvidedMethodIT.java.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
@Stateless
public class ServiceEjbDefaultMethodBean implements ServiceEjbDefaultMethod {
private static final long serialVersionUID = 1L;
@Property("hello.world")
private String helloWorld;
@Property(value = "system.linux.box", parameters = { "Linux", "16" })
private String systemBox;
@Property(value = "other.message", resourceBundleBaseName = TestConstants.OTHER_RESOURCE_BUNDLE_NAME)
private String other;
@Property(value = "other.parameter", parameters = { "B" }, resourceBundleBaseName = TestConstants.OTHER_RESOURCE_BUNDLE_NAME)
private String otherAbc;
@Inject
private InjectedBean injectedBean;
@PersistenceContext
private EntityManager entityManager;
@SuppressWarnings("unused")
@PostConstruct
private void init() {
Assert.assertEquals(injectedBean.getText(), TestConstants.BEAN_TEST_RETURN_VALUE);
}
@Override
public String getHelloWorld() { | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/InjectedBean.java
// public class InjectedBean implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// public String getText() {
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/edm/ServiceEjbDefaultMethodBean.java
import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.Assert;
import com.byteslounge.cdi.annotation.Property;
import com.byteslounge.cdi.test.common.InjectedBean;
import com.byteslounge.cdi.test.configuration.TestConstants;
import com.byteslounge.cdi.test.model.TestEntity;
/*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.edm;
/**
* Used in CDI Properties integration tests. See WarDefaultMethodIT.java,
* WarProvidedMethodIT.java, EjbDefaultMethodIT.java and
* EjbProvidedMethodIT.java.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
@Stateless
public class ServiceEjbDefaultMethodBean implements ServiceEjbDefaultMethod {
private static final long serialVersionUID = 1L;
@Property("hello.world")
private String helloWorld;
@Property(value = "system.linux.box", parameters = { "Linux", "16" })
private String systemBox;
@Property(value = "other.message", resourceBundleBaseName = TestConstants.OTHER_RESOURCE_BUNDLE_NAME)
private String other;
@Property(value = "other.parameter", parameters = { "B" }, resourceBundleBaseName = TestConstants.OTHER_RESOURCE_BUNDLE_NAME)
private String otherAbc;
@Inject
private InjectedBean injectedBean;
@PersistenceContext
private EntityManager entityManager;
@SuppressWarnings("unused")
@PostConstruct
private void init() {
Assert.assertEquals(injectedBean.getText(), TestConstants.BEAN_TEST_RETURN_VALUE);
}
@Override
public String getHelloWorld() { | TestEntity entity = entityManager.find(TestEntity.class, 1L); |
gonmarques/cdi-properties | cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/verifier/DependentResolverMethodParametersVerifier.java | // Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/exception/ExtensionInitializationException.java
// public class ExtensionInitializationException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public ExtensionInitializationException(String message) {
// super(message);
// }
//
// public ExtensionInitializationException(Throwable cause) {
// super(cause);
// }
//
// public ExtensionInitializationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/utils/MessageUtils.java
// public class MessageUtils {
//
// private MessageUtils() {
// }
//
// /**
// * Builds a textual representation of an {@link AnnotatedMethod}
// *
// * @param method
// * The {@link AnnotatedMethod} instance
// * @return A textual representation of the {@link AnnotatedMethod}
// */
// public static String getMethodDefinition(AnnotatedMethod<?> method) {
// return method.getJavaMember().getDeclaringClass().getName() + "." + method.getJavaMember().getName() + "()";
// }
//
// }
| import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.Dependent;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.spi.AnnotatedMethod;
import javax.enterprise.inject.spi.AnnotatedParameter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.byteslounge.cdi.annotation.Property;
import com.byteslounge.cdi.exception.ExtensionInitializationException;
import com.byteslounge.cdi.utils.MessageUtils; | viewScopedClass = Class.forName("javax.faces.view.ViewScoped");
} catch (Exception e) {
// JEE 6 environment
if (logger.isDebugEnabled()) {
logger.debug("Class javax.faces.view.ViewScoped was not found: Running in a Java EE 6 environment.");
}
}
if (viewScopedClass != null) {
if (annotation.annotationType().equals(viewScopedClass)) {
return false;
}
}
}
return true;
}
/**
* Checks if a custom injected parameter has any field annotated with
* {@link Property} (this function calls itself recursively).
*
* @param originalType
* The type being checked
* @param type
* The current type or original type super class being checked
* (this function calls itself recursively).
*/
private void checkPropertyField(Class<?> originalType, Class<?> type) {
for (Field field : type.getDeclaredFields()) {
for (Annotation annotation : field.getAnnotations()) {
if (annotation.annotationType().equals(Property.class)) { | // Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/exception/ExtensionInitializationException.java
// public class ExtensionInitializationException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public ExtensionInitializationException(String message) {
// super(message);
// }
//
// public ExtensionInitializationException(Throwable cause) {
// super(cause);
// }
//
// public ExtensionInitializationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/utils/MessageUtils.java
// public class MessageUtils {
//
// private MessageUtils() {
// }
//
// /**
// * Builds a textual representation of an {@link AnnotatedMethod}
// *
// * @param method
// * The {@link AnnotatedMethod} instance
// * @return A textual representation of the {@link AnnotatedMethod}
// */
// public static String getMethodDefinition(AnnotatedMethod<?> method) {
// return method.getJavaMember().getDeclaringClass().getName() + "." + method.getJavaMember().getName() + "()";
// }
//
// }
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/verifier/DependentResolverMethodParametersVerifier.java
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.Dependent;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.spi.AnnotatedMethod;
import javax.enterprise.inject.spi.AnnotatedParameter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.byteslounge.cdi.annotation.Property;
import com.byteslounge.cdi.exception.ExtensionInitializationException;
import com.byteslounge.cdi.utils.MessageUtils;
viewScopedClass = Class.forName("javax.faces.view.ViewScoped");
} catch (Exception e) {
// JEE 6 environment
if (logger.isDebugEnabled()) {
logger.debug("Class javax.faces.view.ViewScoped was not found: Running in a Java EE 6 environment.");
}
}
if (viewScopedClass != null) {
if (annotation.annotationType().equals(viewScopedClass)) {
return false;
}
}
}
return true;
}
/**
* Checks if a custom injected parameter has any field annotated with
* {@link Property} (this function calls itself recursively).
*
* @param originalType
* The type being checked
* @param type
* The current type or original type super class being checked
* (this function calls itself recursively).
*/
private void checkPropertyField(Class<?> originalType, Class<?> type) {
for (Field field : type.getDeclaredFields()) {
for (Annotation annotation : field.getAnnotations()) {
if (annotation.annotationType().equals(Property.class)) { | throw new ExtensionInitializationException( |
gonmarques/cdi-properties | cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/verifier/DependentResolverMethodParametersVerifier.java | // Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/exception/ExtensionInitializationException.java
// public class ExtensionInitializationException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public ExtensionInitializationException(String message) {
// super(message);
// }
//
// public ExtensionInitializationException(Throwable cause) {
// super(cause);
// }
//
// public ExtensionInitializationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/utils/MessageUtils.java
// public class MessageUtils {
//
// private MessageUtils() {
// }
//
// /**
// * Builds a textual representation of an {@link AnnotatedMethod}
// *
// * @param method
// * The {@link AnnotatedMethod} instance
// * @return A textual representation of the {@link AnnotatedMethod}
// */
// public static String getMethodDefinition(AnnotatedMethod<?> method) {
// return method.getJavaMember().getDeclaringClass().getName() + "." + method.getJavaMember().getName() + "()";
// }
//
// }
| import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.Dependent;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.spi.AnnotatedMethod;
import javax.enterprise.inject.spi.AnnotatedParameter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.byteslounge.cdi.annotation.Property;
import com.byteslounge.cdi.exception.ExtensionInitializationException;
import com.byteslounge.cdi.utils.MessageUtils; | // JEE 6 environment
if (logger.isDebugEnabled()) {
logger.debug("Class javax.faces.view.ViewScoped was not found: Running in a Java EE 6 environment.");
}
}
if (viewScopedClass != null) {
if (annotation.annotationType().equals(viewScopedClass)) {
return false;
}
}
}
return true;
}
/**
* Checks if a custom injected parameter has any field annotated with
* {@link Property} (this function calls itself recursively).
*
* @param originalType
* The type being checked
* @param type
* The current type or original type super class being checked
* (this function calls itself recursively).
*/
private void checkPropertyField(Class<?> originalType, Class<?> type) {
for (Field field : type.getDeclaredFields()) {
for (Annotation annotation : field.getAnnotations()) {
if (annotation.annotationType().equals(Property.class)) {
throw new ExtensionInitializationException(
"Resolver method " | // Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/exception/ExtensionInitializationException.java
// public class ExtensionInitializationException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public ExtensionInitializationException(String message) {
// super(message);
// }
//
// public ExtensionInitializationException(Throwable cause) {
// super(cause);
// }
//
// public ExtensionInitializationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/utils/MessageUtils.java
// public class MessageUtils {
//
// private MessageUtils() {
// }
//
// /**
// * Builds a textual representation of an {@link AnnotatedMethod}
// *
// * @param method
// * The {@link AnnotatedMethod} instance
// * @return A textual representation of the {@link AnnotatedMethod}
// */
// public static String getMethodDefinition(AnnotatedMethod<?> method) {
// return method.getJavaMember().getDeclaringClass().getName() + "." + method.getJavaMember().getName() + "()";
// }
//
// }
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/verifier/DependentResolverMethodParametersVerifier.java
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.Dependent;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.spi.AnnotatedMethod;
import javax.enterprise.inject.spi.AnnotatedParameter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.byteslounge.cdi.annotation.Property;
import com.byteslounge.cdi.exception.ExtensionInitializationException;
import com.byteslounge.cdi.utils.MessageUtils;
// JEE 6 environment
if (logger.isDebugEnabled()) {
logger.debug("Class javax.faces.view.ViewScoped was not found: Running in a Java EE 6 environment.");
}
}
if (viewScopedClass != null) {
if (annotation.annotationType().equals(viewScopedClass)) {
return false;
}
}
}
return true;
}
/**
* Checks if a custom injected parameter has any field annotated with
* {@link Property} (this function calls itself recursively).
*
* @param originalType
* The type being checked
* @param type
* The current type or original type super class being checked
* (this function calls itself recursively).
*/
private void checkPropertyField(Class<?> originalType, Class<?> type) {
for (Field field : type.getDeclaredFields()) {
for (Annotation annotation : field.getAnnotations()) {
if (annotation.annotationType().equals(Property.class)) {
throw new ExtensionInitializationException(
"Resolver method " | + MessageUtils.getMethodDefinition(resolverMethod) |
gonmarques/cdi-properties | cdi-properties-main/src/main/java/com/byteslounge/cdi/extension/param/InjectableResolverParameter.java | // Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/context/ResolverContext.java
// public class ResolverContext {
//
// private final String key;
// private final String bundleName;
// private Bean<?> resolverBean;
// private BeanManager beanManager;
//
// private ResolverContext(String key, String bundleName) {
// this.key = key;
// this.bundleName = bundleName;
// }
//
// /**
// * Creates a {@link com.byteslounge.cdi.resolver.context.ResolverContext} instance.
// *
// * @param key the property key to be associated with the created context
// * @param bundleName the resource bundle name to be associated with the created context
// *
// * @return the newly created {@link com.byteslounge.cdi.resolver.context.ResolverContext} instance
// */
// public static ResolverContext create(String key, String bundleName) {
// return new ResolverContext(key, bundleName);
// }
//
// /**
// * Gets the key associated with this {@link com.byteslounge.cdi.resolver.context.ResolverContext} instance
// *
// * @return the key associated with this {@link com.byteslounge.cdi.resolver.context.ResolverContext} instance
// */
// public String getKey() {
// return key;
// }
//
// /**
// * Gets the resource bundle name associated with this {@link com.byteslounge.cdi.resolver.context.ResolverContext} instance
// *
// * @return the resource bundle name associated with this {@link com.byteslounge.cdi.resolver.context.ResolverContext} instance
// */
// public String getBundleName() {
// return bundleName;
// }
//
// /**
// * Sets the resolver bean associated with the current resolving execution
// *
// * @param resolverBean the property key to be associated with the created context
// */
// public void setResolverBean(Bean<?> resolverBean) {
// this.resolverBean = resolverBean;
// }
//
// /**
// * Gets the resolver bean associated with the current resolving execution
// *
// * @return the resolver bean associated with the current resolving execution
// */
// public Bean<?> getResolverBean() {
// return resolverBean;
// }
//
// /**
// * Gets the bean manager associated with the current resolving execution
// *
// * @return the bean manager associated with the current resolving execution
// */
// public BeanManager getBeanManager() {
// return beanManager;
// }
//
// /**
// * Sets the bean manager associated with the current resolving execution
// *
// * @param beanManager the bean manager associated with the current resolving execution
// */
// public void setBeanManager(BeanManager beanManager) {
// this.beanManager = beanManager;
// }
//
// }
| import java.lang.annotation.Annotation;
import java.lang.reflect.Member;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Set;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Annotated;
import javax.enterprise.inject.spi.AnnotatedParameter;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.InjectionPoint;
import com.byteslounge.cdi.resolver.context.ResolverContext; | }
/**
* See {@link InjectionPoint#getType()}
*/
@Override
public Type getType() {
return parameter.getBaseType();
}
/**
* See {@link InjectionPoint#isDelegate()}
*/
@Override
public boolean isDelegate() {
return false;
}
/**
* See {@link InjectionPoint#isTransient()}
*/
@Override
public boolean isTransient() {
return false;
}
/**
* see {@link ResolverParameter#resolve(String, String, CreationalContext)}
*/
@Override | // Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/context/ResolverContext.java
// public class ResolverContext {
//
// private final String key;
// private final String bundleName;
// private Bean<?> resolverBean;
// private BeanManager beanManager;
//
// private ResolverContext(String key, String bundleName) {
// this.key = key;
// this.bundleName = bundleName;
// }
//
// /**
// * Creates a {@link com.byteslounge.cdi.resolver.context.ResolverContext} instance.
// *
// * @param key the property key to be associated with the created context
// * @param bundleName the resource bundle name to be associated with the created context
// *
// * @return the newly created {@link com.byteslounge.cdi.resolver.context.ResolverContext} instance
// */
// public static ResolverContext create(String key, String bundleName) {
// return new ResolverContext(key, bundleName);
// }
//
// /**
// * Gets the key associated with this {@link com.byteslounge.cdi.resolver.context.ResolverContext} instance
// *
// * @return the key associated with this {@link com.byteslounge.cdi.resolver.context.ResolverContext} instance
// */
// public String getKey() {
// return key;
// }
//
// /**
// * Gets the resource bundle name associated with this {@link com.byteslounge.cdi.resolver.context.ResolverContext} instance
// *
// * @return the resource bundle name associated with this {@link com.byteslounge.cdi.resolver.context.ResolverContext} instance
// */
// public String getBundleName() {
// return bundleName;
// }
//
// /**
// * Sets the resolver bean associated with the current resolving execution
// *
// * @param resolverBean the property key to be associated with the created context
// */
// public void setResolverBean(Bean<?> resolverBean) {
// this.resolverBean = resolverBean;
// }
//
// /**
// * Gets the resolver bean associated with the current resolving execution
// *
// * @return the resolver bean associated with the current resolving execution
// */
// public Bean<?> getResolverBean() {
// return resolverBean;
// }
//
// /**
// * Gets the bean manager associated with the current resolving execution
// *
// * @return the bean manager associated with the current resolving execution
// */
// public BeanManager getBeanManager() {
// return beanManager;
// }
//
// /**
// * Sets the bean manager associated with the current resolving execution
// *
// * @param beanManager the bean manager associated with the current resolving execution
// */
// public void setBeanManager(BeanManager beanManager) {
// this.beanManager = beanManager;
// }
//
// }
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/extension/param/InjectableResolverParameter.java
import java.lang.annotation.Annotation;
import java.lang.reflect.Member;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Set;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Annotated;
import javax.enterprise.inject.spi.AnnotatedParameter;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.InjectionPoint;
import com.byteslounge.cdi.resolver.context.ResolverContext;
}
/**
* See {@link InjectionPoint#getType()}
*/
@Override
public Type getType() {
return parameter.getBaseType();
}
/**
* See {@link InjectionPoint#isDelegate()}
*/
@Override
public boolean isDelegate() {
return false;
}
/**
* See {@link InjectionPoint#isTransient()}
*/
@Override
public boolean isTransient() {
return false;
}
/**
* see {@link ResolverParameter#resolve(String, String, CreationalContext)}
*/
@Override | public <T> Object resolve(ResolverContext resolverContext, CreationalContext<T> ctx) { |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-wildfly82/src/test/java/com/byteslounge/cdi/test/it/WarProvidedLocaleMethodThreadLocalPTIT.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodThreadLocal.java
// public abstract class AbstractWarProvidedLocaleMethodThreadLocal {
//
// protected static WebArchive createArchive() throws IOException {
//
// WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses(
// ProvidedLocaleMethodResolverThreadLocal.class, OtherService.class, OtherServiceBean.class,
// TestServlet.class, LocaleThreadLocal.class);
// DeploymentAppenderFactory.create(webArchive)
// .appendWebXml("../cdi-properties-test-common/src/test/resources/assets/warCommon/WEB-INF/simpleWeb.xml")
// .appendWebResource("../cdi-properties-test-common/src/test/resources/assets/warCommon/webapp/test.jsp")
// .appendBeansXml()
// .appendCDIPropertiesLib()
// .appendLogging().appendProperties();
// return webArchive;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/utils/MessageBundleUtils.java
// public class MessageBundleUtils {
//
// private MessageBundleUtils() {
// }
//
// public static String resolveProperty(String key, String bundleName, Locale locale, Object... args) {
// String value = ResourceBundle.getBundle(bundleName, locale).getString(key);
// if (args != null && args.length > 0) {
// value = MessageFormat.format(value, args);
// }
// return value;
// }
//
// }
| import com.byteslounge.cdi.test.utils.MessageBundleUtils;
import java.io.IOException;
import java.net.URL;
import java.util.Locale;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import com.byteslounge.cdi.test.it.common.AbstractWarProvidedLocaleMethodThreadLocal; | /*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it;
/**
* Integration Test
*
* @author Gonçalo Marques
* @since 1.1.0
*/
@RunWith(Arquillian.class)
public class WarProvidedLocaleMethodThreadLocalPTIT extends AbstractWarProvidedLocaleMethodThreadLocal {
@Drone
private WebDriver browser;
@FindBy(id = "result")
private WebElement result;
@FindBy(id = "integer")
private WebElement integer;
@Deployment
public static WebArchive createArchive() throws IOException {
WebArchive webArchive = CommonWarProvidedLocaleMethodThreadLocalPT.createArchive();
return webArchive;
}
@Test
@RunAsClient
public void test(@ArquillianResource URL contextPath) {
browser.get(contextPath + "testservlet");
Assert.assertEquals(result.getText(), | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodThreadLocal.java
// public abstract class AbstractWarProvidedLocaleMethodThreadLocal {
//
// protected static WebArchive createArchive() throws IOException {
//
// WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses(
// ProvidedLocaleMethodResolverThreadLocal.class, OtherService.class, OtherServiceBean.class,
// TestServlet.class, LocaleThreadLocal.class);
// DeploymentAppenderFactory.create(webArchive)
// .appendWebXml("../cdi-properties-test-common/src/test/resources/assets/warCommon/WEB-INF/simpleWeb.xml")
// .appendWebResource("../cdi-properties-test-common/src/test/resources/assets/warCommon/webapp/test.jsp")
// .appendBeansXml()
// .appendCDIPropertiesLib()
// .appendLogging().appendProperties();
// return webArchive;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/utils/MessageBundleUtils.java
// public class MessageBundleUtils {
//
// private MessageBundleUtils() {
// }
//
// public static String resolveProperty(String key, String bundleName, Locale locale, Object... args) {
// String value = ResourceBundle.getBundle(bundleName, locale).getString(key);
// if (args != null && args.length > 0) {
// value = MessageFormat.format(value, args);
// }
// return value;
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-wildfly82/src/test/java/com/byteslounge/cdi/test/it/WarProvidedLocaleMethodThreadLocalPTIT.java
import com.byteslounge.cdi.test.utils.MessageBundleUtils;
import java.io.IOException;
import java.net.URL;
import java.util.Locale;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import com.byteslounge.cdi.test.it.common.AbstractWarProvidedLocaleMethodThreadLocal;
/*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it;
/**
* Integration Test
*
* @author Gonçalo Marques
* @since 1.1.0
*/
@RunWith(Arquillian.class)
public class WarProvidedLocaleMethodThreadLocalPTIT extends AbstractWarProvidedLocaleMethodThreadLocal {
@Drone
private WebDriver browser;
@FindBy(id = "result")
private WebElement result;
@FindBy(id = "integer")
private WebElement integer;
@Deployment
public static WebArchive createArchive() throws IOException {
WebArchive webArchive = CommonWarProvidedLocaleMethodThreadLocalPT.createArchive();
return webArchive;
}
@Test
@RunAsClient
public void test(@ArquillianResource URL contextPath) {
browser.get(contextPath + "testservlet");
Assert.assertEquals(result.getText(), | MessageBundleUtils.resolveProperty("hello.world", "bl.messages", new Locale("pt", "PT"))); |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/CommonWarProvidedLocaleMethodSession.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/filter/LocaleSessionFilter.java
// @WebFilter(urlPatterns = "/*")
// public class LocaleSessionFilter implements Filter {
//
// @Inject
// private UserSession userSession;
//
// @Override
// public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
// ServletException {
// userSession.setLocale(Locale.getDefault());
// chain.doFilter(request, response);
// }
//
// @Override
// public void init(FilterConfig config) throws ServletException {
// }
//
// @Override
// public void destroy() {
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodSession.java
// public abstract class AbstractWarProvidedLocaleMethodSession {
//
// protected static WebArchive createArchive() throws IOException {
//
// WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses(
// ProvidedLocaleMethodResolverSession.class, OtherService.class, OtherServiceBean.class,
// TestServlet.class, UserSession.class);
// DeploymentAppenderFactory.create(webArchive)
// .appendWebXml("../cdi-properties-test-common/src/test/resources/assets/warCommon/WEB-INF/simpleWeb.xml")
// .appendWebResource("../cdi-properties-test-common/src/test/resources/assets/warCommon/webapp/test.jsp")
// .appendCDIPropertiesLib()
// .appendBeansXml().appendLogging().appendProperties();
// return webArchive;
// }
//
// }
| import org.jboss.shrinkwrap.api.spec.WebArchive;
import com.byteslounge.cdi.test.common.filter.LocaleSessionFilter;
import com.byteslounge.cdi.test.it.common.AbstractWarProvidedLocaleMethodSession;
import java.io.IOException; | /*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it;
/**
* Integration Test
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public class CommonWarProvidedLocaleMethodSession extends AbstractWarProvidedLocaleMethodSession {
public static WebArchive createArchive() throws IOException {
WebArchive webArchive = AbstractWarProvidedLocaleMethodSession.createArchive().addClasses( | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/filter/LocaleSessionFilter.java
// @WebFilter(urlPatterns = "/*")
// public class LocaleSessionFilter implements Filter {
//
// @Inject
// private UserSession userSession;
//
// @Override
// public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
// ServletException {
// userSession.setLocale(Locale.getDefault());
// chain.doFilter(request, response);
// }
//
// @Override
// public void init(FilterConfig config) throws ServletException {
// }
//
// @Override
// public void destroy() {
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodSession.java
// public abstract class AbstractWarProvidedLocaleMethodSession {
//
// protected static WebArchive createArchive() throws IOException {
//
// WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses(
// ProvidedLocaleMethodResolverSession.class, OtherService.class, OtherServiceBean.class,
// TestServlet.class, UserSession.class);
// DeploymentAppenderFactory.create(webArchive)
// .appendWebXml("../cdi-properties-test-common/src/test/resources/assets/warCommon/WEB-INF/simpleWeb.xml")
// .appendWebResource("../cdi-properties-test-common/src/test/resources/assets/warCommon/webapp/test.jsp")
// .appendCDIPropertiesLib()
// .appendBeansXml().appendLogging().appendProperties();
// return webArchive;
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/CommonWarProvidedLocaleMethodSession.java
import org.jboss.shrinkwrap.api.spec.WebArchive;
import com.byteslounge.cdi.test.common.filter.LocaleSessionFilter;
import com.byteslounge.cdi.test.it.common.AbstractWarProvidedLocaleMethodSession;
import java.io.IOException;
/*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it;
/**
* Integration Test
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public class CommonWarProvidedLocaleMethodSession extends AbstractWarProvidedLocaleMethodSession {
public static WebArchive createArchive() throws IOException {
WebArchive webArchive = AbstractWarProvidedLocaleMethodSession.createArchive().addClasses( | LocaleSessionFilter.class); |
gonmarques/cdi-properties | cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/extractor/LocaleResolverParameterExtractor.java | // Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/extension/param/LocalePropertyResolverParameter.java
// public class LocalePropertyResolverParameter implements ResolverParameter<Locale> {
//
// private final ResolverBean<Locale> localeResolverBean;
//
// public LocalePropertyResolverParameter(ResolverBean<Locale> localResolverBean) {
// this.localeResolverBean = localResolverBean;
// }
//
// /**
// * see {@link ResolverParameter#resolve(String, String, CreationalContext)}
// */
// @Override
// public <T> Locale resolve(ResolverContext resolverContext, CreationalContext<T> ctx) {
// return localeResolverBean.invoke(resolverContext, ctx);
// }
//
// }
//
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/bean/ResolverBean.java
// public interface ResolverBean<T> {
//
// /**
// * Processes a CDI managed bean and checks if it defines an extension's resolver method
// *
// * @param at the CDI managed bean to check for an extension's resolver method
// */
// void process(AnnotatedType<?> at);
//
// /**
// * Initializes the extension's resolver method
// *
// * @param beanManager the CDI container Bean Manager
// */
// void initialize(BeanManager beanManager);
//
// /**
// * Invokes the extension's resolver method represented by this bean
// *
// * @param resolverContext the Resolver Context
// * @param ctx The CDI creational context
// *
// * @return the value returned by this extension's resolver method
// */
// T invoke(ResolverContext resolverContext, CreationalContext<?> ctx);
//
// }
| import com.byteslounge.cdi.annotation.PropertyLocale;
import com.byteslounge.cdi.extension.param.LocalePropertyResolverParameter;
import com.byteslounge.cdi.resolver.bean.ResolverBean;
import java.util.Locale; | /*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.resolver.extractor;
/**
* Represents the extractor for the Locale property resolver method parameter
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public class LocaleResolverParameterExtractor extends
ProvidedResolverParameterExtractor<LocalePropertyResolverParameter> {
| // Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/extension/param/LocalePropertyResolverParameter.java
// public class LocalePropertyResolverParameter implements ResolverParameter<Locale> {
//
// private final ResolverBean<Locale> localeResolverBean;
//
// public LocalePropertyResolverParameter(ResolverBean<Locale> localResolverBean) {
// this.localeResolverBean = localResolverBean;
// }
//
// /**
// * see {@link ResolverParameter#resolve(String, String, CreationalContext)}
// */
// @Override
// public <T> Locale resolve(ResolverContext resolverContext, CreationalContext<T> ctx) {
// return localeResolverBean.invoke(resolverContext, ctx);
// }
//
// }
//
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/bean/ResolverBean.java
// public interface ResolverBean<T> {
//
// /**
// * Processes a CDI managed bean and checks if it defines an extension's resolver method
// *
// * @param at the CDI managed bean to check for an extension's resolver method
// */
// void process(AnnotatedType<?> at);
//
// /**
// * Initializes the extension's resolver method
// *
// * @param beanManager the CDI container Bean Manager
// */
// void initialize(BeanManager beanManager);
//
// /**
// * Invokes the extension's resolver method represented by this bean
// *
// * @param resolverContext the Resolver Context
// * @param ctx The CDI creational context
// *
// * @return the value returned by this extension's resolver method
// */
// T invoke(ResolverContext resolverContext, CreationalContext<?> ctx);
//
// }
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/extractor/LocaleResolverParameterExtractor.java
import com.byteslounge.cdi.annotation.PropertyLocale;
import com.byteslounge.cdi.extension.param.LocalePropertyResolverParameter;
import com.byteslounge.cdi.resolver.bean.ResolverBean;
import java.util.Locale;
/*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.resolver.extractor;
/**
* Represents the extractor for the Locale property resolver method parameter
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public class LocaleResolverParameterExtractor extends
ProvidedResolverParameterExtractor<LocalePropertyResolverParameter> {
| public LocaleResolverParameterExtractor(ResolverBean<Locale> localeResolverBean) { |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ProvidedPropertyMethodResolver.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/ApplicationScopedBean.java
// @ApplicationScoped
// public class ApplicationScopedBean implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Inject
// private InjectedBean injectedBean;
//
// public String getText() {
// Assert.assertEquals(injectedBean.getText(), TestConstants.BEAN_TEST_RETURN_VALUE);
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/DependentScopedBean.java
// public class DependentScopedBean {
//
// @Inject
// private InjectedBean injectedBean;
//
// public String getText() {
// Assert.assertEquals(injectedBean.getText(), TestConstants.BEAN_TEST_RETURN_VALUE);
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
| import java.io.Serializable;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.enterprise.context.ApplicationScoped;
import org.junit.Assert;
import com.byteslounge.cdi.annotation.PropertyBundle;
import com.byteslounge.cdi.annotation.PropertyKey;
import com.byteslounge.cdi.annotation.PropertyLocale;
import com.byteslounge.cdi.annotation.PropertyResolver;
import com.byteslounge.cdi.test.common.ApplicationScopedBean;
import com.byteslounge.cdi.test.common.DependentScopedBean;
import com.byteslounge.cdi.test.configuration.TestConstants;
import com.byteslounge.cdi.test.model.TestEntity; | /*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.wpm;
@ApplicationScoped
public class ProvidedPropertyMethodResolver implements Serializable {
private static final long serialVersionUID = 1L;
// Lets provide a set of completely mixed up parameters in what matters to "logical" definition order
@PropertyResolver | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/ApplicationScopedBean.java
// @ApplicationScoped
// public class ApplicationScopedBean implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Inject
// private InjectedBean injectedBean;
//
// public String getText() {
// Assert.assertEquals(injectedBean.getText(), TestConstants.BEAN_TEST_RETURN_VALUE);
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/DependentScopedBean.java
// public class DependentScopedBean {
//
// @Inject
// private InjectedBean injectedBean;
//
// public String getText() {
// Assert.assertEquals(injectedBean.getText(), TestConstants.BEAN_TEST_RETURN_VALUE);
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ProvidedPropertyMethodResolver.java
import java.io.Serializable;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.enterprise.context.ApplicationScoped;
import org.junit.Assert;
import com.byteslounge.cdi.annotation.PropertyBundle;
import com.byteslounge.cdi.annotation.PropertyKey;
import com.byteslounge.cdi.annotation.PropertyLocale;
import com.byteslounge.cdi.annotation.PropertyResolver;
import com.byteslounge.cdi.test.common.ApplicationScopedBean;
import com.byteslounge.cdi.test.common.DependentScopedBean;
import com.byteslounge.cdi.test.configuration.TestConstants;
import com.byteslounge.cdi.test.model.TestEntity;
/*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.wpm;
@ApplicationScoped
public class ProvidedPropertyMethodResolver implements Serializable {
private static final long serialVersionUID = 1L;
// Lets provide a set of completely mixed up parameters in what matters to "logical" definition order
@PropertyResolver | public String resolveProperty(DependentScopedBean dependentScopedBean, |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ProvidedPropertyMethodResolver.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/ApplicationScopedBean.java
// @ApplicationScoped
// public class ApplicationScopedBean implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Inject
// private InjectedBean injectedBean;
//
// public String getText() {
// Assert.assertEquals(injectedBean.getText(), TestConstants.BEAN_TEST_RETURN_VALUE);
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/DependentScopedBean.java
// public class DependentScopedBean {
//
// @Inject
// private InjectedBean injectedBean;
//
// public String getText() {
// Assert.assertEquals(injectedBean.getText(), TestConstants.BEAN_TEST_RETURN_VALUE);
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
| import java.io.Serializable;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.enterprise.context.ApplicationScoped;
import org.junit.Assert;
import com.byteslounge.cdi.annotation.PropertyBundle;
import com.byteslounge.cdi.annotation.PropertyKey;
import com.byteslounge.cdi.annotation.PropertyLocale;
import com.byteslounge.cdi.annotation.PropertyResolver;
import com.byteslounge.cdi.test.common.ApplicationScopedBean;
import com.byteslounge.cdi.test.common.DependentScopedBean;
import com.byteslounge.cdi.test.configuration.TestConstants;
import com.byteslounge.cdi.test.model.TestEntity; | /*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.wpm;
@ApplicationScoped
public class ProvidedPropertyMethodResolver implements Serializable {
private static final long serialVersionUID = 1L;
// Lets provide a set of completely mixed up parameters in what matters to "logical" definition order
@PropertyResolver
public String resolveProperty(DependentScopedBean dependentScopedBean,
RequestScopedBean requestScopedBean, SessionScopedBean sessionScopedBean,
@PropertyBundle String bundleName, @PropertyLocale Locale locale, | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/ApplicationScopedBean.java
// @ApplicationScoped
// public class ApplicationScopedBean implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Inject
// private InjectedBean injectedBean;
//
// public String getText() {
// Assert.assertEquals(injectedBean.getText(), TestConstants.BEAN_TEST_RETURN_VALUE);
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/DependentScopedBean.java
// public class DependentScopedBean {
//
// @Inject
// private InjectedBean injectedBean;
//
// public String getText() {
// Assert.assertEquals(injectedBean.getText(), TestConstants.BEAN_TEST_RETURN_VALUE);
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ProvidedPropertyMethodResolver.java
import java.io.Serializable;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.enterprise.context.ApplicationScoped;
import org.junit.Assert;
import com.byteslounge.cdi.annotation.PropertyBundle;
import com.byteslounge.cdi.annotation.PropertyKey;
import com.byteslounge.cdi.annotation.PropertyLocale;
import com.byteslounge.cdi.annotation.PropertyResolver;
import com.byteslounge.cdi.test.common.ApplicationScopedBean;
import com.byteslounge.cdi.test.common.DependentScopedBean;
import com.byteslounge.cdi.test.configuration.TestConstants;
import com.byteslounge.cdi.test.model.TestEntity;
/*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.wpm;
@ApplicationScoped
public class ProvidedPropertyMethodResolver implements Serializable {
private static final long serialVersionUID = 1L;
// Lets provide a set of completely mixed up parameters in what matters to "logical" definition order
@PropertyResolver
public String resolveProperty(DependentScopedBean dependentScopedBean,
RequestScopedBean requestScopedBean, SessionScopedBean sessionScopedBean,
@PropertyBundle String bundleName, @PropertyLocale Locale locale, | ApplicationScopedBean applicationScopedBean, @PropertyKey String key, Service service) { |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ProvidedPropertyMethodResolver.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/ApplicationScopedBean.java
// @ApplicationScoped
// public class ApplicationScopedBean implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Inject
// private InjectedBean injectedBean;
//
// public String getText() {
// Assert.assertEquals(injectedBean.getText(), TestConstants.BEAN_TEST_RETURN_VALUE);
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/DependentScopedBean.java
// public class DependentScopedBean {
//
// @Inject
// private InjectedBean injectedBean;
//
// public String getText() {
// Assert.assertEquals(injectedBean.getText(), TestConstants.BEAN_TEST_RETURN_VALUE);
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
| import java.io.Serializable;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.enterprise.context.ApplicationScoped;
import org.junit.Assert;
import com.byteslounge.cdi.annotation.PropertyBundle;
import com.byteslounge.cdi.annotation.PropertyKey;
import com.byteslounge.cdi.annotation.PropertyLocale;
import com.byteslounge.cdi.annotation.PropertyResolver;
import com.byteslounge.cdi.test.common.ApplicationScopedBean;
import com.byteslounge.cdi.test.common.DependentScopedBean;
import com.byteslounge.cdi.test.configuration.TestConstants;
import com.byteslounge.cdi.test.model.TestEntity; | /*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.wpm;
@ApplicationScoped
public class ProvidedPropertyMethodResolver implements Serializable {
private static final long serialVersionUID = 1L;
// Lets provide a set of completely mixed up parameters in what matters to "logical" definition order
@PropertyResolver
public String resolveProperty(DependentScopedBean dependentScopedBean,
RequestScopedBean requestScopedBean, SessionScopedBean sessionScopedBean,
@PropertyBundle String bundleName, @PropertyLocale Locale locale,
ApplicationScopedBean applicationScopedBean, @PropertyKey String key, Service service) {
service.remove(1L); | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/ApplicationScopedBean.java
// @ApplicationScoped
// public class ApplicationScopedBean implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Inject
// private InjectedBean injectedBean;
//
// public String getText() {
// Assert.assertEquals(injectedBean.getText(), TestConstants.BEAN_TEST_RETURN_VALUE);
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/DependentScopedBean.java
// public class DependentScopedBean {
//
// @Inject
// private InjectedBean injectedBean;
//
// public String getText() {
// Assert.assertEquals(injectedBean.getText(), TestConstants.BEAN_TEST_RETURN_VALUE);
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ProvidedPropertyMethodResolver.java
import java.io.Serializable;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.enterprise.context.ApplicationScoped;
import org.junit.Assert;
import com.byteslounge.cdi.annotation.PropertyBundle;
import com.byteslounge.cdi.annotation.PropertyKey;
import com.byteslounge.cdi.annotation.PropertyLocale;
import com.byteslounge.cdi.annotation.PropertyResolver;
import com.byteslounge.cdi.test.common.ApplicationScopedBean;
import com.byteslounge.cdi.test.common.DependentScopedBean;
import com.byteslounge.cdi.test.configuration.TestConstants;
import com.byteslounge.cdi.test.model.TestEntity;
/*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.wpm;
@ApplicationScoped
public class ProvidedPropertyMethodResolver implements Serializable {
private static final long serialVersionUID = 1L;
// Lets provide a set of completely mixed up parameters in what matters to "logical" definition order
@PropertyResolver
public String resolveProperty(DependentScopedBean dependentScopedBean,
RequestScopedBean requestScopedBean, SessionScopedBean sessionScopedBean,
@PropertyBundle String bundleName, @PropertyLocale Locale locale,
ApplicationScopedBean applicationScopedBean, @PropertyKey String key, Service service) {
service.remove(1L); | TestEntity testEntity = new TestEntity(); |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ProvidedPropertyMethodResolver.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/ApplicationScopedBean.java
// @ApplicationScoped
// public class ApplicationScopedBean implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Inject
// private InjectedBean injectedBean;
//
// public String getText() {
// Assert.assertEquals(injectedBean.getText(), TestConstants.BEAN_TEST_RETURN_VALUE);
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/DependentScopedBean.java
// public class DependentScopedBean {
//
// @Inject
// private InjectedBean injectedBean;
//
// public String getText() {
// Assert.assertEquals(injectedBean.getText(), TestConstants.BEAN_TEST_RETURN_VALUE);
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
| import java.io.Serializable;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.enterprise.context.ApplicationScoped;
import org.junit.Assert;
import com.byteslounge.cdi.annotation.PropertyBundle;
import com.byteslounge.cdi.annotation.PropertyKey;
import com.byteslounge.cdi.annotation.PropertyLocale;
import com.byteslounge.cdi.annotation.PropertyResolver;
import com.byteslounge.cdi.test.common.ApplicationScopedBean;
import com.byteslounge.cdi.test.common.DependentScopedBean;
import com.byteslounge.cdi.test.configuration.TestConstants;
import com.byteslounge.cdi.test.model.TestEntity; | /*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.wpm;
@ApplicationScoped
public class ProvidedPropertyMethodResolver implements Serializable {
private static final long serialVersionUID = 1L;
// Lets provide a set of completely mixed up parameters in what matters to "logical" definition order
@PropertyResolver
public String resolveProperty(DependentScopedBean dependentScopedBean,
RequestScopedBean requestScopedBean, SessionScopedBean sessionScopedBean,
@PropertyBundle String bundleName, @PropertyLocale Locale locale,
ApplicationScopedBean applicationScopedBean, @PropertyKey String key, Service service) {
service.remove(1L);
TestEntity testEntity = new TestEntity();
testEntity.setId(1L);
testEntity.setDescription("Description");
testEntity = service.merge(testEntity);
TestEntity other = service.findById(1L);
Assert.assertEquals(new Long(1L), other.getId());
| // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/ApplicationScopedBean.java
// @ApplicationScoped
// public class ApplicationScopedBean implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Inject
// private InjectedBean injectedBean;
//
// public String getText() {
// Assert.assertEquals(injectedBean.getText(), TestConstants.BEAN_TEST_RETURN_VALUE);
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/DependentScopedBean.java
// public class DependentScopedBean {
//
// @Inject
// private InjectedBean injectedBean;
//
// public String getText() {
// Assert.assertEquals(injectedBean.getText(), TestConstants.BEAN_TEST_RETURN_VALUE);
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ProvidedPropertyMethodResolver.java
import java.io.Serializable;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.enterprise.context.ApplicationScoped;
import org.junit.Assert;
import com.byteslounge.cdi.annotation.PropertyBundle;
import com.byteslounge.cdi.annotation.PropertyKey;
import com.byteslounge.cdi.annotation.PropertyLocale;
import com.byteslounge.cdi.annotation.PropertyResolver;
import com.byteslounge.cdi.test.common.ApplicationScopedBean;
import com.byteslounge.cdi.test.common.DependentScopedBean;
import com.byteslounge.cdi.test.configuration.TestConstants;
import com.byteslounge.cdi.test.model.TestEntity;
/*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.wpm;
@ApplicationScoped
public class ProvidedPropertyMethodResolver implements Serializable {
private static final long serialVersionUID = 1L;
// Lets provide a set of completely mixed up parameters in what matters to "logical" definition order
@PropertyResolver
public String resolveProperty(DependentScopedBean dependentScopedBean,
RequestScopedBean requestScopedBean, SessionScopedBean sessionScopedBean,
@PropertyBundle String bundleName, @PropertyLocale Locale locale,
ApplicationScopedBean applicationScopedBean, @PropertyKey String key, Service service) {
service.remove(1L);
TestEntity testEntity = new TestEntity();
testEntity.setId(1L);
testEntity.setDescription("Description");
testEntity = service.merge(testEntity);
TestEntity other = service.findById(1L);
Assert.assertEquals(new Long(1L), other.getId());
| Assert.assertEquals(dependentScopedBean.getText(), TestConstants.BEAN_TEST_RETURN_VALUE); |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/CommonWarProvidedLocaleMethodThreadLocal.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/filter/LocaleFilter.java
// @WebFilter(urlPatterns = "/*")
// public class LocaleFilter implements Filter {
//
// @Override
// public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
// ServletException {
// try {
// LocaleThreadLocal.localeThreadLocal.set(new LocaleThreadLocal(Locale.getDefault()));
// chain.doFilter(request, response);
// } finally {
// LocaleThreadLocal.localeThreadLocal.remove();
// }
// }
//
// @Override
// public void init(FilterConfig config) throws ServletException {
// }
//
// @Override
// public void destroy() {
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodThreadLocal.java
// public abstract class AbstractWarProvidedLocaleMethodThreadLocal {
//
// protected static WebArchive createArchive() throws IOException {
//
// WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses(
// ProvidedLocaleMethodResolverThreadLocal.class, OtherService.class, OtherServiceBean.class,
// TestServlet.class, LocaleThreadLocal.class);
// DeploymentAppenderFactory.create(webArchive)
// .appendWebXml("../cdi-properties-test-common/src/test/resources/assets/warCommon/WEB-INF/simpleWeb.xml")
// .appendWebResource("../cdi-properties-test-common/src/test/resources/assets/warCommon/webapp/test.jsp")
// .appendBeansXml()
// .appendCDIPropertiesLib()
// .appendLogging().appendProperties();
// return webArchive;
// }
//
// }
| import org.jboss.shrinkwrap.api.spec.WebArchive;
import com.byteslounge.cdi.test.common.filter.LocaleFilter;
import com.byteslounge.cdi.test.it.common.AbstractWarProvidedLocaleMethodThreadLocal;
import java.io.IOException; | /*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it;
/**
* Integration Test
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public class CommonWarProvidedLocaleMethodThreadLocal extends AbstractWarProvidedLocaleMethodThreadLocal {
public static WebArchive createArchive() throws IOException {
WebArchive webArchive = AbstractWarProvidedLocaleMethodThreadLocal.createArchive().addClasses( | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/filter/LocaleFilter.java
// @WebFilter(urlPatterns = "/*")
// public class LocaleFilter implements Filter {
//
// @Override
// public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
// ServletException {
// try {
// LocaleThreadLocal.localeThreadLocal.set(new LocaleThreadLocal(Locale.getDefault()));
// chain.doFilter(request, response);
// } finally {
// LocaleThreadLocal.localeThreadLocal.remove();
// }
// }
//
// @Override
// public void init(FilterConfig config) throws ServletException {
// }
//
// @Override
// public void destroy() {
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodThreadLocal.java
// public abstract class AbstractWarProvidedLocaleMethodThreadLocal {
//
// protected static WebArchive createArchive() throws IOException {
//
// WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses(
// ProvidedLocaleMethodResolverThreadLocal.class, OtherService.class, OtherServiceBean.class,
// TestServlet.class, LocaleThreadLocal.class);
// DeploymentAppenderFactory.create(webArchive)
// .appendWebXml("../cdi-properties-test-common/src/test/resources/assets/warCommon/WEB-INF/simpleWeb.xml")
// .appendWebResource("../cdi-properties-test-common/src/test/resources/assets/warCommon/webapp/test.jsp")
// .appendBeansXml()
// .appendCDIPropertiesLib()
// .appendLogging().appendProperties();
// return webArchive;
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/CommonWarProvidedLocaleMethodThreadLocal.java
import org.jboss.shrinkwrap.api.spec.WebArchive;
import com.byteslounge.cdi.test.common.filter.LocaleFilter;
import com.byteslounge.cdi.test.it.common.AbstractWarProvidedLocaleMethodThreadLocal;
import java.io.IOException;
/*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it;
/**
* Integration Test
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public class CommonWarProvidedLocaleMethodThreadLocal extends AbstractWarProvidedLocaleMethodThreadLocal {
public static WebArchive createArchive() throws IOException {
WebArchive webArchive = AbstractWarProvidedLocaleMethodThreadLocal.createArchive().addClasses( | LocaleFilter.class); |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ServiceBean.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/InjectedBean.java
// public class InjectedBean implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// public String getText() {
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
| import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.Assert;
import com.byteslounge.cdi.test.common.InjectedBean;
import com.byteslounge.cdi.test.configuration.TestConstants;
import com.byteslounge.cdi.test.model.TestEntity; | /*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.wpm;
/**
* Used in CDI Properties integration tests. See WarDefaultMethodIT.java,
* WarProvidedMethodIT.java, EjbDefaultMethodIT.java and
* EjbProvidedMethodIT.java.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
@Stateless
public class ServiceBean implements Service {
private static final long serialVersionUID = 1L;
@PersistenceContext
private EntityManager entityManager;
@Inject | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/InjectedBean.java
// public class InjectedBean implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// public String getText() {
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ServiceBean.java
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.Assert;
import com.byteslounge.cdi.test.common.InjectedBean;
import com.byteslounge.cdi.test.configuration.TestConstants;
import com.byteslounge.cdi.test.model.TestEntity;
/*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.wpm;
/**
* Used in CDI Properties integration tests. See WarDefaultMethodIT.java,
* WarProvidedMethodIT.java, EjbDefaultMethodIT.java and
* EjbProvidedMethodIT.java.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
@Stateless
public class ServiceBean implements Service {
private static final long serialVersionUID = 1L;
@PersistenceContext
private EntityManager entityManager;
@Inject | private InjectedBean injectedBean; |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ServiceBean.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/InjectedBean.java
// public class InjectedBean implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// public String getText() {
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
| import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.Assert;
import com.byteslounge.cdi.test.common.InjectedBean;
import com.byteslounge.cdi.test.configuration.TestConstants;
import com.byteslounge.cdi.test.model.TestEntity; | /*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.wpm;
/**
* Used in CDI Properties integration tests. See WarDefaultMethodIT.java,
* WarProvidedMethodIT.java, EjbDefaultMethodIT.java and
* EjbProvidedMethodIT.java.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
@Stateless
public class ServiceBean implements Service {
private static final long serialVersionUID = 1L;
@PersistenceContext
private EntityManager entityManager;
@Inject
private InjectedBean injectedBean;
@Override
public String getText() { | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/InjectedBean.java
// public class InjectedBean implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// public String getText() {
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ServiceBean.java
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.Assert;
import com.byteslounge.cdi.test.common.InjectedBean;
import com.byteslounge.cdi.test.configuration.TestConstants;
import com.byteslounge.cdi.test.model.TestEntity;
/*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.wpm;
/**
* Used in CDI Properties integration tests. See WarDefaultMethodIT.java,
* WarProvidedMethodIT.java, EjbDefaultMethodIT.java and
* EjbProvidedMethodIT.java.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
@Stateless
public class ServiceBean implements Service {
private static final long serialVersionUID = 1L;
@PersistenceContext
private EntityManager entityManager;
@Inject
private InjectedBean injectedBean;
@Override
public String getText() { | Assert.assertEquals(injectedBean.getText(), TestConstants.BEAN_TEST_RETURN_VALUE); |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ServiceBean.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/InjectedBean.java
// public class InjectedBean implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// public String getText() {
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
| import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.Assert;
import com.byteslounge.cdi.test.common.InjectedBean;
import com.byteslounge.cdi.test.configuration.TestConstants;
import com.byteslounge.cdi.test.model.TestEntity; | /*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.wpm;
/**
* Used in CDI Properties integration tests. See WarDefaultMethodIT.java,
* WarProvidedMethodIT.java, EjbDefaultMethodIT.java and
* EjbProvidedMethodIT.java.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
@Stateless
public class ServiceBean implements Service {
private static final long serialVersionUID = 1L;
@PersistenceContext
private EntityManager entityManager;
@Inject
private InjectedBean injectedBean;
@Override
public String getText() {
Assert.assertEquals(injectedBean.getText(), TestConstants.BEAN_TEST_RETURN_VALUE);
return TestConstants.BEAN_TEST_RETURN_VALUE;
}
@Override | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/InjectedBean.java
// public class InjectedBean implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// public String getText() {
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ServiceBean.java
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.Assert;
import com.byteslounge.cdi.test.common.InjectedBean;
import com.byteslounge.cdi.test.configuration.TestConstants;
import com.byteslounge.cdi.test.model.TestEntity;
/*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.wpm;
/**
* Used in CDI Properties integration tests. See WarDefaultMethodIT.java,
* WarProvidedMethodIT.java, EjbDefaultMethodIT.java and
* EjbProvidedMethodIT.java.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
@Stateless
public class ServiceBean implements Service {
private static final long serialVersionUID = 1L;
@PersistenceContext
private EntityManager entityManager;
@Inject
private InjectedBean injectedBean;
@Override
public String getText() {
Assert.assertEquals(injectedBean.getText(), TestConstants.BEAN_TEST_RETURN_VALUE);
return TestConstants.BEAN_TEST_RETURN_VALUE;
}
@Override | public TestEntity merge(TestEntity testEntity) { |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-wildfly82/src/test/java/com/byteslounge/cdi/test/it/WarProvidedLocaleMethodThreadLocalIT.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodThreadLocal.java
// public abstract class AbstractWarProvidedLocaleMethodThreadLocal {
//
// protected static WebArchive createArchive() throws IOException {
//
// WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses(
// ProvidedLocaleMethodResolverThreadLocal.class, OtherService.class, OtherServiceBean.class,
// TestServlet.class, LocaleThreadLocal.class);
// DeploymentAppenderFactory.create(webArchive)
// .appendWebXml("../cdi-properties-test-common/src/test/resources/assets/warCommon/WEB-INF/simpleWeb.xml")
// .appendWebResource("../cdi-properties-test-common/src/test/resources/assets/warCommon/webapp/test.jsp")
// .appendBeansXml()
// .appendCDIPropertiesLib()
// .appendLogging().appendProperties();
// return webArchive;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/utils/MessageBundleUtils.java
// public class MessageBundleUtils {
//
// private MessageBundleUtils() {
// }
//
// public static String resolveProperty(String key, String bundleName, Locale locale, Object... args) {
// String value = ResourceBundle.getBundle(bundleName, locale).getString(key);
// if (args != null && args.length > 0) {
// value = MessageFormat.format(value, args);
// }
// return value;
// }
//
// }
| import com.byteslounge.cdi.test.utils.MessageBundleUtils;
import java.io.IOException;
import java.net.URL;
import java.util.Locale;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import com.byteslounge.cdi.test.it.common.AbstractWarProvidedLocaleMethodThreadLocal; | /*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it;
/**
* Integration Test
*
* @author Gonçalo Marques
* @since 1.1.0
*/
@RunWith(Arquillian.class)
public class WarProvidedLocaleMethodThreadLocalIT extends AbstractWarProvidedLocaleMethodThreadLocal {
@Drone
private WebDriver browser;
@FindBy(id = "result")
private WebElement result;
@FindBy(id = "integer")
private WebElement integer;
@Deployment
public static WebArchive createArchive() throws IOException {
WebArchive webArchive = CommonWarProvidedLocaleMethodThreadLocal.createArchive();
return webArchive;
}
@Test
@RunAsClient
public void test(@ArquillianResource URL contextPath) {
browser.get(contextPath + "testservlet");
Assert.assertEquals(result.getText(), | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodThreadLocal.java
// public abstract class AbstractWarProvidedLocaleMethodThreadLocal {
//
// protected static WebArchive createArchive() throws IOException {
//
// WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses(
// ProvidedLocaleMethodResolverThreadLocal.class, OtherService.class, OtherServiceBean.class,
// TestServlet.class, LocaleThreadLocal.class);
// DeploymentAppenderFactory.create(webArchive)
// .appendWebXml("../cdi-properties-test-common/src/test/resources/assets/warCommon/WEB-INF/simpleWeb.xml")
// .appendWebResource("../cdi-properties-test-common/src/test/resources/assets/warCommon/webapp/test.jsp")
// .appendBeansXml()
// .appendCDIPropertiesLib()
// .appendLogging().appendProperties();
// return webArchive;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/utils/MessageBundleUtils.java
// public class MessageBundleUtils {
//
// private MessageBundleUtils() {
// }
//
// public static String resolveProperty(String key, String bundleName, Locale locale, Object... args) {
// String value = ResourceBundle.getBundle(bundleName, locale).getString(key);
// if (args != null && args.length > 0) {
// value = MessageFormat.format(value, args);
// }
// return value;
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-wildfly82/src/test/java/com/byteslounge/cdi/test/it/WarProvidedLocaleMethodThreadLocalIT.java
import com.byteslounge.cdi.test.utils.MessageBundleUtils;
import java.io.IOException;
import java.net.URL;
import java.util.Locale;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import com.byteslounge.cdi.test.it.common.AbstractWarProvidedLocaleMethodThreadLocal;
/*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it;
/**
* Integration Test
*
* @author Gonçalo Marques
* @since 1.1.0
*/
@RunWith(Arquillian.class)
public class WarProvidedLocaleMethodThreadLocalIT extends AbstractWarProvidedLocaleMethodThreadLocal {
@Drone
private WebDriver browser;
@FindBy(id = "result")
private WebElement result;
@FindBy(id = "integer")
private WebElement integer;
@Deployment
public static WebArchive createArchive() throws IOException {
WebArchive webArchive = CommonWarProvidedLocaleMethodThreadLocal.createArchive();
return webArchive;
}
@Test
@RunAsClient
public void test(@ArquillianResource URL contextPath) {
browser.get(contextPath + "testservlet");
Assert.assertEquals(result.getText(), | MessageBundleUtils.resolveProperty("hello.world", "bl.messages", Locale.getDefault())); |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/filter/LocaleSessionFilterPT.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/session/UserSession.java
// @SessionScoped
// public class UserSession implements Serializable {
//
// private static final long serialVersionUID = 1L;
// private Locale locale;
//
// public Locale getLocale() {
// return locale;
// }
//
// public void setLocale(Locale locale) {
// this.locale = locale;
// }
//
// }
| import java.io.IOException;
import java.util.Locale;
import javax.inject.Inject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import com.byteslounge.cdi.test.common.session.UserSession; | /*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.common.filter;
/**
* Filter that sets the current session locale as PT
*
* @author Gonçalo Marques
* @since 1.1.0
*/
@WebFilter(urlPatterns = "/*")
public class LocaleSessionFilterPT implements Filter {
@Inject | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/session/UserSession.java
// @SessionScoped
// public class UserSession implements Serializable {
//
// private static final long serialVersionUID = 1L;
// private Locale locale;
//
// public Locale getLocale() {
// return locale;
// }
//
// public void setLocale(Locale locale) {
// this.locale = locale;
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/filter/LocaleSessionFilterPT.java
import java.io.IOException;
import java.util.Locale;
import javax.inject.Inject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import com.byteslounge.cdi.test.common.session.UserSession;
/*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.common.filter;
/**
* Filter that sets the current session locale as PT
*
* @author Gonçalo Marques
* @since 1.1.0
*/
@WebFilter(urlPatterns = "/*")
public class LocaleSessionFilterPT implements Filter {
@Inject | private UserSession userSession; |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/CommonWarProvidedLocaleMethodSessionPT.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/filter/LocaleSessionFilterPT.java
// @WebFilter(urlPatterns = "/*")
// public class LocaleSessionFilterPT implements Filter {
//
// @Inject
// private UserSession userSession;
//
// @Override
// public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
// ServletException {
// userSession.setLocale(new Locale("pt", "PT"));
// chain.doFilter(request, response);
// }
//
// @Override
// public void init(FilterConfig config) throws ServletException {
// }
//
// @Override
// public void destroy() {
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodSession.java
// public abstract class AbstractWarProvidedLocaleMethodSession {
//
// protected static WebArchive createArchive() throws IOException {
//
// WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses(
// ProvidedLocaleMethodResolverSession.class, OtherService.class, OtherServiceBean.class,
// TestServlet.class, UserSession.class);
// DeploymentAppenderFactory.create(webArchive)
// .appendWebXml("../cdi-properties-test-common/src/test/resources/assets/warCommon/WEB-INF/simpleWeb.xml")
// .appendWebResource("../cdi-properties-test-common/src/test/resources/assets/warCommon/webapp/test.jsp")
// .appendCDIPropertiesLib()
// .appendBeansXml().appendLogging().appendProperties();
// return webArchive;
// }
//
// }
| import org.jboss.shrinkwrap.api.spec.WebArchive;
import com.byteslounge.cdi.test.common.filter.LocaleSessionFilterPT;
import com.byteslounge.cdi.test.it.common.AbstractWarProvidedLocaleMethodSession;
import java.io.IOException; | /*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it;
/**
* Integration Test
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public class CommonWarProvidedLocaleMethodSessionPT extends AbstractWarProvidedLocaleMethodSession {
public static WebArchive createArchive() throws IOException {
WebArchive webArchive = AbstractWarProvidedLocaleMethodSession.createArchive().addClasses( | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/filter/LocaleSessionFilterPT.java
// @WebFilter(urlPatterns = "/*")
// public class LocaleSessionFilterPT implements Filter {
//
// @Inject
// private UserSession userSession;
//
// @Override
// public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
// ServletException {
// userSession.setLocale(new Locale("pt", "PT"));
// chain.doFilter(request, response);
// }
//
// @Override
// public void init(FilterConfig config) throws ServletException {
// }
//
// @Override
// public void destroy() {
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodSession.java
// public abstract class AbstractWarProvidedLocaleMethodSession {
//
// protected static WebArchive createArchive() throws IOException {
//
// WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses(
// ProvidedLocaleMethodResolverSession.class, OtherService.class, OtherServiceBean.class,
// TestServlet.class, UserSession.class);
// DeploymentAppenderFactory.create(webArchive)
// .appendWebXml("../cdi-properties-test-common/src/test/resources/assets/warCommon/WEB-INF/simpleWeb.xml")
// .appendWebResource("../cdi-properties-test-common/src/test/resources/assets/warCommon/webapp/test.jsp")
// .appendCDIPropertiesLib()
// .appendBeansXml().appendLogging().appendProperties();
// return webArchive;
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/CommonWarProvidedLocaleMethodSessionPT.java
import org.jboss.shrinkwrap.api.spec.WebArchive;
import com.byteslounge.cdi.test.common.filter.LocaleSessionFilterPT;
import com.byteslounge.cdi.test.it.common.AbstractWarProvidedLocaleMethodSession;
import java.io.IOException;
/*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it;
/**
* Integration Test
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public class CommonWarProvidedLocaleMethodSessionPT extends AbstractWarProvidedLocaleMethodSession {
public static WebArchive createArchive() throws IOException {
WebArchive webArchive = AbstractWarProvidedLocaleMethodSession.createArchive().addClasses( | LocaleSessionFilterPT.class); |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodSession.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/servlet/TestServlet.java
// @WebServlet(urlPatterns = "/testservlet")
// public class TestServlet extends HttpServlet {
//
// private static final long serialVersionUID = 1L;
//
// @EJB
// private OtherService otherService;
//
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Assert.assertEquals(Integer.class, otherService.getInteger().getClass());
// Assert.assertEquals(new Integer(2), otherService.getInteger());
// req.setAttribute("result", otherService.getText());
// req.setAttribute("integer", otherService.getInteger());
// req.getRequestDispatcher("test.jsp").forward(req, resp);
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/session/UserSession.java
// @SessionScoped
// public class UserSession implements Serializable {
//
// private static final long serialVersionUID = 1L;
// private Locale locale;
//
// public Locale getLocale() {
// return locale;
// }
//
// public void setLocale(Locale locale) {
// this.locale = locale;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/IntegrationTestDeploymentUtils.java
// public static class DeploymentAppenderFactory {
//
// private DeploymentAppenderFactory() {
// }
//
// public static WebDeploymentAppender create(WebArchive archive) {
// return new WebDeploymentAppender(archive);
// }
//
// public static JavaDeploymentAppender create(JavaArchive archive) {
// return new JavaDeploymentAppender(archive);
// }
//
// public static EnterpriseDeploymentAppender create(EnterpriseArchive archive) {
// return new EnterpriseDeploymentAppender(archive);
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherService.java
// @Local
// public interface OtherService extends Serializable {
//
// String getText();
//
// Integer getInteger();
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherServiceBean.java
// @Stateless
// public class OtherServiceBean implements OtherService {
//
// private static final long serialVersionUID = 1L;
//
// @Property("hello.world")
// private String text;
//
// @Property("some.integer")
// private Integer integer;
//
// @Override
// public String getText() {
// return text;
// }
//
// @Override
// public Integer getInteger() {
// return integer;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ProvidedLocaleMethodResolverSession.java
// @ApplicationScoped
// public class ProvidedLocaleMethodResolverSession implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @LocaleResolver
// public Locale resolveLocale(UserSession userSession) {
// return userSession.getLocale();
// }
//
// }
| import java.io.IOException;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import com.byteslounge.cdi.test.common.servlet.TestServlet;
import com.byteslounge.cdi.test.common.session.UserSession;
import com.byteslounge.cdi.test.it.common.IntegrationTestDeploymentUtils.DeploymentAppenderFactory;
import com.byteslounge.cdi.test.wpm.OtherService;
import com.byteslounge.cdi.test.wpm.OtherServiceBean;
import com.byteslounge.cdi.test.wpm.ProvidedLocaleMethodResolverSession; | /*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it.common;
/**
* Base class for Integration Tests which resolve the current locale from the user session
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public abstract class AbstractWarProvidedLocaleMethodSession {
protected static WebArchive createArchive() throws IOException {
WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses( | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/servlet/TestServlet.java
// @WebServlet(urlPatterns = "/testservlet")
// public class TestServlet extends HttpServlet {
//
// private static final long serialVersionUID = 1L;
//
// @EJB
// private OtherService otherService;
//
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Assert.assertEquals(Integer.class, otherService.getInteger().getClass());
// Assert.assertEquals(new Integer(2), otherService.getInteger());
// req.setAttribute("result", otherService.getText());
// req.setAttribute("integer", otherService.getInteger());
// req.getRequestDispatcher("test.jsp").forward(req, resp);
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/session/UserSession.java
// @SessionScoped
// public class UserSession implements Serializable {
//
// private static final long serialVersionUID = 1L;
// private Locale locale;
//
// public Locale getLocale() {
// return locale;
// }
//
// public void setLocale(Locale locale) {
// this.locale = locale;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/IntegrationTestDeploymentUtils.java
// public static class DeploymentAppenderFactory {
//
// private DeploymentAppenderFactory() {
// }
//
// public static WebDeploymentAppender create(WebArchive archive) {
// return new WebDeploymentAppender(archive);
// }
//
// public static JavaDeploymentAppender create(JavaArchive archive) {
// return new JavaDeploymentAppender(archive);
// }
//
// public static EnterpriseDeploymentAppender create(EnterpriseArchive archive) {
// return new EnterpriseDeploymentAppender(archive);
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherService.java
// @Local
// public interface OtherService extends Serializable {
//
// String getText();
//
// Integer getInteger();
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherServiceBean.java
// @Stateless
// public class OtherServiceBean implements OtherService {
//
// private static final long serialVersionUID = 1L;
//
// @Property("hello.world")
// private String text;
//
// @Property("some.integer")
// private Integer integer;
//
// @Override
// public String getText() {
// return text;
// }
//
// @Override
// public Integer getInteger() {
// return integer;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ProvidedLocaleMethodResolverSession.java
// @ApplicationScoped
// public class ProvidedLocaleMethodResolverSession implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @LocaleResolver
// public Locale resolveLocale(UserSession userSession) {
// return userSession.getLocale();
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodSession.java
import java.io.IOException;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import com.byteslounge.cdi.test.common.servlet.TestServlet;
import com.byteslounge.cdi.test.common.session.UserSession;
import com.byteslounge.cdi.test.it.common.IntegrationTestDeploymentUtils.DeploymentAppenderFactory;
import com.byteslounge.cdi.test.wpm.OtherService;
import com.byteslounge.cdi.test.wpm.OtherServiceBean;
import com.byteslounge.cdi.test.wpm.ProvidedLocaleMethodResolverSession;
/*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it.common;
/**
* Base class for Integration Tests which resolve the current locale from the user session
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public abstract class AbstractWarProvidedLocaleMethodSession {
protected static WebArchive createArchive() throws IOException {
WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses( | ProvidedLocaleMethodResolverSession.class, OtherService.class, OtherServiceBean.class, |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodSession.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/servlet/TestServlet.java
// @WebServlet(urlPatterns = "/testservlet")
// public class TestServlet extends HttpServlet {
//
// private static final long serialVersionUID = 1L;
//
// @EJB
// private OtherService otherService;
//
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Assert.assertEquals(Integer.class, otherService.getInteger().getClass());
// Assert.assertEquals(new Integer(2), otherService.getInteger());
// req.setAttribute("result", otherService.getText());
// req.setAttribute("integer", otherService.getInteger());
// req.getRequestDispatcher("test.jsp").forward(req, resp);
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/session/UserSession.java
// @SessionScoped
// public class UserSession implements Serializable {
//
// private static final long serialVersionUID = 1L;
// private Locale locale;
//
// public Locale getLocale() {
// return locale;
// }
//
// public void setLocale(Locale locale) {
// this.locale = locale;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/IntegrationTestDeploymentUtils.java
// public static class DeploymentAppenderFactory {
//
// private DeploymentAppenderFactory() {
// }
//
// public static WebDeploymentAppender create(WebArchive archive) {
// return new WebDeploymentAppender(archive);
// }
//
// public static JavaDeploymentAppender create(JavaArchive archive) {
// return new JavaDeploymentAppender(archive);
// }
//
// public static EnterpriseDeploymentAppender create(EnterpriseArchive archive) {
// return new EnterpriseDeploymentAppender(archive);
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherService.java
// @Local
// public interface OtherService extends Serializable {
//
// String getText();
//
// Integer getInteger();
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherServiceBean.java
// @Stateless
// public class OtherServiceBean implements OtherService {
//
// private static final long serialVersionUID = 1L;
//
// @Property("hello.world")
// private String text;
//
// @Property("some.integer")
// private Integer integer;
//
// @Override
// public String getText() {
// return text;
// }
//
// @Override
// public Integer getInteger() {
// return integer;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ProvidedLocaleMethodResolverSession.java
// @ApplicationScoped
// public class ProvidedLocaleMethodResolverSession implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @LocaleResolver
// public Locale resolveLocale(UserSession userSession) {
// return userSession.getLocale();
// }
//
// }
| import java.io.IOException;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import com.byteslounge.cdi.test.common.servlet.TestServlet;
import com.byteslounge.cdi.test.common.session.UserSession;
import com.byteslounge.cdi.test.it.common.IntegrationTestDeploymentUtils.DeploymentAppenderFactory;
import com.byteslounge.cdi.test.wpm.OtherService;
import com.byteslounge.cdi.test.wpm.OtherServiceBean;
import com.byteslounge.cdi.test.wpm.ProvidedLocaleMethodResolverSession; | /*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it.common;
/**
* Base class for Integration Tests which resolve the current locale from the user session
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public abstract class AbstractWarProvidedLocaleMethodSession {
protected static WebArchive createArchive() throws IOException {
WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses( | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/servlet/TestServlet.java
// @WebServlet(urlPatterns = "/testservlet")
// public class TestServlet extends HttpServlet {
//
// private static final long serialVersionUID = 1L;
//
// @EJB
// private OtherService otherService;
//
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Assert.assertEquals(Integer.class, otherService.getInteger().getClass());
// Assert.assertEquals(new Integer(2), otherService.getInteger());
// req.setAttribute("result", otherService.getText());
// req.setAttribute("integer", otherService.getInteger());
// req.getRequestDispatcher("test.jsp").forward(req, resp);
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/session/UserSession.java
// @SessionScoped
// public class UserSession implements Serializable {
//
// private static final long serialVersionUID = 1L;
// private Locale locale;
//
// public Locale getLocale() {
// return locale;
// }
//
// public void setLocale(Locale locale) {
// this.locale = locale;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/IntegrationTestDeploymentUtils.java
// public static class DeploymentAppenderFactory {
//
// private DeploymentAppenderFactory() {
// }
//
// public static WebDeploymentAppender create(WebArchive archive) {
// return new WebDeploymentAppender(archive);
// }
//
// public static JavaDeploymentAppender create(JavaArchive archive) {
// return new JavaDeploymentAppender(archive);
// }
//
// public static EnterpriseDeploymentAppender create(EnterpriseArchive archive) {
// return new EnterpriseDeploymentAppender(archive);
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherService.java
// @Local
// public interface OtherService extends Serializable {
//
// String getText();
//
// Integer getInteger();
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherServiceBean.java
// @Stateless
// public class OtherServiceBean implements OtherService {
//
// private static final long serialVersionUID = 1L;
//
// @Property("hello.world")
// private String text;
//
// @Property("some.integer")
// private Integer integer;
//
// @Override
// public String getText() {
// return text;
// }
//
// @Override
// public Integer getInteger() {
// return integer;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ProvidedLocaleMethodResolverSession.java
// @ApplicationScoped
// public class ProvidedLocaleMethodResolverSession implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @LocaleResolver
// public Locale resolveLocale(UserSession userSession) {
// return userSession.getLocale();
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodSession.java
import java.io.IOException;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import com.byteslounge.cdi.test.common.servlet.TestServlet;
import com.byteslounge.cdi.test.common.session.UserSession;
import com.byteslounge.cdi.test.it.common.IntegrationTestDeploymentUtils.DeploymentAppenderFactory;
import com.byteslounge.cdi.test.wpm.OtherService;
import com.byteslounge.cdi.test.wpm.OtherServiceBean;
import com.byteslounge.cdi.test.wpm.ProvidedLocaleMethodResolverSession;
/*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it.common;
/**
* Base class for Integration Tests which resolve the current locale from the user session
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public abstract class AbstractWarProvidedLocaleMethodSession {
protected static WebArchive createArchive() throws IOException {
WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses( | ProvidedLocaleMethodResolverSession.class, OtherService.class, OtherServiceBean.class, |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodSession.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/servlet/TestServlet.java
// @WebServlet(urlPatterns = "/testservlet")
// public class TestServlet extends HttpServlet {
//
// private static final long serialVersionUID = 1L;
//
// @EJB
// private OtherService otherService;
//
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Assert.assertEquals(Integer.class, otherService.getInteger().getClass());
// Assert.assertEquals(new Integer(2), otherService.getInteger());
// req.setAttribute("result", otherService.getText());
// req.setAttribute("integer", otherService.getInteger());
// req.getRequestDispatcher("test.jsp").forward(req, resp);
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/session/UserSession.java
// @SessionScoped
// public class UserSession implements Serializable {
//
// private static final long serialVersionUID = 1L;
// private Locale locale;
//
// public Locale getLocale() {
// return locale;
// }
//
// public void setLocale(Locale locale) {
// this.locale = locale;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/IntegrationTestDeploymentUtils.java
// public static class DeploymentAppenderFactory {
//
// private DeploymentAppenderFactory() {
// }
//
// public static WebDeploymentAppender create(WebArchive archive) {
// return new WebDeploymentAppender(archive);
// }
//
// public static JavaDeploymentAppender create(JavaArchive archive) {
// return new JavaDeploymentAppender(archive);
// }
//
// public static EnterpriseDeploymentAppender create(EnterpriseArchive archive) {
// return new EnterpriseDeploymentAppender(archive);
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherService.java
// @Local
// public interface OtherService extends Serializable {
//
// String getText();
//
// Integer getInteger();
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherServiceBean.java
// @Stateless
// public class OtherServiceBean implements OtherService {
//
// private static final long serialVersionUID = 1L;
//
// @Property("hello.world")
// private String text;
//
// @Property("some.integer")
// private Integer integer;
//
// @Override
// public String getText() {
// return text;
// }
//
// @Override
// public Integer getInteger() {
// return integer;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ProvidedLocaleMethodResolverSession.java
// @ApplicationScoped
// public class ProvidedLocaleMethodResolverSession implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @LocaleResolver
// public Locale resolveLocale(UserSession userSession) {
// return userSession.getLocale();
// }
//
// }
| import java.io.IOException;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import com.byteslounge.cdi.test.common.servlet.TestServlet;
import com.byteslounge.cdi.test.common.session.UserSession;
import com.byteslounge.cdi.test.it.common.IntegrationTestDeploymentUtils.DeploymentAppenderFactory;
import com.byteslounge.cdi.test.wpm.OtherService;
import com.byteslounge.cdi.test.wpm.OtherServiceBean;
import com.byteslounge.cdi.test.wpm.ProvidedLocaleMethodResolverSession; | /*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it.common;
/**
* Base class for Integration Tests which resolve the current locale from the user session
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public abstract class AbstractWarProvidedLocaleMethodSession {
protected static WebArchive createArchive() throws IOException {
WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses( | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/servlet/TestServlet.java
// @WebServlet(urlPatterns = "/testservlet")
// public class TestServlet extends HttpServlet {
//
// private static final long serialVersionUID = 1L;
//
// @EJB
// private OtherService otherService;
//
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Assert.assertEquals(Integer.class, otherService.getInteger().getClass());
// Assert.assertEquals(new Integer(2), otherService.getInteger());
// req.setAttribute("result", otherService.getText());
// req.setAttribute("integer", otherService.getInteger());
// req.getRequestDispatcher("test.jsp").forward(req, resp);
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/session/UserSession.java
// @SessionScoped
// public class UserSession implements Serializable {
//
// private static final long serialVersionUID = 1L;
// private Locale locale;
//
// public Locale getLocale() {
// return locale;
// }
//
// public void setLocale(Locale locale) {
// this.locale = locale;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/IntegrationTestDeploymentUtils.java
// public static class DeploymentAppenderFactory {
//
// private DeploymentAppenderFactory() {
// }
//
// public static WebDeploymentAppender create(WebArchive archive) {
// return new WebDeploymentAppender(archive);
// }
//
// public static JavaDeploymentAppender create(JavaArchive archive) {
// return new JavaDeploymentAppender(archive);
// }
//
// public static EnterpriseDeploymentAppender create(EnterpriseArchive archive) {
// return new EnterpriseDeploymentAppender(archive);
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherService.java
// @Local
// public interface OtherService extends Serializable {
//
// String getText();
//
// Integer getInteger();
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherServiceBean.java
// @Stateless
// public class OtherServiceBean implements OtherService {
//
// private static final long serialVersionUID = 1L;
//
// @Property("hello.world")
// private String text;
//
// @Property("some.integer")
// private Integer integer;
//
// @Override
// public String getText() {
// return text;
// }
//
// @Override
// public Integer getInteger() {
// return integer;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ProvidedLocaleMethodResolverSession.java
// @ApplicationScoped
// public class ProvidedLocaleMethodResolverSession implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @LocaleResolver
// public Locale resolveLocale(UserSession userSession) {
// return userSession.getLocale();
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodSession.java
import java.io.IOException;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import com.byteslounge.cdi.test.common.servlet.TestServlet;
import com.byteslounge.cdi.test.common.session.UserSession;
import com.byteslounge.cdi.test.it.common.IntegrationTestDeploymentUtils.DeploymentAppenderFactory;
import com.byteslounge.cdi.test.wpm.OtherService;
import com.byteslounge.cdi.test.wpm.OtherServiceBean;
import com.byteslounge.cdi.test.wpm.ProvidedLocaleMethodResolverSession;
/*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it.common;
/**
* Base class for Integration Tests which resolve the current locale from the user session
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public abstract class AbstractWarProvidedLocaleMethodSession {
protected static WebArchive createArchive() throws IOException {
WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses( | ProvidedLocaleMethodResolverSession.class, OtherService.class, OtherServiceBean.class, |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodSession.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/servlet/TestServlet.java
// @WebServlet(urlPatterns = "/testservlet")
// public class TestServlet extends HttpServlet {
//
// private static final long serialVersionUID = 1L;
//
// @EJB
// private OtherService otherService;
//
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Assert.assertEquals(Integer.class, otherService.getInteger().getClass());
// Assert.assertEquals(new Integer(2), otherService.getInteger());
// req.setAttribute("result", otherService.getText());
// req.setAttribute("integer", otherService.getInteger());
// req.getRequestDispatcher("test.jsp").forward(req, resp);
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/session/UserSession.java
// @SessionScoped
// public class UserSession implements Serializable {
//
// private static final long serialVersionUID = 1L;
// private Locale locale;
//
// public Locale getLocale() {
// return locale;
// }
//
// public void setLocale(Locale locale) {
// this.locale = locale;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/IntegrationTestDeploymentUtils.java
// public static class DeploymentAppenderFactory {
//
// private DeploymentAppenderFactory() {
// }
//
// public static WebDeploymentAppender create(WebArchive archive) {
// return new WebDeploymentAppender(archive);
// }
//
// public static JavaDeploymentAppender create(JavaArchive archive) {
// return new JavaDeploymentAppender(archive);
// }
//
// public static EnterpriseDeploymentAppender create(EnterpriseArchive archive) {
// return new EnterpriseDeploymentAppender(archive);
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherService.java
// @Local
// public interface OtherService extends Serializable {
//
// String getText();
//
// Integer getInteger();
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherServiceBean.java
// @Stateless
// public class OtherServiceBean implements OtherService {
//
// private static final long serialVersionUID = 1L;
//
// @Property("hello.world")
// private String text;
//
// @Property("some.integer")
// private Integer integer;
//
// @Override
// public String getText() {
// return text;
// }
//
// @Override
// public Integer getInteger() {
// return integer;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ProvidedLocaleMethodResolverSession.java
// @ApplicationScoped
// public class ProvidedLocaleMethodResolverSession implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @LocaleResolver
// public Locale resolveLocale(UserSession userSession) {
// return userSession.getLocale();
// }
//
// }
| import java.io.IOException;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import com.byteslounge.cdi.test.common.servlet.TestServlet;
import com.byteslounge.cdi.test.common.session.UserSession;
import com.byteslounge.cdi.test.it.common.IntegrationTestDeploymentUtils.DeploymentAppenderFactory;
import com.byteslounge.cdi.test.wpm.OtherService;
import com.byteslounge.cdi.test.wpm.OtherServiceBean;
import com.byteslounge.cdi.test.wpm.ProvidedLocaleMethodResolverSession; | /*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it.common;
/**
* Base class for Integration Tests which resolve the current locale from the user session
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public abstract class AbstractWarProvidedLocaleMethodSession {
protected static WebArchive createArchive() throws IOException {
WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses(
ProvidedLocaleMethodResolverSession.class, OtherService.class, OtherServiceBean.class, | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/servlet/TestServlet.java
// @WebServlet(urlPatterns = "/testservlet")
// public class TestServlet extends HttpServlet {
//
// private static final long serialVersionUID = 1L;
//
// @EJB
// private OtherService otherService;
//
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Assert.assertEquals(Integer.class, otherService.getInteger().getClass());
// Assert.assertEquals(new Integer(2), otherService.getInteger());
// req.setAttribute("result", otherService.getText());
// req.setAttribute("integer", otherService.getInteger());
// req.getRequestDispatcher("test.jsp").forward(req, resp);
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/session/UserSession.java
// @SessionScoped
// public class UserSession implements Serializable {
//
// private static final long serialVersionUID = 1L;
// private Locale locale;
//
// public Locale getLocale() {
// return locale;
// }
//
// public void setLocale(Locale locale) {
// this.locale = locale;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/IntegrationTestDeploymentUtils.java
// public static class DeploymentAppenderFactory {
//
// private DeploymentAppenderFactory() {
// }
//
// public static WebDeploymentAppender create(WebArchive archive) {
// return new WebDeploymentAppender(archive);
// }
//
// public static JavaDeploymentAppender create(JavaArchive archive) {
// return new JavaDeploymentAppender(archive);
// }
//
// public static EnterpriseDeploymentAppender create(EnterpriseArchive archive) {
// return new EnterpriseDeploymentAppender(archive);
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherService.java
// @Local
// public interface OtherService extends Serializable {
//
// String getText();
//
// Integer getInteger();
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherServiceBean.java
// @Stateless
// public class OtherServiceBean implements OtherService {
//
// private static final long serialVersionUID = 1L;
//
// @Property("hello.world")
// private String text;
//
// @Property("some.integer")
// private Integer integer;
//
// @Override
// public String getText() {
// return text;
// }
//
// @Override
// public Integer getInteger() {
// return integer;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ProvidedLocaleMethodResolverSession.java
// @ApplicationScoped
// public class ProvidedLocaleMethodResolverSession implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @LocaleResolver
// public Locale resolveLocale(UserSession userSession) {
// return userSession.getLocale();
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodSession.java
import java.io.IOException;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import com.byteslounge.cdi.test.common.servlet.TestServlet;
import com.byteslounge.cdi.test.common.session.UserSession;
import com.byteslounge.cdi.test.it.common.IntegrationTestDeploymentUtils.DeploymentAppenderFactory;
import com.byteslounge.cdi.test.wpm.OtherService;
import com.byteslounge.cdi.test.wpm.OtherServiceBean;
import com.byteslounge.cdi.test.wpm.ProvidedLocaleMethodResolverSession;
/*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it.common;
/**
* Base class for Integration Tests which resolve the current locale from the user session
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public abstract class AbstractWarProvidedLocaleMethodSession {
protected static WebArchive createArchive() throws IOException {
WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses(
ProvidedLocaleMethodResolverSession.class, OtherService.class, OtherServiceBean.class, | TestServlet.class, UserSession.class); |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodSession.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/servlet/TestServlet.java
// @WebServlet(urlPatterns = "/testservlet")
// public class TestServlet extends HttpServlet {
//
// private static final long serialVersionUID = 1L;
//
// @EJB
// private OtherService otherService;
//
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Assert.assertEquals(Integer.class, otherService.getInteger().getClass());
// Assert.assertEquals(new Integer(2), otherService.getInteger());
// req.setAttribute("result", otherService.getText());
// req.setAttribute("integer", otherService.getInteger());
// req.getRequestDispatcher("test.jsp").forward(req, resp);
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/session/UserSession.java
// @SessionScoped
// public class UserSession implements Serializable {
//
// private static final long serialVersionUID = 1L;
// private Locale locale;
//
// public Locale getLocale() {
// return locale;
// }
//
// public void setLocale(Locale locale) {
// this.locale = locale;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/IntegrationTestDeploymentUtils.java
// public static class DeploymentAppenderFactory {
//
// private DeploymentAppenderFactory() {
// }
//
// public static WebDeploymentAppender create(WebArchive archive) {
// return new WebDeploymentAppender(archive);
// }
//
// public static JavaDeploymentAppender create(JavaArchive archive) {
// return new JavaDeploymentAppender(archive);
// }
//
// public static EnterpriseDeploymentAppender create(EnterpriseArchive archive) {
// return new EnterpriseDeploymentAppender(archive);
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherService.java
// @Local
// public interface OtherService extends Serializable {
//
// String getText();
//
// Integer getInteger();
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherServiceBean.java
// @Stateless
// public class OtherServiceBean implements OtherService {
//
// private static final long serialVersionUID = 1L;
//
// @Property("hello.world")
// private String text;
//
// @Property("some.integer")
// private Integer integer;
//
// @Override
// public String getText() {
// return text;
// }
//
// @Override
// public Integer getInteger() {
// return integer;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ProvidedLocaleMethodResolverSession.java
// @ApplicationScoped
// public class ProvidedLocaleMethodResolverSession implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @LocaleResolver
// public Locale resolveLocale(UserSession userSession) {
// return userSession.getLocale();
// }
//
// }
| import java.io.IOException;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import com.byteslounge.cdi.test.common.servlet.TestServlet;
import com.byteslounge.cdi.test.common.session.UserSession;
import com.byteslounge.cdi.test.it.common.IntegrationTestDeploymentUtils.DeploymentAppenderFactory;
import com.byteslounge.cdi.test.wpm.OtherService;
import com.byteslounge.cdi.test.wpm.OtherServiceBean;
import com.byteslounge.cdi.test.wpm.ProvidedLocaleMethodResolverSession; | /*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it.common;
/**
* Base class for Integration Tests which resolve the current locale from the user session
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public abstract class AbstractWarProvidedLocaleMethodSession {
protected static WebArchive createArchive() throws IOException {
WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses(
ProvidedLocaleMethodResolverSession.class, OtherService.class, OtherServiceBean.class, | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/servlet/TestServlet.java
// @WebServlet(urlPatterns = "/testservlet")
// public class TestServlet extends HttpServlet {
//
// private static final long serialVersionUID = 1L;
//
// @EJB
// private OtherService otherService;
//
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Assert.assertEquals(Integer.class, otherService.getInteger().getClass());
// Assert.assertEquals(new Integer(2), otherService.getInteger());
// req.setAttribute("result", otherService.getText());
// req.setAttribute("integer", otherService.getInteger());
// req.getRequestDispatcher("test.jsp").forward(req, resp);
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/session/UserSession.java
// @SessionScoped
// public class UserSession implements Serializable {
//
// private static final long serialVersionUID = 1L;
// private Locale locale;
//
// public Locale getLocale() {
// return locale;
// }
//
// public void setLocale(Locale locale) {
// this.locale = locale;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/IntegrationTestDeploymentUtils.java
// public static class DeploymentAppenderFactory {
//
// private DeploymentAppenderFactory() {
// }
//
// public static WebDeploymentAppender create(WebArchive archive) {
// return new WebDeploymentAppender(archive);
// }
//
// public static JavaDeploymentAppender create(JavaArchive archive) {
// return new JavaDeploymentAppender(archive);
// }
//
// public static EnterpriseDeploymentAppender create(EnterpriseArchive archive) {
// return new EnterpriseDeploymentAppender(archive);
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherService.java
// @Local
// public interface OtherService extends Serializable {
//
// String getText();
//
// Integer getInteger();
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherServiceBean.java
// @Stateless
// public class OtherServiceBean implements OtherService {
//
// private static final long serialVersionUID = 1L;
//
// @Property("hello.world")
// private String text;
//
// @Property("some.integer")
// private Integer integer;
//
// @Override
// public String getText() {
// return text;
// }
//
// @Override
// public Integer getInteger() {
// return integer;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ProvidedLocaleMethodResolverSession.java
// @ApplicationScoped
// public class ProvidedLocaleMethodResolverSession implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @LocaleResolver
// public Locale resolveLocale(UserSession userSession) {
// return userSession.getLocale();
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodSession.java
import java.io.IOException;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import com.byteslounge.cdi.test.common.servlet.TestServlet;
import com.byteslounge.cdi.test.common.session.UserSession;
import com.byteslounge.cdi.test.it.common.IntegrationTestDeploymentUtils.DeploymentAppenderFactory;
import com.byteslounge.cdi.test.wpm.OtherService;
import com.byteslounge.cdi.test.wpm.OtherServiceBean;
import com.byteslounge.cdi.test.wpm.ProvidedLocaleMethodResolverSession;
/*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it.common;
/**
* Base class for Integration Tests which resolve the current locale from the user session
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public abstract class AbstractWarProvidedLocaleMethodSession {
protected static WebArchive createArchive() throws IOException {
WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses(
ProvidedLocaleMethodResolverSession.class, OtherService.class, OtherServiceBean.class, | TestServlet.class, UserSession.class); |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodSession.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/servlet/TestServlet.java
// @WebServlet(urlPatterns = "/testservlet")
// public class TestServlet extends HttpServlet {
//
// private static final long serialVersionUID = 1L;
//
// @EJB
// private OtherService otherService;
//
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Assert.assertEquals(Integer.class, otherService.getInteger().getClass());
// Assert.assertEquals(new Integer(2), otherService.getInteger());
// req.setAttribute("result", otherService.getText());
// req.setAttribute("integer", otherService.getInteger());
// req.getRequestDispatcher("test.jsp").forward(req, resp);
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/session/UserSession.java
// @SessionScoped
// public class UserSession implements Serializable {
//
// private static final long serialVersionUID = 1L;
// private Locale locale;
//
// public Locale getLocale() {
// return locale;
// }
//
// public void setLocale(Locale locale) {
// this.locale = locale;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/IntegrationTestDeploymentUtils.java
// public static class DeploymentAppenderFactory {
//
// private DeploymentAppenderFactory() {
// }
//
// public static WebDeploymentAppender create(WebArchive archive) {
// return new WebDeploymentAppender(archive);
// }
//
// public static JavaDeploymentAppender create(JavaArchive archive) {
// return new JavaDeploymentAppender(archive);
// }
//
// public static EnterpriseDeploymentAppender create(EnterpriseArchive archive) {
// return new EnterpriseDeploymentAppender(archive);
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherService.java
// @Local
// public interface OtherService extends Serializable {
//
// String getText();
//
// Integer getInteger();
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherServiceBean.java
// @Stateless
// public class OtherServiceBean implements OtherService {
//
// private static final long serialVersionUID = 1L;
//
// @Property("hello.world")
// private String text;
//
// @Property("some.integer")
// private Integer integer;
//
// @Override
// public String getText() {
// return text;
// }
//
// @Override
// public Integer getInteger() {
// return integer;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ProvidedLocaleMethodResolverSession.java
// @ApplicationScoped
// public class ProvidedLocaleMethodResolverSession implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @LocaleResolver
// public Locale resolveLocale(UserSession userSession) {
// return userSession.getLocale();
// }
//
// }
| import java.io.IOException;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import com.byteslounge.cdi.test.common.servlet.TestServlet;
import com.byteslounge.cdi.test.common.session.UserSession;
import com.byteslounge.cdi.test.it.common.IntegrationTestDeploymentUtils.DeploymentAppenderFactory;
import com.byteslounge.cdi.test.wpm.OtherService;
import com.byteslounge.cdi.test.wpm.OtherServiceBean;
import com.byteslounge.cdi.test.wpm.ProvidedLocaleMethodResolverSession; | /*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it.common;
/**
* Base class for Integration Tests which resolve the current locale from the user session
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public abstract class AbstractWarProvidedLocaleMethodSession {
protected static WebArchive createArchive() throws IOException {
WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses(
ProvidedLocaleMethodResolverSession.class, OtherService.class, OtherServiceBean.class,
TestServlet.class, UserSession.class); | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/servlet/TestServlet.java
// @WebServlet(urlPatterns = "/testservlet")
// public class TestServlet extends HttpServlet {
//
// private static final long serialVersionUID = 1L;
//
// @EJB
// private OtherService otherService;
//
// @Override
// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Assert.assertEquals(Integer.class, otherService.getInteger().getClass());
// Assert.assertEquals(new Integer(2), otherService.getInteger());
// req.setAttribute("result", otherService.getText());
// req.setAttribute("integer", otherService.getInteger());
// req.getRequestDispatcher("test.jsp").forward(req, resp);
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/session/UserSession.java
// @SessionScoped
// public class UserSession implements Serializable {
//
// private static final long serialVersionUID = 1L;
// private Locale locale;
//
// public Locale getLocale() {
// return locale;
// }
//
// public void setLocale(Locale locale) {
// this.locale = locale;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/IntegrationTestDeploymentUtils.java
// public static class DeploymentAppenderFactory {
//
// private DeploymentAppenderFactory() {
// }
//
// public static WebDeploymentAppender create(WebArchive archive) {
// return new WebDeploymentAppender(archive);
// }
//
// public static JavaDeploymentAppender create(JavaArchive archive) {
// return new JavaDeploymentAppender(archive);
// }
//
// public static EnterpriseDeploymentAppender create(EnterpriseArchive archive) {
// return new EnterpriseDeploymentAppender(archive);
// }
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherService.java
// @Local
// public interface OtherService extends Serializable {
//
// String getText();
//
// Integer getInteger();
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherServiceBean.java
// @Stateless
// public class OtherServiceBean implements OtherService {
//
// private static final long serialVersionUID = 1L;
//
// @Property("hello.world")
// private String text;
//
// @Property("some.integer")
// private Integer integer;
//
// @Override
// public String getText() {
// return text;
// }
//
// @Override
// public Integer getInteger() {
// return integer;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/ProvidedLocaleMethodResolverSession.java
// @ApplicationScoped
// public class ProvidedLocaleMethodResolverSession implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @LocaleResolver
// public Locale resolveLocale(UserSession userSession) {
// return userSession.getLocale();
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/it/common/AbstractWarProvidedLocaleMethodSession.java
import java.io.IOException;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import com.byteslounge.cdi.test.common.servlet.TestServlet;
import com.byteslounge.cdi.test.common.session.UserSession;
import com.byteslounge.cdi.test.it.common.IntegrationTestDeploymentUtils.DeploymentAppenderFactory;
import com.byteslounge.cdi.test.wpm.OtherService;
import com.byteslounge.cdi.test.wpm.OtherServiceBean;
import com.byteslounge.cdi.test.wpm.ProvidedLocaleMethodResolverSession;
/*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.it.common;
/**
* Base class for Integration Tests which resolve the current locale from the user session
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public abstract class AbstractWarProvidedLocaleMethodSession {
protected static WebArchive createArchive() throws IOException {
WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "cdipropertiestest.war").addClasses(
ProvidedLocaleMethodResolverSession.class, OtherService.class, OtherServiceBean.class,
TestServlet.class, UserSession.class); | DeploymentAppenderFactory.create(webArchive) |
gonmarques/cdi-properties | cdi-properties-main/src/main/java/com/byteslounge/cdi/extension/param/LocalePropertyResolverParameter.java | // Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/bean/ResolverBean.java
// public interface ResolverBean<T> {
//
// /**
// * Processes a CDI managed bean and checks if it defines an extension's resolver method
// *
// * @param at the CDI managed bean to check for an extension's resolver method
// */
// void process(AnnotatedType<?> at);
//
// /**
// * Initializes the extension's resolver method
// *
// * @param beanManager the CDI container Bean Manager
// */
// void initialize(BeanManager beanManager);
//
// /**
// * Invokes the extension's resolver method represented by this bean
// *
// * @param resolverContext the Resolver Context
// * @param ctx The CDI creational context
// *
// * @return the value returned by this extension's resolver method
// */
// T invoke(ResolverContext resolverContext, CreationalContext<?> ctx);
//
// }
//
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/context/ResolverContext.java
// public class ResolverContext {
//
// private final String key;
// private final String bundleName;
// private Bean<?> resolverBean;
// private BeanManager beanManager;
//
// private ResolverContext(String key, String bundleName) {
// this.key = key;
// this.bundleName = bundleName;
// }
//
// /**
// * Creates a {@link com.byteslounge.cdi.resolver.context.ResolverContext} instance.
// *
// * @param key the property key to be associated with the created context
// * @param bundleName the resource bundle name to be associated with the created context
// *
// * @return the newly created {@link com.byteslounge.cdi.resolver.context.ResolverContext} instance
// */
// public static ResolverContext create(String key, String bundleName) {
// return new ResolverContext(key, bundleName);
// }
//
// /**
// * Gets the key associated with this {@link com.byteslounge.cdi.resolver.context.ResolverContext} instance
// *
// * @return the key associated with this {@link com.byteslounge.cdi.resolver.context.ResolverContext} instance
// */
// public String getKey() {
// return key;
// }
//
// /**
// * Gets the resource bundle name associated with this {@link com.byteslounge.cdi.resolver.context.ResolverContext} instance
// *
// * @return the resource bundle name associated with this {@link com.byteslounge.cdi.resolver.context.ResolverContext} instance
// */
// public String getBundleName() {
// return bundleName;
// }
//
// /**
// * Sets the resolver bean associated with the current resolving execution
// *
// * @param resolverBean the property key to be associated with the created context
// */
// public void setResolverBean(Bean<?> resolverBean) {
// this.resolverBean = resolverBean;
// }
//
// /**
// * Gets the resolver bean associated with the current resolving execution
// *
// * @return the resolver bean associated with the current resolving execution
// */
// public Bean<?> getResolverBean() {
// return resolverBean;
// }
//
// /**
// * Gets the bean manager associated with the current resolving execution
// *
// * @return the bean manager associated with the current resolving execution
// */
// public BeanManager getBeanManager() {
// return beanManager;
// }
//
// /**
// * Sets the bean manager associated with the current resolving execution
// *
// * @param beanManager the bean manager associated with the current resolving execution
// */
// public void setBeanManager(BeanManager beanManager) {
// this.beanManager = beanManager;
// }
//
// }
| import javax.enterprise.context.spi.CreationalContext;
import com.byteslounge.cdi.resolver.bean.ResolverBean;
import com.byteslounge.cdi.resolver.context.ResolverContext;
import java.util.Locale; | /*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.extension.param;
/**
* Represents a resolver that will be used to evaluate a
* parameter of the property resolver method of type Locale
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public class LocalePropertyResolverParameter implements ResolverParameter<Locale> {
private final ResolverBean<Locale> localeResolverBean;
public LocalePropertyResolverParameter(ResolverBean<Locale> localResolverBean) {
this.localeResolverBean = localResolverBean;
}
/**
* see {@link ResolverParameter#resolve(String, String, CreationalContext)}
*/
@Override | // Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/bean/ResolverBean.java
// public interface ResolverBean<T> {
//
// /**
// * Processes a CDI managed bean and checks if it defines an extension's resolver method
// *
// * @param at the CDI managed bean to check for an extension's resolver method
// */
// void process(AnnotatedType<?> at);
//
// /**
// * Initializes the extension's resolver method
// *
// * @param beanManager the CDI container Bean Manager
// */
// void initialize(BeanManager beanManager);
//
// /**
// * Invokes the extension's resolver method represented by this bean
// *
// * @param resolverContext the Resolver Context
// * @param ctx The CDI creational context
// *
// * @return the value returned by this extension's resolver method
// */
// T invoke(ResolverContext resolverContext, CreationalContext<?> ctx);
//
// }
//
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/context/ResolverContext.java
// public class ResolverContext {
//
// private final String key;
// private final String bundleName;
// private Bean<?> resolverBean;
// private BeanManager beanManager;
//
// private ResolverContext(String key, String bundleName) {
// this.key = key;
// this.bundleName = bundleName;
// }
//
// /**
// * Creates a {@link com.byteslounge.cdi.resolver.context.ResolverContext} instance.
// *
// * @param key the property key to be associated with the created context
// * @param bundleName the resource bundle name to be associated with the created context
// *
// * @return the newly created {@link com.byteslounge.cdi.resolver.context.ResolverContext} instance
// */
// public static ResolverContext create(String key, String bundleName) {
// return new ResolverContext(key, bundleName);
// }
//
// /**
// * Gets the key associated with this {@link com.byteslounge.cdi.resolver.context.ResolverContext} instance
// *
// * @return the key associated with this {@link com.byteslounge.cdi.resolver.context.ResolverContext} instance
// */
// public String getKey() {
// return key;
// }
//
// /**
// * Gets the resource bundle name associated with this {@link com.byteslounge.cdi.resolver.context.ResolverContext} instance
// *
// * @return the resource bundle name associated with this {@link com.byteslounge.cdi.resolver.context.ResolverContext} instance
// */
// public String getBundleName() {
// return bundleName;
// }
//
// /**
// * Sets the resolver bean associated with the current resolving execution
// *
// * @param resolverBean the property key to be associated with the created context
// */
// public void setResolverBean(Bean<?> resolverBean) {
// this.resolverBean = resolverBean;
// }
//
// /**
// * Gets the resolver bean associated with the current resolving execution
// *
// * @return the resolver bean associated with the current resolving execution
// */
// public Bean<?> getResolverBean() {
// return resolverBean;
// }
//
// /**
// * Gets the bean manager associated with the current resolving execution
// *
// * @return the bean manager associated with the current resolving execution
// */
// public BeanManager getBeanManager() {
// return beanManager;
// }
//
// /**
// * Sets the bean manager associated with the current resolving execution
// *
// * @param beanManager the bean manager associated with the current resolving execution
// */
// public void setBeanManager(BeanManager beanManager) {
// this.beanManager = beanManager;
// }
//
// }
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/extension/param/LocalePropertyResolverParameter.java
import javax.enterprise.context.spi.CreationalContext;
import com.byteslounge.cdi.resolver.bean.ResolverBean;
import com.byteslounge.cdi.resolver.context.ResolverContext;
import java.util.Locale;
/*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.extension.param;
/**
* Represents a resolver that will be used to evaluate a
* parameter of the property resolver method of type Locale
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public class LocalePropertyResolverParameter implements ResolverParameter<Locale> {
private final ResolverBean<Locale> localeResolverBean;
public LocalePropertyResolverParameter(ResolverBean<Locale> localResolverBean) {
this.localeResolverBean = localResolverBean;
}
/**
* see {@link ResolverParameter#resolve(String, String, CreationalContext)}
*/
@Override | public <T> Locale resolve(ResolverContext resolverContext, CreationalContext<T> ctx) { |
gonmarques/cdi-properties | cdi-properties-main/src/main/java/com/byteslounge/cdi/configuration/ExtensionConfiguration.java | // Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/exception/ExtensionInitializationException.java
// public class ExtensionInitializationException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public ExtensionInitializationException(String message) {
// super(message);
// }
//
// public ExtensionInitializationException(Throwable cause) {
// super(cause);
// }
//
// public ExtensionInitializationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/locale/LocaleResolverFactory.java
// public class LocaleResolverFactory {
//
// private static volatile LocaleResolver localeResolver;
//
// private LocaleResolverFactory() {
// }
//
// /**
// * Gets the configured extension locale resolver
// *
// * @return The extension configured locale resolver
// */
// public static LocaleResolver getLocaleResolver() {
// return localeResolver;
// }
//
// /**
// * Sets the configured extension locale resolver
// *
// * @param localeResolver
// * The configured extension locale resolver
// */
// public static void setLocaleResolver(LocaleResolver localeResolver) {
// LocaleResolverFactory.localeResolver = localeResolver;
// }
//
// }
//
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/locale/StandaloneLocaleResolver.java
// public class StandaloneLocaleResolver implements LocaleResolver {
//
// /**
// * See {@link LocaleResolver#getLocale()}
// */
// @Override
// public Locale getLocale() {
// return Locale.getDefault();
// }
//
// }
| import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.byteslounge.cdi.exception.ExtensionInitializationException;
import com.byteslounge.cdi.resolver.locale.LocaleResolverFactory;
import com.byteslounge.cdi.resolver.locale.StandaloneLocaleResolver; | /*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.configuration;
/**
* Defines the global application configuration.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
public enum ExtensionConfiguration {
INSTANCE;
private static final String EXTENSION_PROPERTIES_FILE = "CDIProperties.properties";
private Logger logger;
private String resourceBundleDefaultBaseName;
private ExtensionConfiguration() {
logger = LoggerFactory.getLogger(ExtensionConfiguration.class); | // Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/exception/ExtensionInitializationException.java
// public class ExtensionInitializationException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public ExtensionInitializationException(String message) {
// super(message);
// }
//
// public ExtensionInitializationException(Throwable cause) {
// super(cause);
// }
//
// public ExtensionInitializationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/locale/LocaleResolverFactory.java
// public class LocaleResolverFactory {
//
// private static volatile LocaleResolver localeResolver;
//
// private LocaleResolverFactory() {
// }
//
// /**
// * Gets the configured extension locale resolver
// *
// * @return The extension configured locale resolver
// */
// public static LocaleResolver getLocaleResolver() {
// return localeResolver;
// }
//
// /**
// * Sets the configured extension locale resolver
// *
// * @param localeResolver
// * The configured extension locale resolver
// */
// public static void setLocaleResolver(LocaleResolver localeResolver) {
// LocaleResolverFactory.localeResolver = localeResolver;
// }
//
// }
//
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/locale/StandaloneLocaleResolver.java
// public class StandaloneLocaleResolver implements LocaleResolver {
//
// /**
// * See {@link LocaleResolver#getLocale()}
// */
// @Override
// public Locale getLocale() {
// return Locale.getDefault();
// }
//
// }
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/configuration/ExtensionConfiguration.java
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.byteslounge.cdi.exception.ExtensionInitializationException;
import com.byteslounge.cdi.resolver.locale.LocaleResolverFactory;
import com.byteslounge.cdi.resolver.locale.StandaloneLocaleResolver;
/*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.configuration;
/**
* Defines the global application configuration.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
public enum ExtensionConfiguration {
INSTANCE;
private static final String EXTENSION_PROPERTIES_FILE = "CDIProperties.properties";
private Logger logger;
private String resourceBundleDefaultBaseName;
private ExtensionConfiguration() {
logger = LoggerFactory.getLogger(ExtensionConfiguration.class); | LocaleResolverFactory.setLocaleResolver(new StandaloneLocaleResolver()); |
gonmarques/cdi-properties | cdi-properties-main/src/main/java/com/byteslounge/cdi/configuration/ExtensionConfiguration.java | // Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/exception/ExtensionInitializationException.java
// public class ExtensionInitializationException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public ExtensionInitializationException(String message) {
// super(message);
// }
//
// public ExtensionInitializationException(Throwable cause) {
// super(cause);
// }
//
// public ExtensionInitializationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/locale/LocaleResolverFactory.java
// public class LocaleResolverFactory {
//
// private static volatile LocaleResolver localeResolver;
//
// private LocaleResolverFactory() {
// }
//
// /**
// * Gets the configured extension locale resolver
// *
// * @return The extension configured locale resolver
// */
// public static LocaleResolver getLocaleResolver() {
// return localeResolver;
// }
//
// /**
// * Sets the configured extension locale resolver
// *
// * @param localeResolver
// * The configured extension locale resolver
// */
// public static void setLocaleResolver(LocaleResolver localeResolver) {
// LocaleResolverFactory.localeResolver = localeResolver;
// }
//
// }
//
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/locale/StandaloneLocaleResolver.java
// public class StandaloneLocaleResolver implements LocaleResolver {
//
// /**
// * See {@link LocaleResolver#getLocale()}
// */
// @Override
// public Locale getLocale() {
// return Locale.getDefault();
// }
//
// }
| import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.byteslounge.cdi.exception.ExtensionInitializationException;
import com.byteslounge.cdi.resolver.locale.LocaleResolverFactory;
import com.byteslounge.cdi.resolver.locale.StandaloneLocaleResolver; | /*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.configuration;
/**
* Defines the global application configuration.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
public enum ExtensionConfiguration {
INSTANCE;
private static final String EXTENSION_PROPERTIES_FILE = "CDIProperties.properties";
private Logger logger;
private String resourceBundleDefaultBaseName;
private ExtensionConfiguration() {
logger = LoggerFactory.getLogger(ExtensionConfiguration.class); | // Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/exception/ExtensionInitializationException.java
// public class ExtensionInitializationException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public ExtensionInitializationException(String message) {
// super(message);
// }
//
// public ExtensionInitializationException(Throwable cause) {
// super(cause);
// }
//
// public ExtensionInitializationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/locale/LocaleResolverFactory.java
// public class LocaleResolverFactory {
//
// private static volatile LocaleResolver localeResolver;
//
// private LocaleResolverFactory() {
// }
//
// /**
// * Gets the configured extension locale resolver
// *
// * @return The extension configured locale resolver
// */
// public static LocaleResolver getLocaleResolver() {
// return localeResolver;
// }
//
// /**
// * Sets the configured extension locale resolver
// *
// * @param localeResolver
// * The configured extension locale resolver
// */
// public static void setLocaleResolver(LocaleResolver localeResolver) {
// LocaleResolverFactory.localeResolver = localeResolver;
// }
//
// }
//
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/locale/StandaloneLocaleResolver.java
// public class StandaloneLocaleResolver implements LocaleResolver {
//
// /**
// * See {@link LocaleResolver#getLocale()}
// */
// @Override
// public Locale getLocale() {
// return Locale.getDefault();
// }
//
// }
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/configuration/ExtensionConfiguration.java
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.byteslounge.cdi.exception.ExtensionInitializationException;
import com.byteslounge.cdi.resolver.locale.LocaleResolverFactory;
import com.byteslounge.cdi.resolver.locale.StandaloneLocaleResolver;
/*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.configuration;
/**
* Defines the global application configuration.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
public enum ExtensionConfiguration {
INSTANCE;
private static final String EXTENSION_PROPERTIES_FILE = "CDIProperties.properties";
private Logger logger;
private String resourceBundleDefaultBaseName;
private ExtensionConfiguration() {
logger = LoggerFactory.getLogger(ExtensionConfiguration.class); | LocaleResolverFactory.setLocaleResolver(new StandaloneLocaleResolver()); |
gonmarques/cdi-properties | cdi-properties-main/src/main/java/com/byteslounge/cdi/configuration/ExtensionConfiguration.java | // Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/exception/ExtensionInitializationException.java
// public class ExtensionInitializationException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public ExtensionInitializationException(String message) {
// super(message);
// }
//
// public ExtensionInitializationException(Throwable cause) {
// super(cause);
// }
//
// public ExtensionInitializationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/locale/LocaleResolverFactory.java
// public class LocaleResolverFactory {
//
// private static volatile LocaleResolver localeResolver;
//
// private LocaleResolverFactory() {
// }
//
// /**
// * Gets the configured extension locale resolver
// *
// * @return The extension configured locale resolver
// */
// public static LocaleResolver getLocaleResolver() {
// return localeResolver;
// }
//
// /**
// * Sets the configured extension locale resolver
// *
// * @param localeResolver
// * The configured extension locale resolver
// */
// public static void setLocaleResolver(LocaleResolver localeResolver) {
// LocaleResolverFactory.localeResolver = localeResolver;
// }
//
// }
//
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/locale/StandaloneLocaleResolver.java
// public class StandaloneLocaleResolver implements LocaleResolver {
//
// /**
// * See {@link LocaleResolver#getLocale()}
// */
// @Override
// public Locale getLocale() {
// return Locale.getDefault();
// }
//
// }
| import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.byteslounge.cdi.exception.ExtensionInitializationException;
import com.byteslounge.cdi.resolver.locale.LocaleResolverFactory;
import com.byteslounge.cdi.resolver.locale.StandaloneLocaleResolver; | /*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.configuration;
/**
* Defines the global application configuration.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
public enum ExtensionConfiguration {
INSTANCE;
private static final String EXTENSION_PROPERTIES_FILE = "CDIProperties.properties";
private Logger logger;
private String resourceBundleDefaultBaseName;
private ExtensionConfiguration() {
logger = LoggerFactory.getLogger(ExtensionConfiguration.class);
LocaleResolverFactory.setLocaleResolver(new StandaloneLocaleResolver());
URL url = ExtensionConfiguration.class.getClassLoader().getResource(EXTENSION_PROPERTIES_FILE);
if (url != null) {
Properties properties = new Properties();
try {
properties.load(url.openStream());
setResourceBundleDefaultBaseName(properties.getProperty(ExtensionInitializer.DEFAULT_RESOURCE_BUNDLE_BASE_NAME_PARAM));
} catch (IOException e) { | // Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/exception/ExtensionInitializationException.java
// public class ExtensionInitializationException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public ExtensionInitializationException(String message) {
// super(message);
// }
//
// public ExtensionInitializationException(Throwable cause) {
// super(cause);
// }
//
// public ExtensionInitializationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/locale/LocaleResolverFactory.java
// public class LocaleResolverFactory {
//
// private static volatile LocaleResolver localeResolver;
//
// private LocaleResolverFactory() {
// }
//
// /**
// * Gets the configured extension locale resolver
// *
// * @return The extension configured locale resolver
// */
// public static LocaleResolver getLocaleResolver() {
// return localeResolver;
// }
//
// /**
// * Sets the configured extension locale resolver
// *
// * @param localeResolver
// * The configured extension locale resolver
// */
// public static void setLocaleResolver(LocaleResolver localeResolver) {
// LocaleResolverFactory.localeResolver = localeResolver;
// }
//
// }
//
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/locale/StandaloneLocaleResolver.java
// public class StandaloneLocaleResolver implements LocaleResolver {
//
// /**
// * See {@link LocaleResolver#getLocale()}
// */
// @Override
// public Locale getLocale() {
// return Locale.getDefault();
// }
//
// }
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/configuration/ExtensionConfiguration.java
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.byteslounge.cdi.exception.ExtensionInitializationException;
import com.byteslounge.cdi.resolver.locale.LocaleResolverFactory;
import com.byteslounge.cdi.resolver.locale.StandaloneLocaleResolver;
/*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.configuration;
/**
* Defines the global application configuration.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
public enum ExtensionConfiguration {
INSTANCE;
private static final String EXTENSION_PROPERTIES_FILE = "CDIProperties.properties";
private Logger logger;
private String resourceBundleDefaultBaseName;
private ExtensionConfiguration() {
logger = LoggerFactory.getLogger(ExtensionConfiguration.class);
LocaleResolverFactory.setLocaleResolver(new StandaloneLocaleResolver());
URL url = ExtensionConfiguration.class.getClassLoader().getResource(EXTENSION_PROPERTIES_FILE);
if (url != null) {
Properties properties = new Properties();
try {
properties.load(url.openStream());
setResourceBundleDefaultBaseName(properties.getProperty(ExtensionInitializer.DEFAULT_RESOURCE_BUNDLE_BASE_NAME_PARAM));
} catch (IOException e) { | throw new ExtensionInitializationException("Error while loading CDI Properties configuration file", e); |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/DependentScopedBean.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
| import org.junit.Assert;
import com.byteslounge.cdi.test.configuration.TestConstants;
import javax.inject.Inject; | /*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.common;
/**
* Used in CDI Properties integration tests. See WarDefaultMethodIT.java,
* WarProvidedMethodIT.java, EjbDefaultMethodIT.java and
* EjbProvidedMethodIT.java.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
public class DependentScopedBean {
@Inject
private InjectedBean injectedBean;
public String getText() { | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/DependentScopedBean.java
import org.junit.Assert;
import com.byteslounge.cdi.test.configuration.TestConstants;
import javax.inject.Inject;
/*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.common;
/**
* Used in CDI Properties integration tests. See WarDefaultMethodIT.java,
* WarProvidedMethodIT.java, EjbDefaultMethodIT.java and
* EjbProvidedMethodIT.java.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
public class DependentScopedBean {
@Inject
private InjectedBean injectedBean;
public String getText() { | Assert.assertEquals(injectedBean.getText(), TestConstants.BEAN_TEST_RETURN_VALUE); |
gonmarques/cdi-properties | cdi-properties-main/src/main/java/com/byteslounge/cdi/utils/ValidationUtils.java | // Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/verifier/ResolverMethodVerifier.java
// public interface ResolverMethodVerifier {
//
// /**
// * Verifies if the property resolver method is properly configured
// */
// void verify();
//
// }
| import com.byteslounge.cdi.resolver.verifier.ResolverMethodVerifier;
import java.util.Collection; | /*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.utils;
/**
* Utility class related property resolver method validation.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
public class ValidationUtils {
private ValidationUtils() {
}
/**
* Validates the property resolver method against a list of property
* resolver method verifiers
*
* @param verifiers
* The list of property resolver method verifiers
*/ | // Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/verifier/ResolverMethodVerifier.java
// public interface ResolverMethodVerifier {
//
// /**
// * Verifies if the property resolver method is properly configured
// */
// void verify();
//
// }
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/utils/ValidationUtils.java
import com.byteslounge.cdi.resolver.verifier.ResolverMethodVerifier;
import java.util.Collection;
/*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.utils;
/**
* Utility class related property resolver method validation.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
public class ValidationUtils {
private ValidationUtils() {
}
/**
* Validates the property resolver method against a list of property
* resolver method verifiers
*
* @param verifiers
* The list of property resolver method verifiers
*/ | public static void validateResolverMethod(Collection<? extends ResolverMethodVerifier> verifiers) { |
gonmarques/cdi-properties | cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/verifier/LocaleResolverMethodParametersVerifier.java | // Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/exception/ExtensionInitializationException.java
// public class ExtensionInitializationException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public ExtensionInitializationException(String message) {
// super(message);
// }
//
// public ExtensionInitializationException(Throwable cause) {
// super(cause);
// }
//
// public ExtensionInitializationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
| import com.byteslounge.cdi.annotation.PropertyLocale;
import com.byteslounge.cdi.exception.ExtensionInitializationException;
import javax.enterprise.inject.spi.AnnotatedMethod;
import javax.enterprise.inject.spi.AnnotatedParameter; | /*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.resolver.verifier;
/**
* Checks if a custom Locale resolver method parameter is annotated with {@link PropertyLocale}
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public class LocaleResolverMethodParametersVerifier implements ResolverMethodVerifier {
private final AnnotatedMethod<?> localeResolverMethod;
public LocaleResolverMethodParametersVerifier(AnnotatedMethod<?> localeResolverMethod) {
this.localeResolverMethod = localeResolverMethod;
}
/**
* See {@link ResolverMethodVerifier#verify()}
*/
@Override
public void verify() {
checkLocaleResolverParameterAnnotations();
}
/**
* Checks if any property resolver method parameter is annotated with
* {@link PropertyLocale}
*/
private void checkLocaleResolverParameterAnnotations() {
for (final AnnotatedParameter<?> parameter : localeResolverMethod.getParameters()) {
if (parameter.isAnnotationPresent(PropertyLocale.class)) { | // Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/exception/ExtensionInitializationException.java
// public class ExtensionInitializationException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public ExtensionInitializationException(String message) {
// super(message);
// }
//
// public ExtensionInitializationException(Throwable cause) {
// super(cause);
// }
//
// public ExtensionInitializationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/verifier/LocaleResolverMethodParametersVerifier.java
import com.byteslounge.cdi.annotation.PropertyLocale;
import com.byteslounge.cdi.exception.ExtensionInitializationException;
import javax.enterprise.inject.spi.AnnotatedMethod;
import javax.enterprise.inject.spi.AnnotatedParameter;
/*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.resolver.verifier;
/**
* Checks if a custom Locale resolver method parameter is annotated with {@link PropertyLocale}
*
* @author Gonçalo Marques
* @since 1.1.0
*/
public class LocaleResolverMethodParametersVerifier implements ResolverMethodVerifier {
private final AnnotatedMethod<?> localeResolverMethod;
public LocaleResolverMethodParametersVerifier(AnnotatedMethod<?> localeResolverMethod) {
this.localeResolverMethod = localeResolverMethod;
}
/**
* See {@link ResolverMethodVerifier#verify()}
*/
@Override
public void verify() {
checkLocaleResolverParameterAnnotations();
}
/**
* Checks if any property resolver method parameter is annotated with
* {@link PropertyLocale}
*/
private void checkLocaleResolverParameterAnnotations() {
for (final AnnotatedParameter<?> parameter : localeResolverMethod.getParameters()) {
if (parameter.isAnnotationPresent(PropertyLocale.class)) { | throw new ExtensionInitializationException( |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/TestBean.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
| import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.junit.Assert;
import com.byteslounge.cdi.annotation.Property;
import com.byteslounge.cdi.test.configuration.TestConstants; | /*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.common;
/**
* Used in CDI Properties integration tests. See WarDefaultMethodIT.java,
* WarProvidedMethodIT.java, EjbDefaultMethodIT.java and
* EjbProvidedMethodIT.java.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
@Named
@RequestScoped
public class TestBean {
@Property("hello.world")
private String helloWorld;
@Property(value = "system.linux.box", parameters = { "Linux", "16" })
private String systemBox;
| // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/TestBean.java
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;
import org.junit.Assert;
import com.byteslounge.cdi.annotation.Property;
import com.byteslounge.cdi.test.configuration.TestConstants;
/*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.common;
/**
* Used in CDI Properties integration tests. See WarDefaultMethodIT.java,
* WarProvidedMethodIT.java, EjbDefaultMethodIT.java and
* EjbProvidedMethodIT.java.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
@Named
@RequestScoped
public class TestBean {
@Property("hello.world")
private String helloWorld;
@Property(value = "system.linux.box", parameters = { "Linux", "16" })
private String systemBox;
| @Property(value = "other.message", resourceBundleBaseName = TestConstants.OTHER_RESOURCE_BUNDLE_NAME) |
gonmarques/cdi-properties | cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/bean/ResolverInstanceLazyInitializer.java | // Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/exception/ExtensionInitializationException.java
// public class ExtensionInitializationException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public ExtensionInitializationException(String message) {
// super(message);
// }
//
// public ExtensionInitializationException(Throwable cause) {
// super(cause);
// }
//
// public ExtensionInitializationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
| import java.util.Collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.byteslounge.cdi.exception.ExtensionInitializationException; | /*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.resolver.bean;
/**
* Lazy resolver bean initializer created to solve bean resolution problems
* in older versions of Weld (ex: Weld 1.1.3 that is shipped with Weblogic 12.1.1).
*
* Basically we fall back to the Bean Manager that is fetched through JNDI in case
* the Bean Manager provided to the extension fails to resolve the Property/Locale resolvers.
*
* @author Gonçalo Marques
* @since 1.1.1
*/
public class ResolverInstanceLazyInitializer {
private static final Logger logger = LoggerFactory.getLogger(ResolverInstanceLazyInitializer.class);
private volatile ResolverInstance resolverInstance;
private final Class<?> resolverClass;
private final BeanManagerList beanManagers;
public ResolverInstanceLazyInitializer(BeanManager beanManager, Class<?> resolverClass) {
this.beanManagers = new BeanManagerList(beanManager);
this.resolverClass = resolverClass;
}
public ResolverInstance get() {
ResolverInstance result = resolverInstance;
if (result == null) {
synchronized (this) {
result = resolverInstance;
if (result == null) {
BeanResolverResult beanResolverResult = CDIBeanResolver.resolve(beanManagers, resolverClass);
BeanManager activeBeanManager = beanResolverResult.activeBeanManager;
Bean<?> resolverBean = activeBeanManager.resolve(beanResolverResult.beans);
if (resolverBean == null) { | // Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/exception/ExtensionInitializationException.java
// public class ExtensionInitializationException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public ExtensionInitializationException(String message) {
// super(message);
// }
//
// public ExtensionInitializationException(Throwable cause) {
// super(cause);
// }
//
// public ExtensionInitializationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
// Path: cdi-properties-main/src/main/java/com/byteslounge/cdi/resolver/bean/ResolverInstanceLazyInitializer.java
import java.util.Collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.byteslounge.cdi.exception.ExtensionInitializationException;
/*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.resolver.bean;
/**
* Lazy resolver bean initializer created to solve bean resolution problems
* in older versions of Weld (ex: Weld 1.1.3 that is shipped with Weblogic 12.1.1).
*
* Basically we fall back to the Bean Manager that is fetched through JNDI in case
* the Bean Manager provided to the extension fails to resolve the Property/Locale resolvers.
*
* @author Gonçalo Marques
* @since 1.1.1
*/
public class ResolverInstanceLazyInitializer {
private static final Logger logger = LoggerFactory.getLogger(ResolverInstanceLazyInitializer.class);
private volatile ResolverInstance resolverInstance;
private final Class<?> resolverClass;
private final BeanManagerList beanManagers;
public ResolverInstanceLazyInitializer(BeanManager beanManager, Class<?> resolverClass) {
this.beanManagers = new BeanManagerList(beanManager);
this.resolverClass = resolverClass;
}
public ResolverInstance get() {
ResolverInstance result = resolverInstance;
if (result == null) {
synchronized (this) {
result = resolverInstance;
if (result == null) {
BeanResolverResult beanResolverResult = CDIBeanResolver.resolve(beanManagers, resolverClass);
BeanManager activeBeanManager = beanResolverResult.activeBeanManager;
Bean<?> resolverBean = activeBeanManager.resolve(beanResolverResult.beans);
if (resolverBean == null) { | throw new ExtensionInitializationException( |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/servlet/TestServlet.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherService.java
// @Local
// public interface OtherService extends Serializable {
//
// String getText();
//
// Integer getInteger();
//
// }
| import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Assert;
import com.byteslounge.cdi.test.wpm.OtherService; | /*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.common.servlet;
/**
* Servlet used in integration tests
*
* @author Gonçalo Marques
* @since 1.1.0
*/
@WebServlet(urlPatterns = "/testservlet")
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/wpm/OtherService.java
// @Local
// public interface OtherService extends Serializable {
//
// String getText();
//
// Integer getInteger();
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/servlet/TestServlet.java
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Assert;
import com.byteslounge.cdi.test.wpm.OtherService;
/*
* Copyright 2015 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.common.servlet;
/**
* Servlet used in integration tests
*
* @author Gonçalo Marques
* @since 1.1.0
*/
@WebServlet(urlPatterns = "/testservlet")
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB | private OtherService otherService; |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/InjectedBean.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
| import com.byteslounge.cdi.test.configuration.TestConstants;
import java.io.Serializable; | /*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.common;
/**
* Used in CDI Properties integration tests. See WarDefaultMethodIT.java,
* WarProvidedMethodIT.java, EjbDefaultMethodIT.java and
* EjbProvidedMethodIT.java.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
public class InjectedBean implements Serializable {
private static final long serialVersionUID = 1L;
public String getText() { | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/InjectedBean.java
import com.byteslounge.cdi.test.configuration.TestConstants;
import java.io.Serializable;
/*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.common;
/**
* Used in CDI Properties integration tests. See WarDefaultMethodIT.java,
* WarProvidedMethodIT.java, EjbDefaultMethodIT.java and
* EjbProvidedMethodIT.java.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
public class InjectedBean implements Serializable {
private static final long serialVersionUID = 1L;
public String getText() { | return TestConstants.BEAN_TEST_RETURN_VALUE; |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/epm/ServiceEjbProvidedMethod.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
| import javax.ejb.Remote;
import com.byteslounge.cdi.test.model.TestEntity;
import java.io.Serializable; | /*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.epm;
/**
* Used in CDI Properties integration tests. See WarDefaultMethodIT.java,
* WarProvidedMethodIT.java, EjbDefaultMethodIT.java and
* EjbProvidedMethodIT.java.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
@Remote
public interface ServiceEjbProvidedMethod extends Serializable {
String getText();
| // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/epm/ServiceEjbProvidedMethod.java
import javax.ejb.Remote;
import com.byteslounge.cdi.test.model.TestEntity;
import java.io.Serializable;
/*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.epm;
/**
* Used in CDI Properties integration tests. See WarDefaultMethodIT.java,
* WarProvidedMethodIT.java, EjbDefaultMethodIT.java and
* EjbProvidedMethodIT.java.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
@Remote
public interface ServiceEjbProvidedMethod extends Serializable {
String getText();
| TestEntity merge(TestEntity testEntity); |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/epm/ServiceEjbProvidedMethodBean.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/InjectedBean.java
// public class InjectedBean implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// public String getText() {
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
| import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.Assert;
import com.byteslounge.cdi.test.common.InjectedBean;
import com.byteslounge.cdi.test.configuration.TestConstants;
import com.byteslounge.cdi.test.model.TestEntity; | /*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.epm;
/**
* Used in CDI Properties integration tests. See WarDefaultMethodIT.java,
* WarProvidedMethodIT.java, EjbDefaultMethodIT.java and
* EjbProvidedMethodIT.java.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
@Stateless
public class ServiceEjbProvidedMethodBean implements ServiceEjbProvidedMethod {
private static final long serialVersionUID = 1L;
@PersistenceContext
private EntityManager entityManager;
@Inject | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/InjectedBean.java
// public class InjectedBean implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// public String getText() {
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/epm/ServiceEjbProvidedMethodBean.java
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.Assert;
import com.byteslounge.cdi.test.common.InjectedBean;
import com.byteslounge.cdi.test.configuration.TestConstants;
import com.byteslounge.cdi.test.model.TestEntity;
/*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.epm;
/**
* Used in CDI Properties integration tests. See WarDefaultMethodIT.java,
* WarProvidedMethodIT.java, EjbDefaultMethodIT.java and
* EjbProvidedMethodIT.java.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
@Stateless
public class ServiceEjbProvidedMethodBean implements ServiceEjbProvidedMethod {
private static final long serialVersionUID = 1L;
@PersistenceContext
private EntityManager entityManager;
@Inject | private InjectedBean injectedBean; |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/epm/ServiceEjbProvidedMethodBean.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/InjectedBean.java
// public class InjectedBean implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// public String getText() {
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
| import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.Assert;
import com.byteslounge.cdi.test.common.InjectedBean;
import com.byteslounge.cdi.test.configuration.TestConstants;
import com.byteslounge.cdi.test.model.TestEntity; | /*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.epm;
/**
* Used in CDI Properties integration tests. See WarDefaultMethodIT.java,
* WarProvidedMethodIT.java, EjbDefaultMethodIT.java and
* EjbProvidedMethodIT.java.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
@Stateless
public class ServiceEjbProvidedMethodBean implements ServiceEjbProvidedMethod {
private static final long serialVersionUID = 1L;
@PersistenceContext
private EntityManager entityManager;
@Inject
private InjectedBean injectedBean;
@Override
public String getText() { | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/InjectedBean.java
// public class InjectedBean implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// public String getText() {
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/epm/ServiceEjbProvidedMethodBean.java
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.Assert;
import com.byteslounge.cdi.test.common.InjectedBean;
import com.byteslounge.cdi.test.configuration.TestConstants;
import com.byteslounge.cdi.test.model.TestEntity;
/*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.epm;
/**
* Used in CDI Properties integration tests. See WarDefaultMethodIT.java,
* WarProvidedMethodIT.java, EjbDefaultMethodIT.java and
* EjbProvidedMethodIT.java.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
@Stateless
public class ServiceEjbProvidedMethodBean implements ServiceEjbProvidedMethod {
private static final long serialVersionUID = 1L;
@PersistenceContext
private EntityManager entityManager;
@Inject
private InjectedBean injectedBean;
@Override
public String getText() { | Assert.assertEquals(injectedBean.getText(), TestConstants.BEAN_TEST_RETURN_VALUE); |
gonmarques/cdi-properties | cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/epm/ServiceEjbProvidedMethodBean.java | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/InjectedBean.java
// public class InjectedBean implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// public String getText() {
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
| import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.Assert;
import com.byteslounge.cdi.test.common.InjectedBean;
import com.byteslounge.cdi.test.configuration.TestConstants;
import com.byteslounge.cdi.test.model.TestEntity; | /*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.epm;
/**
* Used in CDI Properties integration tests. See WarDefaultMethodIT.java,
* WarProvidedMethodIT.java, EjbDefaultMethodIT.java and
* EjbProvidedMethodIT.java.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
@Stateless
public class ServiceEjbProvidedMethodBean implements ServiceEjbProvidedMethod {
private static final long serialVersionUID = 1L;
@PersistenceContext
private EntityManager entityManager;
@Inject
private InjectedBean injectedBean;
@Override
public String getText() {
Assert.assertEquals(injectedBean.getText(), TestConstants.BEAN_TEST_RETURN_VALUE);
return TestConstants.BEAN_TEST_RETURN_VALUE;
}
@Override | // Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/common/InjectedBean.java
// public class InjectedBean implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// public String getText() {
// return TestConstants.BEAN_TEST_RETURN_VALUE;
// }
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/configuration/TestConstants.java
// public class TestConstants {
//
// private TestConstants() {
// }
//
// public static final String OTHER_RESOURCE_BUNDLE_NAME = "bl.other";
// public static final String BEAN_TEST_RETURN_VALUE = "getTextResult";
// public static final String PROVIDED_RESOLVER_SUFFIX = "provided";
// public static final String EXTERNAL_CLASSES_DIRECTORY = "target/external";
// public static final String TEST_TARGET_CLASSES_DIRECTORY = "target/test-classes";
//
// }
//
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/model/TestEntity.java
// @Entity
// @Table(name = "TEST_ENTITY")
// public class TestEntity implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "ID", nullable = false)
// @GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerator")
// @GenericGenerator(name = "IdGenerator", strategy = "com.byteslounge.cdi.test.model.IdGenerator")
// private Long id;
//
// @Column(name = "DESCRIPTION", nullable = false)
// private String description;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// }
// Path: cdi-properties-test/cdi-properties-test-common/src/main/java/com/byteslounge/cdi/test/epm/ServiceEjbProvidedMethodBean.java
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.Assert;
import com.byteslounge.cdi.test.common.InjectedBean;
import com.byteslounge.cdi.test.configuration.TestConstants;
import com.byteslounge.cdi.test.model.TestEntity;
/*
* Copyright 2014 byteslounge.com (Gonçalo Marques).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.byteslounge.cdi.test.epm;
/**
* Used in CDI Properties integration tests. See WarDefaultMethodIT.java,
* WarProvidedMethodIT.java, EjbDefaultMethodIT.java and
* EjbProvidedMethodIT.java.
*
* @author Gonçalo Marques
* @since 1.0.0
*/
@Stateless
public class ServiceEjbProvidedMethodBean implements ServiceEjbProvidedMethod {
private static final long serialVersionUID = 1L;
@PersistenceContext
private EntityManager entityManager;
@Inject
private InjectedBean injectedBean;
@Override
public String getText() {
Assert.assertEquals(injectedBean.getText(), TestConstants.BEAN_TEST_RETURN_VALUE);
return TestConstants.BEAN_TEST_RETURN_VALUE;
}
@Override | public TestEntity merge(TestEntity testEntity) { |
sandin/YoDao | yodao-examples/src/main/java/com/yoda/yodao/example/MySQLiteOpenHelper.java | // Path: yodao/src/main/java/com/yoda/yodao/DaoFactory.java
// public final class DaoFactory {
//
// private static final String SUFFIX = "Impl";
//
// private static Map<String, SoftReference<Class<?>>> mClazzCache = new HashMap<>();
//
// public static void onCreateTable(SQLiteDatabase db) {
// // create(HairDao.class).onCreateTable(db);
// // create(PhotoDao.class).onCreateTable(db);
// }
//
// public static void onUpgradeTable(SQLiteDatabase db, int oldVersion,
// int newVersion) {
// // create(HairDao.class).onUpgradeTable(db, oldVersion, newVersion);
// // create(PhotoDao.class).onUpgradeTable(db, oldVersion, newVersion);
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T create(Class<T> daoClass, SQLiteOpenHelper openHelper) {
// String daoClassName = daoClass.getCanonicalName();
// String[] cls = parseToClazz(daoClassName);
// daoClassName = cls[0] + ".impl." + cls[1] + SUFFIX;
// try {
// Class<?> clazz = null;
// SoftReference<Class<?>> ref = mClazzCache.get(daoClassName);
// if (ref != null) {
// clazz = ref.get();
// }
// if (clazz == null) {
// clazz = Class.forName(daoClassName);
// mClazzCache.put(daoClassName, new SoftReference<Class<?>>(clazz));
// }
//
// if (openHelper != null) {
// Constructor<?> constructor = clazz
// .getConstructor(SQLiteOpenHelper.class);
// return (T) constructor.newInstance(openHelper);
// } else {
// return (T) clazz.newInstance();
// }
// } catch (ClassNotFoundException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (NoSuchMethodException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (SecurityException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (InstantiationException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (IllegalAccessException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (IllegalArgumentException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (InvocationTargetException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// }
// }
//
// public static String[] parseToClazz(String clazzName) {
// int index = clazzName.lastIndexOf(".");
// if (index == -1) {
// throw new IllegalArgumentException(
// "model's package name must has at last one `.`");
// }
// String packageName = clazzName.substring(0, index);
// String className = clazzName.substring(index + 1, clazzName.length());
// return new String[] { packageName, className };
// }
//
// }
//
// Path: yodao-examples/src/main/java/com/yoda/yodao/example/dao/HairDao.java
// @Repository
// public abstract class HairDao extends BaseDao<Hair, Long> {
//
// public HairDao(SQLiteOpenHelper openHelper) {
// super(openHelper);
// }
//
// }
//
// Path: yodao-examples/src/main/java/com/yoda/yodao/example/dao/PhotoDao.java
// @Repository
// public interface PhotoDao extends YoDao<Photo, String> {
//
// List<Photo> findListByViewType(int type);
//
// List<Photo> findListByModelingUUId(String mid);
//
// long countByOpStatus(int opStatus);
//
// int updateByViewType(Photo entity, int type);
//
// @Query("select * from photo where type = ?")
// Photo findBySQL(int type);
//
// @Query("select * from photo where type = ?")
// List<Photo> findListBySQL(int type);
//
// @Query("select count(*) from photo where type = ? and name = ?")
// long countBySQL(int type, String name);
//
// }
| import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.yoda.yodao.DaoFactory;
import com.yoda.yodao.example.dao.HairDao;
import com.yoda.yodao.example.dao.PhotoDao; | package com.yoda.yodao.example;
/**
*
* @author wellor
* @version
* @date 2015-3-25
*
*/
public class MySQLiteOpenHelper extends android.database.sqlite.SQLiteOpenHelper {
private static final String DB_NAME = "ibeauty.db";
private static final int DB_VERSION = 13;
private static MySQLiteOpenHelper sInstance;
public MySQLiteOpenHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) { | // Path: yodao/src/main/java/com/yoda/yodao/DaoFactory.java
// public final class DaoFactory {
//
// private static final String SUFFIX = "Impl";
//
// private static Map<String, SoftReference<Class<?>>> mClazzCache = new HashMap<>();
//
// public static void onCreateTable(SQLiteDatabase db) {
// // create(HairDao.class).onCreateTable(db);
// // create(PhotoDao.class).onCreateTable(db);
// }
//
// public static void onUpgradeTable(SQLiteDatabase db, int oldVersion,
// int newVersion) {
// // create(HairDao.class).onUpgradeTable(db, oldVersion, newVersion);
// // create(PhotoDao.class).onUpgradeTable(db, oldVersion, newVersion);
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T create(Class<T> daoClass, SQLiteOpenHelper openHelper) {
// String daoClassName = daoClass.getCanonicalName();
// String[] cls = parseToClazz(daoClassName);
// daoClassName = cls[0] + ".impl." + cls[1] + SUFFIX;
// try {
// Class<?> clazz = null;
// SoftReference<Class<?>> ref = mClazzCache.get(daoClassName);
// if (ref != null) {
// clazz = ref.get();
// }
// if (clazz == null) {
// clazz = Class.forName(daoClassName);
// mClazzCache.put(daoClassName, new SoftReference<Class<?>>(clazz));
// }
//
// if (openHelper != null) {
// Constructor<?> constructor = clazz
// .getConstructor(SQLiteOpenHelper.class);
// return (T) constructor.newInstance(openHelper);
// } else {
// return (T) clazz.newInstance();
// }
// } catch (ClassNotFoundException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (NoSuchMethodException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (SecurityException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (InstantiationException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (IllegalAccessException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (IllegalArgumentException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (InvocationTargetException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// }
// }
//
// public static String[] parseToClazz(String clazzName) {
// int index = clazzName.lastIndexOf(".");
// if (index == -1) {
// throw new IllegalArgumentException(
// "model's package name must has at last one `.`");
// }
// String packageName = clazzName.substring(0, index);
// String className = clazzName.substring(index + 1, clazzName.length());
// return new String[] { packageName, className };
// }
//
// }
//
// Path: yodao-examples/src/main/java/com/yoda/yodao/example/dao/HairDao.java
// @Repository
// public abstract class HairDao extends BaseDao<Hair, Long> {
//
// public HairDao(SQLiteOpenHelper openHelper) {
// super(openHelper);
// }
//
// }
//
// Path: yodao-examples/src/main/java/com/yoda/yodao/example/dao/PhotoDao.java
// @Repository
// public interface PhotoDao extends YoDao<Photo, String> {
//
// List<Photo> findListByViewType(int type);
//
// List<Photo> findListByModelingUUId(String mid);
//
// long countByOpStatus(int opStatus);
//
// int updateByViewType(Photo entity, int type);
//
// @Query("select * from photo where type = ?")
// Photo findBySQL(int type);
//
// @Query("select * from photo where type = ?")
// List<Photo> findListBySQL(int type);
//
// @Query("select count(*) from photo where type = ? and name = ?")
// long countBySQL(int type, String name);
//
// }
// Path: yodao-examples/src/main/java/com/yoda/yodao/example/MySQLiteOpenHelper.java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.yoda.yodao.DaoFactory;
import com.yoda.yodao.example.dao.HairDao;
import com.yoda.yodao.example.dao.PhotoDao;
package com.yoda.yodao.example;
/**
*
* @author wellor
* @version
* @date 2015-3-25
*
*/
public class MySQLiteOpenHelper extends android.database.sqlite.SQLiteOpenHelper {
private static final String DB_NAME = "ibeauty.db";
private static final int DB_VERSION = 13;
private static MySQLiteOpenHelper sInstance;
public MySQLiteOpenHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) { | DaoFactory.create(HairDao.class, null).onCreateTable(db); |
sandin/YoDao | yodao-examples/src/main/java/com/yoda/yodao/example/MySQLiteOpenHelper.java | // Path: yodao/src/main/java/com/yoda/yodao/DaoFactory.java
// public final class DaoFactory {
//
// private static final String SUFFIX = "Impl";
//
// private static Map<String, SoftReference<Class<?>>> mClazzCache = new HashMap<>();
//
// public static void onCreateTable(SQLiteDatabase db) {
// // create(HairDao.class).onCreateTable(db);
// // create(PhotoDao.class).onCreateTable(db);
// }
//
// public static void onUpgradeTable(SQLiteDatabase db, int oldVersion,
// int newVersion) {
// // create(HairDao.class).onUpgradeTable(db, oldVersion, newVersion);
// // create(PhotoDao.class).onUpgradeTable(db, oldVersion, newVersion);
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T create(Class<T> daoClass, SQLiteOpenHelper openHelper) {
// String daoClassName = daoClass.getCanonicalName();
// String[] cls = parseToClazz(daoClassName);
// daoClassName = cls[0] + ".impl." + cls[1] + SUFFIX;
// try {
// Class<?> clazz = null;
// SoftReference<Class<?>> ref = mClazzCache.get(daoClassName);
// if (ref != null) {
// clazz = ref.get();
// }
// if (clazz == null) {
// clazz = Class.forName(daoClassName);
// mClazzCache.put(daoClassName, new SoftReference<Class<?>>(clazz));
// }
//
// if (openHelper != null) {
// Constructor<?> constructor = clazz
// .getConstructor(SQLiteOpenHelper.class);
// return (T) constructor.newInstance(openHelper);
// } else {
// return (T) clazz.newInstance();
// }
// } catch (ClassNotFoundException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (NoSuchMethodException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (SecurityException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (InstantiationException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (IllegalAccessException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (IllegalArgumentException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (InvocationTargetException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// }
// }
//
// public static String[] parseToClazz(String clazzName) {
// int index = clazzName.lastIndexOf(".");
// if (index == -1) {
// throw new IllegalArgumentException(
// "model's package name must has at last one `.`");
// }
// String packageName = clazzName.substring(0, index);
// String className = clazzName.substring(index + 1, clazzName.length());
// return new String[] { packageName, className };
// }
//
// }
//
// Path: yodao-examples/src/main/java/com/yoda/yodao/example/dao/HairDao.java
// @Repository
// public abstract class HairDao extends BaseDao<Hair, Long> {
//
// public HairDao(SQLiteOpenHelper openHelper) {
// super(openHelper);
// }
//
// }
//
// Path: yodao-examples/src/main/java/com/yoda/yodao/example/dao/PhotoDao.java
// @Repository
// public interface PhotoDao extends YoDao<Photo, String> {
//
// List<Photo> findListByViewType(int type);
//
// List<Photo> findListByModelingUUId(String mid);
//
// long countByOpStatus(int opStatus);
//
// int updateByViewType(Photo entity, int type);
//
// @Query("select * from photo where type = ?")
// Photo findBySQL(int type);
//
// @Query("select * from photo where type = ?")
// List<Photo> findListBySQL(int type);
//
// @Query("select count(*) from photo where type = ? and name = ?")
// long countBySQL(int type, String name);
//
// }
| import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.yoda.yodao.DaoFactory;
import com.yoda.yodao.example.dao.HairDao;
import com.yoda.yodao.example.dao.PhotoDao; | package com.yoda.yodao.example;
/**
*
* @author wellor
* @version
* @date 2015-3-25
*
*/
public class MySQLiteOpenHelper extends android.database.sqlite.SQLiteOpenHelper {
private static final String DB_NAME = "ibeauty.db";
private static final int DB_VERSION = 13;
private static MySQLiteOpenHelper sInstance;
public MySQLiteOpenHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) { | // Path: yodao/src/main/java/com/yoda/yodao/DaoFactory.java
// public final class DaoFactory {
//
// private static final String SUFFIX = "Impl";
//
// private static Map<String, SoftReference<Class<?>>> mClazzCache = new HashMap<>();
//
// public static void onCreateTable(SQLiteDatabase db) {
// // create(HairDao.class).onCreateTable(db);
// // create(PhotoDao.class).onCreateTable(db);
// }
//
// public static void onUpgradeTable(SQLiteDatabase db, int oldVersion,
// int newVersion) {
// // create(HairDao.class).onUpgradeTable(db, oldVersion, newVersion);
// // create(PhotoDao.class).onUpgradeTable(db, oldVersion, newVersion);
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T create(Class<T> daoClass, SQLiteOpenHelper openHelper) {
// String daoClassName = daoClass.getCanonicalName();
// String[] cls = parseToClazz(daoClassName);
// daoClassName = cls[0] + ".impl." + cls[1] + SUFFIX;
// try {
// Class<?> clazz = null;
// SoftReference<Class<?>> ref = mClazzCache.get(daoClassName);
// if (ref != null) {
// clazz = ref.get();
// }
// if (clazz == null) {
// clazz = Class.forName(daoClassName);
// mClazzCache.put(daoClassName, new SoftReference<Class<?>>(clazz));
// }
//
// if (openHelper != null) {
// Constructor<?> constructor = clazz
// .getConstructor(SQLiteOpenHelper.class);
// return (T) constructor.newInstance(openHelper);
// } else {
// return (T) clazz.newInstance();
// }
// } catch (ClassNotFoundException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (NoSuchMethodException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (SecurityException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (InstantiationException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (IllegalAccessException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (IllegalArgumentException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (InvocationTargetException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// }
// }
//
// public static String[] parseToClazz(String clazzName) {
// int index = clazzName.lastIndexOf(".");
// if (index == -1) {
// throw new IllegalArgumentException(
// "model's package name must has at last one `.`");
// }
// String packageName = clazzName.substring(0, index);
// String className = clazzName.substring(index + 1, clazzName.length());
// return new String[] { packageName, className };
// }
//
// }
//
// Path: yodao-examples/src/main/java/com/yoda/yodao/example/dao/HairDao.java
// @Repository
// public abstract class HairDao extends BaseDao<Hair, Long> {
//
// public HairDao(SQLiteOpenHelper openHelper) {
// super(openHelper);
// }
//
// }
//
// Path: yodao-examples/src/main/java/com/yoda/yodao/example/dao/PhotoDao.java
// @Repository
// public interface PhotoDao extends YoDao<Photo, String> {
//
// List<Photo> findListByViewType(int type);
//
// List<Photo> findListByModelingUUId(String mid);
//
// long countByOpStatus(int opStatus);
//
// int updateByViewType(Photo entity, int type);
//
// @Query("select * from photo where type = ?")
// Photo findBySQL(int type);
//
// @Query("select * from photo where type = ?")
// List<Photo> findListBySQL(int type);
//
// @Query("select count(*) from photo where type = ? and name = ?")
// long countBySQL(int type, String name);
//
// }
// Path: yodao-examples/src/main/java/com/yoda/yodao/example/MySQLiteOpenHelper.java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.yoda.yodao.DaoFactory;
import com.yoda.yodao.example.dao.HairDao;
import com.yoda.yodao.example.dao.PhotoDao;
package com.yoda.yodao.example;
/**
*
* @author wellor
* @version
* @date 2015-3-25
*
*/
public class MySQLiteOpenHelper extends android.database.sqlite.SQLiteOpenHelper {
private static final String DB_NAME = "ibeauty.db";
private static final int DB_VERSION = 13;
private static MySQLiteOpenHelper sInstance;
public MySQLiteOpenHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) { | DaoFactory.create(HairDao.class, null).onCreateTable(db); |
sandin/YoDao | yodao-examples/src/main/java/com/yoda/yodao/example/MySQLiteOpenHelper.java | // Path: yodao/src/main/java/com/yoda/yodao/DaoFactory.java
// public final class DaoFactory {
//
// private static final String SUFFIX = "Impl";
//
// private static Map<String, SoftReference<Class<?>>> mClazzCache = new HashMap<>();
//
// public static void onCreateTable(SQLiteDatabase db) {
// // create(HairDao.class).onCreateTable(db);
// // create(PhotoDao.class).onCreateTable(db);
// }
//
// public static void onUpgradeTable(SQLiteDatabase db, int oldVersion,
// int newVersion) {
// // create(HairDao.class).onUpgradeTable(db, oldVersion, newVersion);
// // create(PhotoDao.class).onUpgradeTable(db, oldVersion, newVersion);
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T create(Class<T> daoClass, SQLiteOpenHelper openHelper) {
// String daoClassName = daoClass.getCanonicalName();
// String[] cls = parseToClazz(daoClassName);
// daoClassName = cls[0] + ".impl." + cls[1] + SUFFIX;
// try {
// Class<?> clazz = null;
// SoftReference<Class<?>> ref = mClazzCache.get(daoClassName);
// if (ref != null) {
// clazz = ref.get();
// }
// if (clazz == null) {
// clazz = Class.forName(daoClassName);
// mClazzCache.put(daoClassName, new SoftReference<Class<?>>(clazz));
// }
//
// if (openHelper != null) {
// Constructor<?> constructor = clazz
// .getConstructor(SQLiteOpenHelper.class);
// return (T) constructor.newInstance(openHelper);
// } else {
// return (T) clazz.newInstance();
// }
// } catch (ClassNotFoundException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (NoSuchMethodException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (SecurityException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (InstantiationException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (IllegalAccessException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (IllegalArgumentException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (InvocationTargetException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// }
// }
//
// public static String[] parseToClazz(String clazzName) {
// int index = clazzName.lastIndexOf(".");
// if (index == -1) {
// throw new IllegalArgumentException(
// "model's package name must has at last one `.`");
// }
// String packageName = clazzName.substring(0, index);
// String className = clazzName.substring(index + 1, clazzName.length());
// return new String[] { packageName, className };
// }
//
// }
//
// Path: yodao-examples/src/main/java/com/yoda/yodao/example/dao/HairDao.java
// @Repository
// public abstract class HairDao extends BaseDao<Hair, Long> {
//
// public HairDao(SQLiteOpenHelper openHelper) {
// super(openHelper);
// }
//
// }
//
// Path: yodao-examples/src/main/java/com/yoda/yodao/example/dao/PhotoDao.java
// @Repository
// public interface PhotoDao extends YoDao<Photo, String> {
//
// List<Photo> findListByViewType(int type);
//
// List<Photo> findListByModelingUUId(String mid);
//
// long countByOpStatus(int opStatus);
//
// int updateByViewType(Photo entity, int type);
//
// @Query("select * from photo where type = ?")
// Photo findBySQL(int type);
//
// @Query("select * from photo where type = ?")
// List<Photo> findListBySQL(int type);
//
// @Query("select count(*) from photo where type = ? and name = ?")
// long countBySQL(int type, String name);
//
// }
| import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.yoda.yodao.DaoFactory;
import com.yoda.yodao.example.dao.HairDao;
import com.yoda.yodao.example.dao.PhotoDao; | package com.yoda.yodao.example;
/**
*
* @author wellor
* @version
* @date 2015-3-25
*
*/
public class MySQLiteOpenHelper extends android.database.sqlite.SQLiteOpenHelper {
private static final String DB_NAME = "ibeauty.db";
private static final int DB_VERSION = 13;
private static MySQLiteOpenHelper sInstance;
public MySQLiteOpenHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
DaoFactory.create(HairDao.class, null).onCreateTable(db); | // Path: yodao/src/main/java/com/yoda/yodao/DaoFactory.java
// public final class DaoFactory {
//
// private static final String SUFFIX = "Impl";
//
// private static Map<String, SoftReference<Class<?>>> mClazzCache = new HashMap<>();
//
// public static void onCreateTable(SQLiteDatabase db) {
// // create(HairDao.class).onCreateTable(db);
// // create(PhotoDao.class).onCreateTable(db);
// }
//
// public static void onUpgradeTable(SQLiteDatabase db, int oldVersion,
// int newVersion) {
// // create(HairDao.class).onUpgradeTable(db, oldVersion, newVersion);
// // create(PhotoDao.class).onUpgradeTable(db, oldVersion, newVersion);
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T create(Class<T> daoClass, SQLiteOpenHelper openHelper) {
// String daoClassName = daoClass.getCanonicalName();
// String[] cls = parseToClazz(daoClassName);
// daoClassName = cls[0] + ".impl." + cls[1] + SUFFIX;
// try {
// Class<?> clazz = null;
// SoftReference<Class<?>> ref = mClazzCache.get(daoClassName);
// if (ref != null) {
// clazz = ref.get();
// }
// if (clazz == null) {
// clazz = Class.forName(daoClassName);
// mClazzCache.put(daoClassName, new SoftReference<Class<?>>(clazz));
// }
//
// if (openHelper != null) {
// Constructor<?> constructor = clazz
// .getConstructor(SQLiteOpenHelper.class);
// return (T) constructor.newInstance(openHelper);
// } else {
// return (T) clazz.newInstance();
// }
// } catch (ClassNotFoundException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (NoSuchMethodException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (SecurityException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (InstantiationException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (IllegalAccessException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (IllegalArgumentException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// } catch (InvocationTargetException e) {
// throw new IllegalArgumentException(daoClassName + " cann't found.");
// }
// }
//
// public static String[] parseToClazz(String clazzName) {
// int index = clazzName.lastIndexOf(".");
// if (index == -1) {
// throw new IllegalArgumentException(
// "model's package name must has at last one `.`");
// }
// String packageName = clazzName.substring(0, index);
// String className = clazzName.substring(index + 1, clazzName.length());
// return new String[] { packageName, className };
// }
//
// }
//
// Path: yodao-examples/src/main/java/com/yoda/yodao/example/dao/HairDao.java
// @Repository
// public abstract class HairDao extends BaseDao<Hair, Long> {
//
// public HairDao(SQLiteOpenHelper openHelper) {
// super(openHelper);
// }
//
// }
//
// Path: yodao-examples/src/main/java/com/yoda/yodao/example/dao/PhotoDao.java
// @Repository
// public interface PhotoDao extends YoDao<Photo, String> {
//
// List<Photo> findListByViewType(int type);
//
// List<Photo> findListByModelingUUId(String mid);
//
// long countByOpStatus(int opStatus);
//
// int updateByViewType(Photo entity, int type);
//
// @Query("select * from photo where type = ?")
// Photo findBySQL(int type);
//
// @Query("select * from photo where type = ?")
// List<Photo> findListBySQL(int type);
//
// @Query("select count(*) from photo where type = ? and name = ?")
// long countBySQL(int type, String name);
//
// }
// Path: yodao-examples/src/main/java/com/yoda/yodao/example/MySQLiteOpenHelper.java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.yoda.yodao.DaoFactory;
import com.yoda.yodao.example.dao.HairDao;
import com.yoda.yodao.example.dao.PhotoDao;
package com.yoda.yodao.example;
/**
*
* @author wellor
* @version
* @date 2015-3-25
*
*/
public class MySQLiteOpenHelper extends android.database.sqlite.SQLiteOpenHelper {
private static final String DB_NAME = "ibeauty.db";
private static final int DB_VERSION = 13;
private static MySQLiteOpenHelper sInstance;
public MySQLiteOpenHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
DaoFactory.create(HairDao.class, null).onCreateTable(db); | DaoFactory.create(PhotoDao.class, null).onCreateTable(db); |
sandin/YoDao | yodao-examples/src/main/java/com/yoda/yodao/example/model/Photo.java | // Path: yodao-annotations/src/main/java/com/yoda/yodao/annotation/GenerationType.java
// public enum GenerationType {
//
// /**
// * Indicates that the persistence provider must assign
// * primary keys for the entity using an underlying
// * database table to ensure uniqueness.
// */
// TABLE,
//
// /**
// * Indicates that the persistence provider must assign
// * primary keys for the entity using database sequence column.
// */
// SEQUENCE,
//
// /**
// * Indicates that the persistence provider must assign
// * primary keys for the entity using database identity column.
// */
// IDENTITY,
//
// /**
// * Indicates that the persistence provider should pick an
// * appropriate strategy for the particular database. The
// * <code>AUTO</code> generation strategy may expect a database
// * resource to exist, or it may attempt to create one. A vendor
// * may provide documentation on how to create such resources
// * in the event that it does not support schema generation
// * or cannot create the schema resource at runtime.
// */
// AUTO,
//
// UUID
// }
| import java.io.Serializable;
import com.yoda.yodao.annotation.Column;
import com.yoda.yodao.annotation.Entity;
import com.yoda.yodao.annotation.GeneratedValue;
import com.yoda.yodao.annotation.GenerationType;
import com.yoda.yodao.annotation.Id;
import com.yoda.yodao.annotation.Table;
| package com.yoda.yodao.example.model;
/**
* 图片实体
*
* @author wellor
* @version
* @date 2015-3-2
* @class Photo2.java
*
*/
@Entity
@Table(name = "pho_photo")
public class Photo implements Serializable {
@Column(name = "id")
private long id;
/** uuid */
@Id
| // Path: yodao-annotations/src/main/java/com/yoda/yodao/annotation/GenerationType.java
// public enum GenerationType {
//
// /**
// * Indicates that the persistence provider must assign
// * primary keys for the entity using an underlying
// * database table to ensure uniqueness.
// */
// TABLE,
//
// /**
// * Indicates that the persistence provider must assign
// * primary keys for the entity using database sequence column.
// */
// SEQUENCE,
//
// /**
// * Indicates that the persistence provider must assign
// * primary keys for the entity using database identity column.
// */
// IDENTITY,
//
// /**
// * Indicates that the persistence provider should pick an
// * appropriate strategy for the particular database. The
// * <code>AUTO</code> generation strategy may expect a database
// * resource to exist, or it may attempt to create one. A vendor
// * may provide documentation on how to create such resources
// * in the event that it does not support schema generation
// * or cannot create the schema resource at runtime.
// */
// AUTO,
//
// UUID
// }
// Path: yodao-examples/src/main/java/com/yoda/yodao/example/model/Photo.java
import java.io.Serializable;
import com.yoda.yodao.annotation.Column;
import com.yoda.yodao.annotation.Entity;
import com.yoda.yodao.annotation.GeneratedValue;
import com.yoda.yodao.annotation.GenerationType;
import com.yoda.yodao.annotation.Id;
import com.yoda.yodao.annotation.Table;
package com.yoda.yodao.example.model;
/**
* 图片实体
*
* @author wellor
* @version
* @date 2015-3-2
* @class Photo2.java
*
*/
@Entity
@Table(name = "pho_photo")
public class Photo implements Serializable {
@Column(name = "id")
private long id;
/** uuid */
@Id
| @GeneratedValue(strategy = GenerationType.UUID)
|
sandin/YoDao | yodao-examples/src/main/java/com/yoda/yodao/example/model/Hair.java | // Path: yodao-annotations/src/main/java/com/yoda/yodao/annotation/GenerationType.java
// public enum GenerationType {
//
// /**
// * Indicates that the persistence provider must assign
// * primary keys for the entity using an underlying
// * database table to ensure uniqueness.
// */
// TABLE,
//
// /**
// * Indicates that the persistence provider must assign
// * primary keys for the entity using database sequence column.
// */
// SEQUENCE,
//
// /**
// * Indicates that the persistence provider must assign
// * primary keys for the entity using database identity column.
// */
// IDENTITY,
//
// /**
// * Indicates that the persistence provider should pick an
// * appropriate strategy for the particular database. The
// * <code>AUTO</code> generation strategy may expect a database
// * resource to exist, or it may attempt to create one. A vendor
// * may provide documentation on how to create such resources
// * in the event that it does not support schema generation
// * or cannot create the schema resource at runtime.
// */
// AUTO,
//
// UUID
// }
| import java.io.Serializable;
import java.util.Date;
import com.yoda.yodao.annotation.Column;
import com.yoda.yodao.annotation.Entity;
import com.yoda.yodao.annotation.GeneratedValue;
import com.yoda.yodao.annotation.GenerationType;
import com.yoda.yodao.annotation.Id;
import com.yoda.yodao.annotation.Table;
| package com.yoda.yodao.example.model;
/**
* 发型 实体
*
* @author wellor
* @version
* @date 2015-3-2
* @class Hair.java
*
*/
@Entity
@Table(name = "pho_hairHa")
public class Hair implements Serializable {
@Id
| // Path: yodao-annotations/src/main/java/com/yoda/yodao/annotation/GenerationType.java
// public enum GenerationType {
//
// /**
// * Indicates that the persistence provider must assign
// * primary keys for the entity using an underlying
// * database table to ensure uniqueness.
// */
// TABLE,
//
// /**
// * Indicates that the persistence provider must assign
// * primary keys for the entity using database sequence column.
// */
// SEQUENCE,
//
// /**
// * Indicates that the persistence provider must assign
// * primary keys for the entity using database identity column.
// */
// IDENTITY,
//
// /**
// * Indicates that the persistence provider should pick an
// * appropriate strategy for the particular database. The
// * <code>AUTO</code> generation strategy may expect a database
// * resource to exist, or it may attempt to create one. A vendor
// * may provide documentation on how to create such resources
// * in the event that it does not support schema generation
// * or cannot create the schema resource at runtime.
// */
// AUTO,
//
// UUID
// }
// Path: yodao-examples/src/main/java/com/yoda/yodao/example/model/Hair.java
import java.io.Serializable;
import java.util.Date;
import com.yoda.yodao.annotation.Column;
import com.yoda.yodao.annotation.Entity;
import com.yoda.yodao.annotation.GeneratedValue;
import com.yoda.yodao.annotation.GenerationType;
import com.yoda.yodao.annotation.Id;
import com.yoda.yodao.annotation.Table;
package com.yoda.yodao.example.model;
/**
* 发型 实体
*
* @author wellor
* @version
* @date 2015-3-2
* @class Hair.java
*
*/
@Entity
@Table(name = "pho_hairHa")
public class Hair implements Serializable {
@Id
| @GeneratedValue(strategy = GenerationType.AUTO)
|
sandin/YoDao | yodao-compiler/src/main/java/com/yoda/yodao/internal/DaoMethod.java | // Path: yodao-compiler/src/main/java/com/yoda/yodao/internal/query/YoQuery.java
// public class YoQuery {
//
// public enum CRUD {
// CREATE, READ, UPDATE, DELETE, COUNT, RAW_SQL
// }
//
// private CRUD crud;
//
// private String name;
//
// private String entity;
//
// private String sql;
//
// private List<YoSelection> selections = new ArrayList<YoSelection>();
// private List<YoGroupBy> groupBys = new ArrayList<YoGroupBy>();
// private List<YoHaving> havings = new ArrayList<YoHaving>();
// private List<YoOrderBy> orderBys = new ArrayList<YoOrderBy>();
//
// public YoQuery selection(YoSelection section) {
// selections.add(section);
// return this;
// }
//
// public YoQuery having(YoHaving having) {
// havings.add(having);
// return this;
// }
//
// public YoQuery groupBy(YoGroupBy groupBy) {
// groupBys.add(groupBy);
// return this;
// }
//
// public YoQuery orderBys(YoOrderBy orderBy) {
// orderBys.add(orderBy);
// return this;
// }
//
// public CRUD getCrud() {
// return crud;
// }
//
// public void setCrud(CRUD crud) {
// this.crud = crud;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getEntity() {
// return entity;
// }
//
// public void setEntity(String entity) {
// this.entity = entity;
// }
//
// public List<YoSelection> getSelections() {
// return selections;
// }
//
// public void setSelections(List<YoSelection> selections) {
// this.selections = selections;
// }
//
// public List<YoGroupBy> getGroupBys() {
// return groupBys;
// }
//
// public void setGroupBys(List<YoGroupBy> groupBys) {
// this.groupBys = groupBys;
// }
//
// public List<YoHaving> getHavings() {
// return havings;
// }
//
// public void setHavings(List<YoHaving> havings) {
// this.havings = havings;
// }
//
// public List<YoOrderBy> getOrderBys() {
// return orderBys;
// }
//
// public void setOrderBys(List<YoOrderBy> orderBys) {
// this.orderBys = orderBys;
// }
//
// public String getSql() {
// return sql;
// }
//
// public void setSql(String sql) {
// this.sql = sql;
// }
//
// @Override
// public String toString() {
// return "YoQuery [crud=" + crud + ", name=" + name + ", entity="
// + entity + ", sql=" + sql + ", selections=" + selections
// + ", groupBys=" + groupBys + ", havings=" + havings
// + ", orderBys=" + orderBys + "]";
// }
//
// }
| import java.util.Arrays;
import com.yoda.yodao.internal.query.YoQuery;
import javax.lang.model.element.Element; | package com.yoda.yodao.internal;
public class DaoMethod {
private String methodName;
private DaoParam[] methodParams;
private String returnType;
private String sql;
| // Path: yodao-compiler/src/main/java/com/yoda/yodao/internal/query/YoQuery.java
// public class YoQuery {
//
// public enum CRUD {
// CREATE, READ, UPDATE, DELETE, COUNT, RAW_SQL
// }
//
// private CRUD crud;
//
// private String name;
//
// private String entity;
//
// private String sql;
//
// private List<YoSelection> selections = new ArrayList<YoSelection>();
// private List<YoGroupBy> groupBys = new ArrayList<YoGroupBy>();
// private List<YoHaving> havings = new ArrayList<YoHaving>();
// private List<YoOrderBy> orderBys = new ArrayList<YoOrderBy>();
//
// public YoQuery selection(YoSelection section) {
// selections.add(section);
// return this;
// }
//
// public YoQuery having(YoHaving having) {
// havings.add(having);
// return this;
// }
//
// public YoQuery groupBy(YoGroupBy groupBy) {
// groupBys.add(groupBy);
// return this;
// }
//
// public YoQuery orderBys(YoOrderBy orderBy) {
// orderBys.add(orderBy);
// return this;
// }
//
// public CRUD getCrud() {
// return crud;
// }
//
// public void setCrud(CRUD crud) {
// this.crud = crud;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getEntity() {
// return entity;
// }
//
// public void setEntity(String entity) {
// this.entity = entity;
// }
//
// public List<YoSelection> getSelections() {
// return selections;
// }
//
// public void setSelections(List<YoSelection> selections) {
// this.selections = selections;
// }
//
// public List<YoGroupBy> getGroupBys() {
// return groupBys;
// }
//
// public void setGroupBys(List<YoGroupBy> groupBys) {
// this.groupBys = groupBys;
// }
//
// public List<YoHaving> getHavings() {
// return havings;
// }
//
// public void setHavings(List<YoHaving> havings) {
// this.havings = havings;
// }
//
// public List<YoOrderBy> getOrderBys() {
// return orderBys;
// }
//
// public void setOrderBys(List<YoOrderBy> orderBys) {
// this.orderBys = orderBys;
// }
//
// public String getSql() {
// return sql;
// }
//
// public void setSql(String sql) {
// this.sql = sql;
// }
//
// @Override
// public String toString() {
// return "YoQuery [crud=" + crud + ", name=" + name + ", entity="
// + entity + ", sql=" + sql + ", selections=" + selections
// + ", groupBys=" + groupBys + ", havings=" + havings
// + ", orderBys=" + orderBys + "]";
// }
//
// }
// Path: yodao-compiler/src/main/java/com/yoda/yodao/internal/DaoMethod.java
import java.util.Arrays;
import com.yoda.yodao.internal.query.YoQuery;
import javax.lang.model.element.Element;
package com.yoda.yodao.internal;
public class DaoMethod {
private String methodName;
private DaoParam[] methodParams;
private String returnType;
private String sql;
| private YoQuery query; |
sandin/YoDao | yodao-compiler/src/main/java/com/yoda/yodao/internal/YodaoProcessor.java | // Path: yodao-annotations/src/main/java/com/yoda/yodao/annotation/GenerationType.java
// public enum GenerationType {
//
// /**
// * Indicates that the persistence provider must assign
// * primary keys for the entity using an underlying
// * database table to ensure uniqueness.
// */
// TABLE,
//
// /**
// * Indicates that the persistence provider must assign
// * primary keys for the entity using database sequence column.
// */
// SEQUENCE,
//
// /**
// * Indicates that the persistence provider must assign
// * primary keys for the entity using database identity column.
// */
// IDENTITY,
//
// /**
// * Indicates that the persistence provider should pick an
// * appropriate strategy for the particular database. The
// * <code>AUTO</code> generation strategy may expect a database
// * resource to exist, or it may attempt to create one. A vendor
// * may provide documentation on how to create such resources
// * in the event that it does not support schema generation
// * or cannot create the schema resource at runtime.
// */
// AUTO,
//
// UUID
// }
| import static javax.tools.Diagnostic.Kind.ERROR;
import static javax.tools.Diagnostic.Kind.NOTE;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.JavaFileObject;
import com.google.auto.service.AutoService;
import com.yoda.yodao.annotation.Column;
import com.yoda.yodao.annotation.Entity;
import com.yoda.yodao.annotation.GeneratedValue;
import com.yoda.yodao.annotation.GenerationType;
import com.yoda.yodao.annotation.Id;
import com.yoda.yodao.annotation.JoinColumn;
import com.yoda.yodao.annotation.ManyToMany;
import com.yoda.yodao.annotation.ManyToOne;
import com.yoda.yodao.annotation.NotColumn;
import com.yoda.yodao.annotation.OneToMany;
import com.yoda.yodao.annotation.OneToOne;
import com.yoda.yodao.annotation.Repository;
| return element.asType().toString();
}
return null;
}
private String getColumnType(Element element) {
if (element != null) {
return element.asType().toString();
}
return null;
}
private String getColumnName(Element element) {
String columnName = null;
Column column = element.getAnnotation(Column.class);
Id id = element.getAnnotation(Id.class);
if (column != null) {
columnName = column.name();
}
// is id or name is empty
if (columnName == null || columnName.length() == 0) {
columnName = Utils.toLowerCase(element.getSimpleName().toString()); // field
// name
}
return columnName;
}
private Field.IdGenerator getIdGenerator(Element element) {
GeneratedValue gv = element.getAnnotation(GeneratedValue.class);
if (gv != null) {
| // Path: yodao-annotations/src/main/java/com/yoda/yodao/annotation/GenerationType.java
// public enum GenerationType {
//
// /**
// * Indicates that the persistence provider must assign
// * primary keys for the entity using an underlying
// * database table to ensure uniqueness.
// */
// TABLE,
//
// /**
// * Indicates that the persistence provider must assign
// * primary keys for the entity using database sequence column.
// */
// SEQUENCE,
//
// /**
// * Indicates that the persistence provider must assign
// * primary keys for the entity using database identity column.
// */
// IDENTITY,
//
// /**
// * Indicates that the persistence provider should pick an
// * appropriate strategy for the particular database. The
// * <code>AUTO</code> generation strategy may expect a database
// * resource to exist, or it may attempt to create one. A vendor
// * may provide documentation on how to create such resources
// * in the event that it does not support schema generation
// * or cannot create the schema resource at runtime.
// */
// AUTO,
//
// UUID
// }
// Path: yodao-compiler/src/main/java/com/yoda/yodao/internal/YodaoProcessor.java
import static javax.tools.Diagnostic.Kind.ERROR;
import static javax.tools.Diagnostic.Kind.NOTE;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import javax.tools.JavaFileObject;
import com.google.auto.service.AutoService;
import com.yoda.yodao.annotation.Column;
import com.yoda.yodao.annotation.Entity;
import com.yoda.yodao.annotation.GeneratedValue;
import com.yoda.yodao.annotation.GenerationType;
import com.yoda.yodao.annotation.Id;
import com.yoda.yodao.annotation.JoinColumn;
import com.yoda.yodao.annotation.ManyToMany;
import com.yoda.yodao.annotation.ManyToOne;
import com.yoda.yodao.annotation.NotColumn;
import com.yoda.yodao.annotation.OneToMany;
import com.yoda.yodao.annotation.OneToOne;
import com.yoda.yodao.annotation.Repository;
return element.asType().toString();
}
return null;
}
private String getColumnType(Element element) {
if (element != null) {
return element.asType().toString();
}
return null;
}
private String getColumnName(Element element) {
String columnName = null;
Column column = element.getAnnotation(Column.class);
Id id = element.getAnnotation(Id.class);
if (column != null) {
columnName = column.name();
}
// is id or name is empty
if (columnName == null || columnName.length() == 0) {
columnName = Utils.toLowerCase(element.getSimpleName().toString()); // field
// name
}
return columnName;
}
private Field.IdGenerator getIdGenerator(Element element) {
GeneratedValue gv = element.getAnnotation(GeneratedValue.class);
if (gv != null) {
| GenerationType gt = gv.strategy();
|
sandin/YoDao | yodao-examples/src/main/java/com/yoda/yodao/example/model/User.java | // Path: yodao-annotations/src/main/java/com/yoda/yodao/annotation/GenerationType.java
// public enum GenerationType {
//
// /**
// * Indicates that the persistence provider must assign
// * primary keys for the entity using an underlying
// * database table to ensure uniqueness.
// */
// TABLE,
//
// /**
// * Indicates that the persistence provider must assign
// * primary keys for the entity using database sequence column.
// */
// SEQUENCE,
//
// /**
// * Indicates that the persistence provider must assign
// * primary keys for the entity using database identity column.
// */
// IDENTITY,
//
// /**
// * Indicates that the persistence provider should pick an
// * appropriate strategy for the particular database. The
// * <code>AUTO</code> generation strategy may expect a database
// * resource to exist, or it may attempt to create one. A vendor
// * may provide documentation on how to create such resources
// * in the event that it does not support schema generation
// * or cannot create the schema resource at runtime.
// */
// AUTO,
//
// UUID
// }
| import com.yoda.yodao.annotation.Column;
import com.yoda.yodao.annotation.Entity;
import com.yoda.yodao.annotation.GeneratedValue;
import com.yoda.yodao.annotation.GenerationType;
import com.yoda.yodao.annotation.Id;
import com.yoda.yodao.annotation.Table;
import java.io.Serializable;
| package com.yoda.yodao.example.model;
/**
* Created by lds on 2016/4/14.
*/
@Entity
@Table(name="user")
public class User implements Serializable {
@Id
| // Path: yodao-annotations/src/main/java/com/yoda/yodao/annotation/GenerationType.java
// public enum GenerationType {
//
// /**
// * Indicates that the persistence provider must assign
// * primary keys for the entity using an underlying
// * database table to ensure uniqueness.
// */
// TABLE,
//
// /**
// * Indicates that the persistence provider must assign
// * primary keys for the entity using database sequence column.
// */
// SEQUENCE,
//
// /**
// * Indicates that the persistence provider must assign
// * primary keys for the entity using database identity column.
// */
// IDENTITY,
//
// /**
// * Indicates that the persistence provider should pick an
// * appropriate strategy for the particular database. The
// * <code>AUTO</code> generation strategy may expect a database
// * resource to exist, or it may attempt to create one. A vendor
// * may provide documentation on how to create such resources
// * in the event that it does not support schema generation
// * or cannot create the schema resource at runtime.
// */
// AUTO,
//
// UUID
// }
// Path: yodao-examples/src/main/java/com/yoda/yodao/example/model/User.java
import com.yoda.yodao.annotation.Column;
import com.yoda.yodao.annotation.Entity;
import com.yoda.yodao.annotation.GeneratedValue;
import com.yoda.yodao.annotation.GenerationType;
import com.yoda.yodao.annotation.Id;
import com.yoda.yodao.annotation.Table;
import java.io.Serializable;
package com.yoda.yodao.example.model;
/**
* Created by lds on 2016/4/14.
*/
@Entity
@Table(name="user")
public class User implements Serializable {
@Id
| @GeneratedValue(strategy = GenerationType.AUTO)
|
kawasima/falchion | falchion-container/src/main/java/net/unit8/falchion/Bootstrap.java | // Path: falchion-container/src/main/java/net/unit8/falchion/evaluator/EvaluatorSupplier.java
// public enum EvaluatorSupplier {
// MIN_GC_TIME(MinGcTime::new),
// MIN_FULL_GC_COUNT(MinFullGcCount::new);
//
// EvaluatorSupplier(Supplier<Evaluator> supplier) {
// this.supplier = supplier;
// }
//
// Supplier<Evaluator> supplier;
//
// public Evaluator createEvaluator() {
// return supplier.get();
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/monitor/MonitorSupplier.java
// public enum MonitorSupplier {
// GCUTIL_JSTAT(JstatMonitor::new),
// METRICS_JMX(MetricsJmxMonitor::new);
//
// private Supplier<JvmMonitor> monitorSupplier;
//
// MonitorSupplier(Supplier<JvmMonitor> monitorSupplier) {
// this.monitorSupplier = monitorSupplier;
// }
//
// public JvmMonitor createMonitor() {
// return monitorSupplier.get();
// }
// }
| import net.unit8.falchion.evaluator.EvaluatorSupplier;
import net.unit8.falchion.monitor.MonitorSupplier;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import org.kohsuke.args4j.spi.Messages;
import org.kohsuke.args4j.spi.StringArrayOptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.Signal;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors; | package net.unit8.falchion;
/**
* Bootstraps JVM container.
*
* @author kawasima
*/
public class Bootstrap {
private static final Logger LOG = LoggerFactory.getLogger(Bootstrap.class);
private static final Signal HUP = new Signal("HUP");
private static final Signal TERM = new Signal("TERM");
@Option(name = "-cp", usage = "Class search path of directories and zip/jar files",
metaVar = "CLASSPATH")
private String classpath;
@Option(name = "-m", usage = "name of JVM process monitor", handler = StringArrayOptionHandler.class)
private String[] monitors = {};
@Option(name = "-p", usage = "size of JVM processes", metaVar = "SIZE")
private int poolSize = 1;
@Option(name = "--admin-port", usage = "a port number of the api server", metaVar = "PORT")
private int adminPort = 44010;
@Option(name = "--auto-tuning", usage = "tuning JVM parameter automatically")
private boolean autoTuning = false;
@Option(name = "--evaluator", usage ="JVM parameter evaluator")
private String evaluator;
@Option(name = "--lifetime", usage = "lifetime of a jvm process",
metaVar = "SEC")
private long lifetime = 0;
@Option(name = "-basedir", usage = "base directory of zip/jar files")
private String basedir;
@Option(name = "-v", usage = "application version")
private String aplVersion;
@Option(name = "--java-opts", usage = "options for worker processes",
metaVar = "JAVA_OPTS")
private String javaOpts;
/** @noinspection MismatchedQueryAndUpdateOfCollection*/
@Argument
private List<String> arguments = new ArrayList<>();
public void doMain(String... args) {
CmdLineParser parser = new CmdLineParser(this);
try {
parser.parseArgument(args);
if (arguments.isEmpty()) {
throw new CmdLineException(parser, Messages.DEFAULT_META_EXPLICIT_BOOLEAN_OPTION_HANDLER);
}
} catch (CmdLineException ex) {
ex.printStackTrace();
parser.printUsage(System.err);
return;
}
LOG.info("monitors={}", Arrays.asList(monitors)); | // Path: falchion-container/src/main/java/net/unit8/falchion/evaluator/EvaluatorSupplier.java
// public enum EvaluatorSupplier {
// MIN_GC_TIME(MinGcTime::new),
// MIN_FULL_GC_COUNT(MinFullGcCount::new);
//
// EvaluatorSupplier(Supplier<Evaluator> supplier) {
// this.supplier = supplier;
// }
//
// Supplier<Evaluator> supplier;
//
// public Evaluator createEvaluator() {
// return supplier.get();
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/monitor/MonitorSupplier.java
// public enum MonitorSupplier {
// GCUTIL_JSTAT(JstatMonitor::new),
// METRICS_JMX(MetricsJmxMonitor::new);
//
// private Supplier<JvmMonitor> monitorSupplier;
//
// MonitorSupplier(Supplier<JvmMonitor> monitorSupplier) {
// this.monitorSupplier = monitorSupplier;
// }
//
// public JvmMonitor createMonitor() {
// return monitorSupplier.get();
// }
// }
// Path: falchion-container/src/main/java/net/unit8/falchion/Bootstrap.java
import net.unit8.falchion.evaluator.EvaluatorSupplier;
import net.unit8.falchion.monitor.MonitorSupplier;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import org.kohsuke.args4j.spi.Messages;
import org.kohsuke.args4j.spi.StringArrayOptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.Signal;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
package net.unit8.falchion;
/**
* Bootstraps JVM container.
*
* @author kawasima
*/
public class Bootstrap {
private static final Logger LOG = LoggerFactory.getLogger(Bootstrap.class);
private static final Signal HUP = new Signal("HUP");
private static final Signal TERM = new Signal("TERM");
@Option(name = "-cp", usage = "Class search path of directories and zip/jar files",
metaVar = "CLASSPATH")
private String classpath;
@Option(name = "-m", usage = "name of JVM process monitor", handler = StringArrayOptionHandler.class)
private String[] monitors = {};
@Option(name = "-p", usage = "size of JVM processes", metaVar = "SIZE")
private int poolSize = 1;
@Option(name = "--admin-port", usage = "a port number of the api server", metaVar = "PORT")
private int adminPort = 44010;
@Option(name = "--auto-tuning", usage = "tuning JVM parameter automatically")
private boolean autoTuning = false;
@Option(name = "--evaluator", usage ="JVM parameter evaluator")
private String evaluator;
@Option(name = "--lifetime", usage = "lifetime of a jvm process",
metaVar = "SEC")
private long lifetime = 0;
@Option(name = "-basedir", usage = "base directory of zip/jar files")
private String basedir;
@Option(name = "-v", usage = "application version")
private String aplVersion;
@Option(name = "--java-opts", usage = "options for worker processes",
metaVar = "JAVA_OPTS")
private String javaOpts;
/** @noinspection MismatchedQueryAndUpdateOfCollection*/
@Argument
private List<String> arguments = new ArrayList<>();
public void doMain(String... args) {
CmdLineParser parser = new CmdLineParser(this);
try {
parser.parseArgument(args);
if (arguments.isEmpty()) {
throw new CmdLineException(parser, Messages.DEFAULT_META_EXPLICIT_BOOLEAN_OPTION_HANDLER);
}
} catch (CmdLineException ex) {
ex.printStackTrace();
parser.printUsage(System.err);
return;
}
LOG.info("monitors={}", Arrays.asList(monitors)); | Set<MonitorSupplier> monitorSuppliers = Arrays.stream(monitors) |
kawasima/falchion | falchion-container/src/main/java/net/unit8/falchion/Bootstrap.java | // Path: falchion-container/src/main/java/net/unit8/falchion/evaluator/EvaluatorSupplier.java
// public enum EvaluatorSupplier {
// MIN_GC_TIME(MinGcTime::new),
// MIN_FULL_GC_COUNT(MinFullGcCount::new);
//
// EvaluatorSupplier(Supplier<Evaluator> supplier) {
// this.supplier = supplier;
// }
//
// Supplier<Evaluator> supplier;
//
// public Evaluator createEvaluator() {
// return supplier.get();
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/monitor/MonitorSupplier.java
// public enum MonitorSupplier {
// GCUTIL_JSTAT(JstatMonitor::new),
// METRICS_JMX(MetricsJmxMonitor::new);
//
// private Supplier<JvmMonitor> monitorSupplier;
//
// MonitorSupplier(Supplier<JvmMonitor> monitorSupplier) {
// this.monitorSupplier = monitorSupplier;
// }
//
// public JvmMonitor createMonitor() {
// return monitorSupplier.get();
// }
// }
| import net.unit8.falchion.evaluator.EvaluatorSupplier;
import net.unit8.falchion.monitor.MonitorSupplier;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import org.kohsuke.args4j.spi.Messages;
import org.kohsuke.args4j.spi.StringArrayOptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.Signal;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors; | package net.unit8.falchion;
/**
* Bootstraps JVM container.
*
* @author kawasima
*/
public class Bootstrap {
private static final Logger LOG = LoggerFactory.getLogger(Bootstrap.class);
private static final Signal HUP = new Signal("HUP");
private static final Signal TERM = new Signal("TERM");
@Option(name = "-cp", usage = "Class search path of directories and zip/jar files",
metaVar = "CLASSPATH")
private String classpath;
@Option(name = "-m", usage = "name of JVM process monitor", handler = StringArrayOptionHandler.class)
private String[] monitors = {};
@Option(name = "-p", usage = "size of JVM processes", metaVar = "SIZE")
private int poolSize = 1;
@Option(name = "--admin-port", usage = "a port number of the api server", metaVar = "PORT")
private int adminPort = 44010;
@Option(name = "--auto-tuning", usage = "tuning JVM parameter automatically")
private boolean autoTuning = false;
@Option(name = "--evaluator", usage ="JVM parameter evaluator")
private String evaluator;
@Option(name = "--lifetime", usage = "lifetime of a jvm process",
metaVar = "SEC")
private long lifetime = 0;
@Option(name = "-basedir", usage = "base directory of zip/jar files")
private String basedir;
@Option(name = "-v", usage = "application version")
private String aplVersion;
@Option(name = "--java-opts", usage = "options for worker processes",
metaVar = "JAVA_OPTS")
private String javaOpts;
/** @noinspection MismatchedQueryAndUpdateOfCollection*/
@Argument
private List<String> arguments = new ArrayList<>();
public void doMain(String... args) {
CmdLineParser parser = new CmdLineParser(this);
try {
parser.parseArgument(args);
if (arguments.isEmpty()) {
throw new CmdLineException(parser, Messages.DEFAULT_META_EXPLICIT_BOOLEAN_OPTION_HANDLER);
}
} catch (CmdLineException ex) {
ex.printStackTrace();
parser.printUsage(System.err);
return;
}
LOG.info("monitors={}", Arrays.asList(monitors));
Set<MonitorSupplier> monitorSuppliers = Arrays.stream(monitors)
.map(MonitorSupplier::valueOf)
.collect(Collectors.toSet());
Container container = new Container(poolSize);
container.setMonitorSuppliers(monitorSuppliers);
container.setAutoTuning(autoTuning);
container.setBasedir(basedir);
if (evaluator != null) { | // Path: falchion-container/src/main/java/net/unit8/falchion/evaluator/EvaluatorSupplier.java
// public enum EvaluatorSupplier {
// MIN_GC_TIME(MinGcTime::new),
// MIN_FULL_GC_COUNT(MinFullGcCount::new);
//
// EvaluatorSupplier(Supplier<Evaluator> supplier) {
// this.supplier = supplier;
// }
//
// Supplier<Evaluator> supplier;
//
// public Evaluator createEvaluator() {
// return supplier.get();
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/monitor/MonitorSupplier.java
// public enum MonitorSupplier {
// GCUTIL_JSTAT(JstatMonitor::new),
// METRICS_JMX(MetricsJmxMonitor::new);
//
// private Supplier<JvmMonitor> monitorSupplier;
//
// MonitorSupplier(Supplier<JvmMonitor> monitorSupplier) {
// this.monitorSupplier = monitorSupplier;
// }
//
// public JvmMonitor createMonitor() {
// return monitorSupplier.get();
// }
// }
// Path: falchion-container/src/main/java/net/unit8/falchion/Bootstrap.java
import net.unit8.falchion.evaluator.EvaluatorSupplier;
import net.unit8.falchion.monitor.MonitorSupplier;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import org.kohsuke.args4j.spi.Messages;
import org.kohsuke.args4j.spi.StringArrayOptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.Signal;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
package net.unit8.falchion;
/**
* Bootstraps JVM container.
*
* @author kawasima
*/
public class Bootstrap {
private static final Logger LOG = LoggerFactory.getLogger(Bootstrap.class);
private static final Signal HUP = new Signal("HUP");
private static final Signal TERM = new Signal("TERM");
@Option(name = "-cp", usage = "Class search path of directories and zip/jar files",
metaVar = "CLASSPATH")
private String classpath;
@Option(name = "-m", usage = "name of JVM process monitor", handler = StringArrayOptionHandler.class)
private String[] monitors = {};
@Option(name = "-p", usage = "size of JVM processes", metaVar = "SIZE")
private int poolSize = 1;
@Option(name = "--admin-port", usage = "a port number of the api server", metaVar = "PORT")
private int adminPort = 44010;
@Option(name = "--auto-tuning", usage = "tuning JVM parameter automatically")
private boolean autoTuning = false;
@Option(name = "--evaluator", usage ="JVM parameter evaluator")
private String evaluator;
@Option(name = "--lifetime", usage = "lifetime of a jvm process",
metaVar = "SEC")
private long lifetime = 0;
@Option(name = "-basedir", usage = "base directory of zip/jar files")
private String basedir;
@Option(name = "-v", usage = "application version")
private String aplVersion;
@Option(name = "--java-opts", usage = "options for worker processes",
metaVar = "JAVA_OPTS")
private String javaOpts;
/** @noinspection MismatchedQueryAndUpdateOfCollection*/
@Argument
private List<String> arguments = new ArrayList<>();
public void doMain(String... args) {
CmdLineParser parser = new CmdLineParser(this);
try {
parser.parseArgument(args);
if (arguments.isEmpty()) {
throw new CmdLineException(parser, Messages.DEFAULT_META_EXPLICIT_BOOLEAN_OPTION_HANDLER);
}
} catch (CmdLineException ex) {
ex.printStackTrace();
parser.printUsage(System.err);
return;
}
LOG.info("monitors={}", Arrays.asList(monitors));
Set<MonitorSupplier> monitorSuppliers = Arrays.stream(monitors)
.map(MonitorSupplier::valueOf)
.collect(Collectors.toSet());
Container container = new Container(poolSize);
container.setMonitorSuppliers(monitorSuppliers);
container.setAutoTuning(autoTuning);
container.setBasedir(basedir);
if (evaluator != null) { | container.setEvaluator(EvaluatorSupplier.valueOf(evaluator).createEvaluator()); |
kawasima/falchion | falchion-container/src/main/java/net/unit8/falchion/JvmPool.java | // Path: falchion-container/src/main/java/net/unit8/falchion/supplier/AutoOptimizableProcessSupplier.java
// public class AutoOptimizableProcessSupplier implements Supplier<JvmProcess> {
// private static final Logger LOG = LoggerFactory.getLogger(AutoOptimizableProcessSupplier.class);
//
// private StandardOptionProvider standardOptionProvider;
// private Evaluator evaluator;
// private Supplier<JvmProcess> baseSupplier;
// private double variance = 0.1;
//
// public AutoOptimizableProcessSupplier(Supplier<JvmProcess> baseSupplier, Evaluator evaluator) {
// this.baseSupplier = baseSupplier;
// this.evaluator = evaluator;
// standardOptionProvider = new StandardOptionProvider(128, 128, variance);
// }
//
// @Override
// public JvmProcess get() {
// JvmProcess process = baseSupplier.get();
// List<String> options = new ArrayList<>(standardOptionProvider.getOptions());
// process.setJvmOptions(options);
// return process;
// }
//
// public void feedback(Collection<JvmProcess> processes) {
// JvmProcess best = evaluator.evaluate(processes);
// LOG.info("best param {}", best.getJvmOptions());
// standardOptionProvider = new StandardOptionProvider(String.join(" ", best.getJvmOptions()), variance);
// }
// }
| import net.unit8.falchion.supplier.AutoOptimizableProcessSupplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream; | if (autofill) fill();
}
});
}
public JvmProcess create() {
JvmProcess process = processSupplier.get();
if (Objects.nonNull(classpath)) {
process.setClasspath(classpath);
}
Future<JvmResult> future = jvmCompletionService.submit(process);
processes.put(process.getId(), new ProcessHolder(process, future));
LOG.info("create new JVM (id={}, pid={})", process.getId(), process.getPid());
return process;
}
public void fill() {
while (processes.size() < poolSize) {
create();
}
}
public void refresh() throws IOException {
Set<JvmProcess> oldProcesses = processes.values().stream()
.map(ProcessHolder::getProcess)
.collect(Collectors.toSet());
// If process supplier is instance of AutoOptimizableProcessSupplier,
// feedback current monitoring value to supplier.
Stream.of(processSupplier) | // Path: falchion-container/src/main/java/net/unit8/falchion/supplier/AutoOptimizableProcessSupplier.java
// public class AutoOptimizableProcessSupplier implements Supplier<JvmProcess> {
// private static final Logger LOG = LoggerFactory.getLogger(AutoOptimizableProcessSupplier.class);
//
// private StandardOptionProvider standardOptionProvider;
// private Evaluator evaluator;
// private Supplier<JvmProcess> baseSupplier;
// private double variance = 0.1;
//
// public AutoOptimizableProcessSupplier(Supplier<JvmProcess> baseSupplier, Evaluator evaluator) {
// this.baseSupplier = baseSupplier;
// this.evaluator = evaluator;
// standardOptionProvider = new StandardOptionProvider(128, 128, variance);
// }
//
// @Override
// public JvmProcess get() {
// JvmProcess process = baseSupplier.get();
// List<String> options = new ArrayList<>(standardOptionProvider.getOptions());
// process.setJvmOptions(options);
// return process;
// }
//
// public void feedback(Collection<JvmProcess> processes) {
// JvmProcess best = evaluator.evaluate(processes);
// LOG.info("best param {}", best.getJvmOptions());
// standardOptionProvider = new StandardOptionProvider(String.join(" ", best.getJvmOptions()), variance);
// }
// }
// Path: falchion-container/src/main/java/net/unit8/falchion/JvmPool.java
import net.unit8.falchion.supplier.AutoOptimizableProcessSupplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
if (autofill) fill();
}
});
}
public JvmProcess create() {
JvmProcess process = processSupplier.get();
if (Objects.nonNull(classpath)) {
process.setClasspath(classpath);
}
Future<JvmResult> future = jvmCompletionService.submit(process);
processes.put(process.getId(), new ProcessHolder(process, future));
LOG.info("create new JVM (id={}, pid={})", process.getId(), process.getPid());
return process;
}
public void fill() {
while (processes.size() < poolSize) {
create();
}
}
public void refresh() throws IOException {
Set<JvmProcess> oldProcesses = processes.values().stream()
.map(ProcessHolder::getProcess)
.collect(Collectors.toSet());
// If process supplier is instance of AutoOptimizableProcessSupplier,
// feedback current monitoring value to supplier.
Stream.of(processSupplier) | .filter(AutoOptimizableProcessSupplier.class::isInstance) |
kawasima/falchion | falchion-container/src/main/java/net/unit8/falchion/option/provider/StandardOptionProvider.java | // Path: falchion-container/src/main/java/net/unit8/falchion/option/JvmType.java
// public enum JvmType {
// SERVER("-server"),
// CLIENT("-client");
//
// private String optionValue;
//
// JvmType(String optionValue) {
// this.optionValue = optionValue;
// }
//
// public String getOptionValue() {
// return optionValue;
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/option/sampler/LongSampler.java
// public class LongSampler {
// private Random random = new Random();
// private long init;
// private double variance = 0.0;
// private Long min;
// private Long max;
//
// public LongSampler(long init) {
// this(init, 0.0);
// }
//
// public LongSampler(long init, double variance) {
// this(init, variance, null, null);
// }
//
// public LongSampler(long init, double variance, Long min, Long max) {
// this.init = init;
// this.variance = variance;
// this.min = min;
// this.max = max;
// }
//
// public long getValue() {
// long val = init + (long) (random.nextGaussian() * variance);
// if (min != null && val < min) {
// val = min;
// }
// if (max != null && val > max) {
// val = max;
// }
// return val;
// }
//
// public void setVariance(double variance) {
// this.variance = variance;
// }
//
// public void setMax(long max) {
// this.max = max;
// }
//
// public void setMin(long min) {
// this.min = min;
// }
//
// @Override
// public String toString() {
// return "LongSampler{" +
// "init=" + init +
// ", variance=" + variance +
// ", min=" + min +
// ", max=" + max +
// '}';
// }
// }
| import net.unit8.falchion.option.JvmType;
import net.unit8.falchion.option.sampler.LongSampler;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.regex.Pattern; | package net.unit8.falchion.option.provider;
/**
* @author kawasima
*/
public class StandardOptionProvider implements OptionProvider {
private JvmType jvmType = JvmType.SERVER; | // Path: falchion-container/src/main/java/net/unit8/falchion/option/JvmType.java
// public enum JvmType {
// SERVER("-server"),
// CLIENT("-client");
//
// private String optionValue;
//
// JvmType(String optionValue) {
// this.optionValue = optionValue;
// }
//
// public String getOptionValue() {
// return optionValue;
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/option/sampler/LongSampler.java
// public class LongSampler {
// private Random random = new Random();
// private long init;
// private double variance = 0.0;
// private Long min;
// private Long max;
//
// public LongSampler(long init) {
// this(init, 0.0);
// }
//
// public LongSampler(long init, double variance) {
// this(init, variance, null, null);
// }
//
// public LongSampler(long init, double variance, Long min, Long max) {
// this.init = init;
// this.variance = variance;
// this.min = min;
// this.max = max;
// }
//
// public long getValue() {
// long val = init + (long) (random.nextGaussian() * variance);
// if (min != null && val < min) {
// val = min;
// }
// if (max != null && val > max) {
// val = max;
// }
// return val;
// }
//
// public void setVariance(double variance) {
// this.variance = variance;
// }
//
// public void setMax(long max) {
// this.max = max;
// }
//
// public void setMin(long min) {
// this.min = min;
// }
//
// @Override
// public String toString() {
// return "LongSampler{" +
// "init=" + init +
// ", variance=" + variance +
// ", min=" + min +
// ", max=" + max +
// '}';
// }
// }
// Path: falchion-container/src/main/java/net/unit8/falchion/option/provider/StandardOptionProvider.java
import net.unit8.falchion.option.JvmType;
import net.unit8.falchion.option.sampler.LongSampler;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.regex.Pattern;
package net.unit8.falchion.option.provider;
/**
* @author kawasima
*/
public class StandardOptionProvider implements OptionProvider {
private JvmType jvmType = JvmType.SERVER; | private LongSampler initialHeap; |
kawasima/falchion | falchion-container/src/main/java/net/unit8/falchion/evaluator/Evaluator.java | // Path: falchion-container/src/main/java/net/unit8/falchion/JvmProcess.java
// public class JvmProcess implements Callable<JvmResult> {
// private static final Logger LOG = LoggerFactory.getLogger(JvmProcess.class);
//
// private static final DateTimeFormatter fmtIO = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
//
// private final String id;
// private long pid = -1;
// private final String mainClass;
// private String classpath;
// private List<String> jvmOptions;
//
// private final ProcessBuilder processBuilder;
// private transient Process process;
// private long startedAt;
// private final CompletableFuture<Void> ready;
//
// private final Set<JvmMonitor> monitors;
//
// private static final String ID_CHARS = "0123456789abcdefghijklmnopqrstuvwxyz";
//
// private String generateId(int length) {
// return new Random().ints(0, ID_CHARS.length())
// .mapToObj(ID_CHARS::charAt)
// .limit(length)
// .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
// .toString();
// }
//
// public JvmProcess(String mainClass, String classpath) {
// this.id = generateId(5);
// this.mainClass = mainClass;
// this.classpath = classpath;
// this.ready = new CompletableFuture<>();
// this.monitors = new HashSet<>();
//
// processBuilder = new ProcessBuilder().inheritIO();
// }
//
// public CompletableFuture<Void> waitForReady() {
// return ready;
// }
//
// public void ready() {
// ready.complete(null);
// monitors.forEach(m -> m.start(this));
// }
//
// @Override
// public JvmResult call() throws Exception {
// String javaHome = System.getProperty("java.home");
// List<String> commandArgs = new ArrayList<>(Arrays.asList(javaHome + "/bin/java", "-cp", classpath));
// if (jvmOptions != null) {
// commandArgs.addAll(jvmOptions);
// }
// commandArgs.add(mainClass);
// processBuilder.command(commandArgs);
// try {
// process = processBuilder.start();
// startedAt = System.currentTimeMillis();
// pid = process.pid();
// LOG.info("process started: id={}, pid={}", id, pid);
//
// //return new JvmResult(id, pid, process.waitFor());
// return new JvmResult(id, pid, process.onExit()
// .whenComplete((result, ex) -> {
// if (ex == null) {
//
// }
// })
// .get().exitValue());
// } catch (InterruptedException ex) {
// LOG.info("process interrupted: id={}, pid={}", id, pid);
// try {
// process.waitFor(3, TimeUnit.SECONDS);
// } catch (InterruptedException ignore) {
// }
// process.destroy();
// LOG.info("process destroy: id={}, pid={}", id, pid);
// return new JvmResult(id, pid, -1);
// } catch (Exception ex) {
// LOG.error("Process start failure", ex);
// throw ex;
// } finally {
// monitors.forEach(JvmMonitor::stop);
//
// if (process != null) {
// process.getInputStream().close();
// process.getOutputStream().close();
// process.getErrorStream().close();
// }
// }
// }
//
// public String getId() {
// return id;
// }
//
// public long getPid() {
// return pid;
// }
//
// public long getUptime(){
// return System.currentTimeMillis() - startedAt;
// }
//
// public String getMainClass() {
// return mainClass;
// }
//
// public void addMonitor(JvmMonitor... monitors) {
// this.monitors.addAll(Arrays.asList(monitors));
// }
//
// public void kill() throws IOException {
// try {
// Process killProcess = new ProcessBuilder("kill", "-TERM", Long.toString(pid)).start();
// int killResult = killProcess.waitFor();
// if (killResult != 0)
// throw new IOException("kill " + pid + " is failure");
// } catch (InterruptedException ex) {
// LOG.warn("Kill the process (pid={}) is canceled.", pid);
// }
// }
//
// public void setIoDir(File directory) {
// if (process != null) {
// throw new IllegalStateException("You should call setIoDir before starting process");
// }
// String prefix = fmtIO.format(LocalDateTime.now()) + "." + id;
// processBuilder
// .redirectError(new File(directory, prefix + ".err"))
// .redirectOutput(new File(directory, prefix + ".out"));
// }
//
// public List<MonitorStat> getMonitorStats() {
// return monitors.stream()
// .map(JvmMonitor::getStat)
// .collect(Collectors.toList());
// }
//
// public void setJvmOptions(List<String> options) {
// this.jvmOptions = options;
// }
//
// public List<String> getJvmOptions() {
// return jvmOptions;
// }
//
// void setClasspath(String classpath) {
// this.classpath = classpath;
// }
//
// @Override
// public String toString() {
// return "JvmProcess{id=" + id + ", pid=" + pid + "}";
// }
// }
| import net.unit8.falchion.JvmProcess;
import java.util.Collection; | package net.unit8.falchion.evaluator;
/**
* @author kawasima
*/
@FunctionalInterface
public interface Evaluator { | // Path: falchion-container/src/main/java/net/unit8/falchion/JvmProcess.java
// public class JvmProcess implements Callable<JvmResult> {
// private static final Logger LOG = LoggerFactory.getLogger(JvmProcess.class);
//
// private static final DateTimeFormatter fmtIO = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
//
// private final String id;
// private long pid = -1;
// private final String mainClass;
// private String classpath;
// private List<String> jvmOptions;
//
// private final ProcessBuilder processBuilder;
// private transient Process process;
// private long startedAt;
// private final CompletableFuture<Void> ready;
//
// private final Set<JvmMonitor> monitors;
//
// private static final String ID_CHARS = "0123456789abcdefghijklmnopqrstuvwxyz";
//
// private String generateId(int length) {
// return new Random().ints(0, ID_CHARS.length())
// .mapToObj(ID_CHARS::charAt)
// .limit(length)
// .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
// .toString();
// }
//
// public JvmProcess(String mainClass, String classpath) {
// this.id = generateId(5);
// this.mainClass = mainClass;
// this.classpath = classpath;
// this.ready = new CompletableFuture<>();
// this.monitors = new HashSet<>();
//
// processBuilder = new ProcessBuilder().inheritIO();
// }
//
// public CompletableFuture<Void> waitForReady() {
// return ready;
// }
//
// public void ready() {
// ready.complete(null);
// monitors.forEach(m -> m.start(this));
// }
//
// @Override
// public JvmResult call() throws Exception {
// String javaHome = System.getProperty("java.home");
// List<String> commandArgs = new ArrayList<>(Arrays.asList(javaHome + "/bin/java", "-cp", classpath));
// if (jvmOptions != null) {
// commandArgs.addAll(jvmOptions);
// }
// commandArgs.add(mainClass);
// processBuilder.command(commandArgs);
// try {
// process = processBuilder.start();
// startedAt = System.currentTimeMillis();
// pid = process.pid();
// LOG.info("process started: id={}, pid={}", id, pid);
//
// //return new JvmResult(id, pid, process.waitFor());
// return new JvmResult(id, pid, process.onExit()
// .whenComplete((result, ex) -> {
// if (ex == null) {
//
// }
// })
// .get().exitValue());
// } catch (InterruptedException ex) {
// LOG.info("process interrupted: id={}, pid={}", id, pid);
// try {
// process.waitFor(3, TimeUnit.SECONDS);
// } catch (InterruptedException ignore) {
// }
// process.destroy();
// LOG.info("process destroy: id={}, pid={}", id, pid);
// return new JvmResult(id, pid, -1);
// } catch (Exception ex) {
// LOG.error("Process start failure", ex);
// throw ex;
// } finally {
// monitors.forEach(JvmMonitor::stop);
//
// if (process != null) {
// process.getInputStream().close();
// process.getOutputStream().close();
// process.getErrorStream().close();
// }
// }
// }
//
// public String getId() {
// return id;
// }
//
// public long getPid() {
// return pid;
// }
//
// public long getUptime(){
// return System.currentTimeMillis() - startedAt;
// }
//
// public String getMainClass() {
// return mainClass;
// }
//
// public void addMonitor(JvmMonitor... monitors) {
// this.monitors.addAll(Arrays.asList(monitors));
// }
//
// public void kill() throws IOException {
// try {
// Process killProcess = new ProcessBuilder("kill", "-TERM", Long.toString(pid)).start();
// int killResult = killProcess.waitFor();
// if (killResult != 0)
// throw new IOException("kill " + pid + " is failure");
// } catch (InterruptedException ex) {
// LOG.warn("Kill the process (pid={}) is canceled.", pid);
// }
// }
//
// public void setIoDir(File directory) {
// if (process != null) {
// throw new IllegalStateException("You should call setIoDir before starting process");
// }
// String prefix = fmtIO.format(LocalDateTime.now()) + "." + id;
// processBuilder
// .redirectError(new File(directory, prefix + ".err"))
// .redirectOutput(new File(directory, prefix + ".out"));
// }
//
// public List<MonitorStat> getMonitorStats() {
// return monitors.stream()
// .map(JvmMonitor::getStat)
// .collect(Collectors.toList());
// }
//
// public void setJvmOptions(List<String> options) {
// this.jvmOptions = options;
// }
//
// public List<String> getJvmOptions() {
// return jvmOptions;
// }
//
// void setClasspath(String classpath) {
// this.classpath = classpath;
// }
//
// @Override
// public String toString() {
// return "JvmProcess{id=" + id + ", pid=" + pid + "}";
// }
// }
// Path: falchion-container/src/main/java/net/unit8/falchion/evaluator/Evaluator.java
import net.unit8.falchion.JvmProcess;
import java.util.Collection;
package net.unit8.falchion.evaluator;
/**
* @author kawasima
*/
@FunctionalInterface
public interface Evaluator { | JvmProcess evaluate(Collection<JvmProcess> processes); |
kawasima/falchion | falchion-example-enkan/src/main/java/net/unit8/falchion/example/ExampleApplicationFactory.java | // Path: falchion-example-enkan/src/main/java/net/unit8/falchion/example/controller/IndexController.java
// public class IndexController {
// @Inject
// private TemplateEngine templateEngine;
//
// public HttpResponse index() {
// return templateEngine.render("index",
// "message", "Hellooooooooooooooooooo");
// }
// }
| import enkan.Application;
import enkan.application.WebApplication;
import enkan.config.ApplicationFactory;
import enkan.endpoint.ResourceEndpoint;
import enkan.middleware.*;
import enkan.system.inject.ComponentInjector;
import kotowari.middleware.ControllerInvokerMiddleware;
import kotowari.middleware.FormMiddleware;
import kotowari.middleware.RenderTemplateMiddleware;
import kotowari.middleware.RoutingMiddleware;
import kotowari.routing.Routes;
import net.unit8.falchion.example.controller.IndexController;
import static enkan.util.Predicates.NONE; | package net.unit8.falchion.example;
public class ExampleApplicationFactory implements ApplicationFactory {
@Override
public Application create(ComponentInjector injector) {
WebApplication app = new WebApplication();
| // Path: falchion-example-enkan/src/main/java/net/unit8/falchion/example/controller/IndexController.java
// public class IndexController {
// @Inject
// private TemplateEngine templateEngine;
//
// public HttpResponse index() {
// return templateEngine.render("index",
// "message", "Hellooooooooooooooooooo");
// }
// }
// Path: falchion-example-enkan/src/main/java/net/unit8/falchion/example/ExampleApplicationFactory.java
import enkan.Application;
import enkan.application.WebApplication;
import enkan.config.ApplicationFactory;
import enkan.endpoint.ResourceEndpoint;
import enkan.middleware.*;
import enkan.system.inject.ComponentInjector;
import kotowari.middleware.ControllerInvokerMiddleware;
import kotowari.middleware.FormMiddleware;
import kotowari.middleware.RenderTemplateMiddleware;
import kotowari.middleware.RoutingMiddleware;
import kotowari.routing.Routes;
import net.unit8.falchion.example.controller.IndexController;
import static enkan.util.Predicates.NONE;
package net.unit8.falchion.example;
public class ExampleApplicationFactory implements ApplicationFactory {
@Override
public Application create(ComponentInjector injector) {
WebApplication app = new WebApplication();
| Routes routes = Routes.define(r -> r.get("/").to(IndexController.class, "index")).compile(); |
kawasima/falchion | falchion-container/src/main/java/net/unit8/falchion/ApiServer.java | // Path: falchion-container/src/main/java/net/unit8/falchion/api/ListJvmHandler.java
// public class ListJvmHandler extends AbstractApi {
// public ListJvmHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
// getContainer().getPool().getActiveProcesses().forEach(p ->
// arrayBuilder.add(Json.createObjectBuilder()
// .add("id", p.getId())
// .add("pid", p.getPid())));
//
// sendJson(exchange, arrayBuilder.build());
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/api/ReadyJvmHandler.java
// public class ReadyJvmHandler extends AbstractApi {
// private static final Pattern RE_ID = Pattern.compile("/([a-zA-Z0-9]+)/ready$");
//
// public ReadyJvmHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// Matcher m = RE_ID.matcher(exchange.getRequestURI().getPath());
// try {
// if (m.find()) {
// String id = m.group(1);
// JvmProcess process = getContainer()
// .getPool()
// .getProcessByPid(Long.parseLong(id));
// process.ready();
//
// sendNoContent(exchange);
// } else {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// } catch (Exception ex) {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/api/RefreshContainerHandler.java
// public class RefreshContainerHandler extends AbstractApi {
// private static final Logger LOG = LoggerFactory.getLogger(RefreshContainerHandler.class);
// private static final Pattern RE_ID = Pattern.compile("/refresh/([a-zA-Z0-9.-]+)$");
//
// public RefreshContainerHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// Matcher m = RE_ID.matcher(exchange.getRequestURI().getPath());
// Container container = getContainer();
// JvmPool pool = container.getPool();
// if (m.find()) {
// String version = m.group(1);
// String classpath = container.createClasspath(container.getBasedir(), version);
// if (Objects.equals(classpath, container.getBasedir())) {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// return;
// }
// pool.setClasspath(classpath);
// LOG.info("The version of the application has been changed. New version is '{}'", version);
// }
// pool.refresh();
// sendNoContent(exchange);
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/api/ShowJvmHandler.java
// public class ShowJvmHandler extends AbstractApi {
// private static final Logger LOG = LoggerFactory.getLogger(ShowJvmHandler.class);
// private static final Pattern RE_ID = Pattern.compile("/([a-zA-Z0-9]+)$");
//
// public ShowJvmHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// Matcher m = RE_ID.matcher(exchange.getRequestURI().getPath());
//
// try {
// if (m.find()) {
// String id = m.group(1);
// JsonObjectBuilder jvmStatus = Json.createObjectBuilder();
// JsonArrayBuilder monitorStats = Json.createArrayBuilder();
// JvmProcess process = getContainer()
// .getPool()
// .getProcess(id);
//
// process.getMonitorStats()
// .stream()
// .filter(Objects::nonNull)
// .map(MonitorStat::toJson)
// .forEach(monitorStats::add);
//
// jvmStatus.add("id", process.getId());
// jvmStatus.add("pid", process.getPid());
// jvmStatus.add("uptime", process.getUptime());
// jvmStatus.add("options", process.getJvmOptions().stream()
// .collect(Collectors.joining(" ")));
// jvmStatus.add("stats", monitorStats.build());
// sendJson(exchange, jvmStatus.build());
// } else {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// } catch (Exception ex) {
// LOG.error("", ex);
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// }
// }
| import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import me.geso.routes.RoutingResult;
import me.geso.routes.WebRouter;
import net.unit8.falchion.api.ListJvmHandler;
import net.unit8.falchion.api.ReadyJvmHandler;
import net.unit8.falchion.api.RefreshContainerHandler;
import net.unit8.falchion.api.ShowJvmHandler;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.InetSocketAddress;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; | package net.unit8.falchion;
/**
* Provides RESTful APIs for managing the container.
*
* @author kawasima
*/
public class ApiServer {
final HttpServer httpServer;
private ExecutorService executor;
public ApiServer(Container container, int port) { | // Path: falchion-container/src/main/java/net/unit8/falchion/api/ListJvmHandler.java
// public class ListJvmHandler extends AbstractApi {
// public ListJvmHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
// getContainer().getPool().getActiveProcesses().forEach(p ->
// arrayBuilder.add(Json.createObjectBuilder()
// .add("id", p.getId())
// .add("pid", p.getPid())));
//
// sendJson(exchange, arrayBuilder.build());
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/api/ReadyJvmHandler.java
// public class ReadyJvmHandler extends AbstractApi {
// private static final Pattern RE_ID = Pattern.compile("/([a-zA-Z0-9]+)/ready$");
//
// public ReadyJvmHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// Matcher m = RE_ID.matcher(exchange.getRequestURI().getPath());
// try {
// if (m.find()) {
// String id = m.group(1);
// JvmProcess process = getContainer()
// .getPool()
// .getProcessByPid(Long.parseLong(id));
// process.ready();
//
// sendNoContent(exchange);
// } else {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// } catch (Exception ex) {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/api/RefreshContainerHandler.java
// public class RefreshContainerHandler extends AbstractApi {
// private static final Logger LOG = LoggerFactory.getLogger(RefreshContainerHandler.class);
// private static final Pattern RE_ID = Pattern.compile("/refresh/([a-zA-Z0-9.-]+)$");
//
// public RefreshContainerHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// Matcher m = RE_ID.matcher(exchange.getRequestURI().getPath());
// Container container = getContainer();
// JvmPool pool = container.getPool();
// if (m.find()) {
// String version = m.group(1);
// String classpath = container.createClasspath(container.getBasedir(), version);
// if (Objects.equals(classpath, container.getBasedir())) {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// return;
// }
// pool.setClasspath(classpath);
// LOG.info("The version of the application has been changed. New version is '{}'", version);
// }
// pool.refresh();
// sendNoContent(exchange);
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/api/ShowJvmHandler.java
// public class ShowJvmHandler extends AbstractApi {
// private static final Logger LOG = LoggerFactory.getLogger(ShowJvmHandler.class);
// private static final Pattern RE_ID = Pattern.compile("/([a-zA-Z0-9]+)$");
//
// public ShowJvmHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// Matcher m = RE_ID.matcher(exchange.getRequestURI().getPath());
//
// try {
// if (m.find()) {
// String id = m.group(1);
// JsonObjectBuilder jvmStatus = Json.createObjectBuilder();
// JsonArrayBuilder monitorStats = Json.createArrayBuilder();
// JvmProcess process = getContainer()
// .getPool()
// .getProcess(id);
//
// process.getMonitorStats()
// .stream()
// .filter(Objects::nonNull)
// .map(MonitorStat::toJson)
// .forEach(monitorStats::add);
//
// jvmStatus.add("id", process.getId());
// jvmStatus.add("pid", process.getPid());
// jvmStatus.add("uptime", process.getUptime());
// jvmStatus.add("options", process.getJvmOptions().stream()
// .collect(Collectors.joining(" ")));
// jvmStatus.add("stats", monitorStats.build());
// sendJson(exchange, jvmStatus.build());
// } else {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// } catch (Exception ex) {
// LOG.error("", ex);
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// }
// }
// Path: falchion-container/src/main/java/net/unit8/falchion/ApiServer.java
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import me.geso.routes.RoutingResult;
import me.geso.routes.WebRouter;
import net.unit8.falchion.api.ListJvmHandler;
import net.unit8.falchion.api.ReadyJvmHandler;
import net.unit8.falchion.api.RefreshContainerHandler;
import net.unit8.falchion.api.ShowJvmHandler;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.InetSocketAddress;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
package net.unit8.falchion;
/**
* Provides RESTful APIs for managing the container.
*
* @author kawasima
*/
public class ApiServer {
final HttpServer httpServer;
private ExecutorService executor;
public ApiServer(Container container, int port) { | ListJvmHandler listJvmHandler = new ListJvmHandler(container); |
kawasima/falchion | falchion-container/src/main/java/net/unit8/falchion/ApiServer.java | // Path: falchion-container/src/main/java/net/unit8/falchion/api/ListJvmHandler.java
// public class ListJvmHandler extends AbstractApi {
// public ListJvmHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
// getContainer().getPool().getActiveProcesses().forEach(p ->
// arrayBuilder.add(Json.createObjectBuilder()
// .add("id", p.getId())
// .add("pid", p.getPid())));
//
// sendJson(exchange, arrayBuilder.build());
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/api/ReadyJvmHandler.java
// public class ReadyJvmHandler extends AbstractApi {
// private static final Pattern RE_ID = Pattern.compile("/([a-zA-Z0-9]+)/ready$");
//
// public ReadyJvmHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// Matcher m = RE_ID.matcher(exchange.getRequestURI().getPath());
// try {
// if (m.find()) {
// String id = m.group(1);
// JvmProcess process = getContainer()
// .getPool()
// .getProcessByPid(Long.parseLong(id));
// process.ready();
//
// sendNoContent(exchange);
// } else {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// } catch (Exception ex) {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/api/RefreshContainerHandler.java
// public class RefreshContainerHandler extends AbstractApi {
// private static final Logger LOG = LoggerFactory.getLogger(RefreshContainerHandler.class);
// private static final Pattern RE_ID = Pattern.compile("/refresh/([a-zA-Z0-9.-]+)$");
//
// public RefreshContainerHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// Matcher m = RE_ID.matcher(exchange.getRequestURI().getPath());
// Container container = getContainer();
// JvmPool pool = container.getPool();
// if (m.find()) {
// String version = m.group(1);
// String classpath = container.createClasspath(container.getBasedir(), version);
// if (Objects.equals(classpath, container.getBasedir())) {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// return;
// }
// pool.setClasspath(classpath);
// LOG.info("The version of the application has been changed. New version is '{}'", version);
// }
// pool.refresh();
// sendNoContent(exchange);
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/api/ShowJvmHandler.java
// public class ShowJvmHandler extends AbstractApi {
// private static final Logger LOG = LoggerFactory.getLogger(ShowJvmHandler.class);
// private static final Pattern RE_ID = Pattern.compile("/([a-zA-Z0-9]+)$");
//
// public ShowJvmHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// Matcher m = RE_ID.matcher(exchange.getRequestURI().getPath());
//
// try {
// if (m.find()) {
// String id = m.group(1);
// JsonObjectBuilder jvmStatus = Json.createObjectBuilder();
// JsonArrayBuilder monitorStats = Json.createArrayBuilder();
// JvmProcess process = getContainer()
// .getPool()
// .getProcess(id);
//
// process.getMonitorStats()
// .stream()
// .filter(Objects::nonNull)
// .map(MonitorStat::toJson)
// .forEach(monitorStats::add);
//
// jvmStatus.add("id", process.getId());
// jvmStatus.add("pid", process.getPid());
// jvmStatus.add("uptime", process.getUptime());
// jvmStatus.add("options", process.getJvmOptions().stream()
// .collect(Collectors.joining(" ")));
// jvmStatus.add("stats", monitorStats.build());
// sendJson(exchange, jvmStatus.build());
// } else {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// } catch (Exception ex) {
// LOG.error("", ex);
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// }
// }
| import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import me.geso.routes.RoutingResult;
import me.geso.routes.WebRouter;
import net.unit8.falchion.api.ListJvmHandler;
import net.unit8.falchion.api.ReadyJvmHandler;
import net.unit8.falchion.api.RefreshContainerHandler;
import net.unit8.falchion.api.ShowJvmHandler;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.InetSocketAddress;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; | package net.unit8.falchion;
/**
* Provides RESTful APIs for managing the container.
*
* @author kawasima
*/
public class ApiServer {
final HttpServer httpServer;
private ExecutorService executor;
public ApiServer(Container container, int port) {
ListJvmHandler listJvmHandler = new ListJvmHandler(container); | // Path: falchion-container/src/main/java/net/unit8/falchion/api/ListJvmHandler.java
// public class ListJvmHandler extends AbstractApi {
// public ListJvmHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
// getContainer().getPool().getActiveProcesses().forEach(p ->
// arrayBuilder.add(Json.createObjectBuilder()
// .add("id", p.getId())
// .add("pid", p.getPid())));
//
// sendJson(exchange, arrayBuilder.build());
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/api/ReadyJvmHandler.java
// public class ReadyJvmHandler extends AbstractApi {
// private static final Pattern RE_ID = Pattern.compile("/([a-zA-Z0-9]+)/ready$");
//
// public ReadyJvmHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// Matcher m = RE_ID.matcher(exchange.getRequestURI().getPath());
// try {
// if (m.find()) {
// String id = m.group(1);
// JvmProcess process = getContainer()
// .getPool()
// .getProcessByPid(Long.parseLong(id));
// process.ready();
//
// sendNoContent(exchange);
// } else {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// } catch (Exception ex) {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/api/RefreshContainerHandler.java
// public class RefreshContainerHandler extends AbstractApi {
// private static final Logger LOG = LoggerFactory.getLogger(RefreshContainerHandler.class);
// private static final Pattern RE_ID = Pattern.compile("/refresh/([a-zA-Z0-9.-]+)$");
//
// public RefreshContainerHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// Matcher m = RE_ID.matcher(exchange.getRequestURI().getPath());
// Container container = getContainer();
// JvmPool pool = container.getPool();
// if (m.find()) {
// String version = m.group(1);
// String classpath = container.createClasspath(container.getBasedir(), version);
// if (Objects.equals(classpath, container.getBasedir())) {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// return;
// }
// pool.setClasspath(classpath);
// LOG.info("The version of the application has been changed. New version is '{}'", version);
// }
// pool.refresh();
// sendNoContent(exchange);
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/api/ShowJvmHandler.java
// public class ShowJvmHandler extends AbstractApi {
// private static final Logger LOG = LoggerFactory.getLogger(ShowJvmHandler.class);
// private static final Pattern RE_ID = Pattern.compile("/([a-zA-Z0-9]+)$");
//
// public ShowJvmHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// Matcher m = RE_ID.matcher(exchange.getRequestURI().getPath());
//
// try {
// if (m.find()) {
// String id = m.group(1);
// JsonObjectBuilder jvmStatus = Json.createObjectBuilder();
// JsonArrayBuilder monitorStats = Json.createArrayBuilder();
// JvmProcess process = getContainer()
// .getPool()
// .getProcess(id);
//
// process.getMonitorStats()
// .stream()
// .filter(Objects::nonNull)
// .map(MonitorStat::toJson)
// .forEach(monitorStats::add);
//
// jvmStatus.add("id", process.getId());
// jvmStatus.add("pid", process.getPid());
// jvmStatus.add("uptime", process.getUptime());
// jvmStatus.add("options", process.getJvmOptions().stream()
// .collect(Collectors.joining(" ")));
// jvmStatus.add("stats", monitorStats.build());
// sendJson(exchange, jvmStatus.build());
// } else {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// } catch (Exception ex) {
// LOG.error("", ex);
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// }
// }
// Path: falchion-container/src/main/java/net/unit8/falchion/ApiServer.java
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import me.geso.routes.RoutingResult;
import me.geso.routes.WebRouter;
import net.unit8.falchion.api.ListJvmHandler;
import net.unit8.falchion.api.ReadyJvmHandler;
import net.unit8.falchion.api.RefreshContainerHandler;
import net.unit8.falchion.api.ShowJvmHandler;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.InetSocketAddress;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
package net.unit8.falchion;
/**
* Provides RESTful APIs for managing the container.
*
* @author kawasima
*/
public class ApiServer {
final HttpServer httpServer;
private ExecutorService executor;
public ApiServer(Container container, int port) {
ListJvmHandler listJvmHandler = new ListJvmHandler(container); | RefreshContainerHandler refreshContainerHandler = new RefreshContainerHandler(container); |
kawasima/falchion | falchion-container/src/main/java/net/unit8/falchion/ApiServer.java | // Path: falchion-container/src/main/java/net/unit8/falchion/api/ListJvmHandler.java
// public class ListJvmHandler extends AbstractApi {
// public ListJvmHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
// getContainer().getPool().getActiveProcesses().forEach(p ->
// arrayBuilder.add(Json.createObjectBuilder()
// .add("id", p.getId())
// .add("pid", p.getPid())));
//
// sendJson(exchange, arrayBuilder.build());
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/api/ReadyJvmHandler.java
// public class ReadyJvmHandler extends AbstractApi {
// private static final Pattern RE_ID = Pattern.compile("/([a-zA-Z0-9]+)/ready$");
//
// public ReadyJvmHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// Matcher m = RE_ID.matcher(exchange.getRequestURI().getPath());
// try {
// if (m.find()) {
// String id = m.group(1);
// JvmProcess process = getContainer()
// .getPool()
// .getProcessByPid(Long.parseLong(id));
// process.ready();
//
// sendNoContent(exchange);
// } else {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// } catch (Exception ex) {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/api/RefreshContainerHandler.java
// public class RefreshContainerHandler extends AbstractApi {
// private static final Logger LOG = LoggerFactory.getLogger(RefreshContainerHandler.class);
// private static final Pattern RE_ID = Pattern.compile("/refresh/([a-zA-Z0-9.-]+)$");
//
// public RefreshContainerHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// Matcher m = RE_ID.matcher(exchange.getRequestURI().getPath());
// Container container = getContainer();
// JvmPool pool = container.getPool();
// if (m.find()) {
// String version = m.group(1);
// String classpath = container.createClasspath(container.getBasedir(), version);
// if (Objects.equals(classpath, container.getBasedir())) {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// return;
// }
// pool.setClasspath(classpath);
// LOG.info("The version of the application has been changed. New version is '{}'", version);
// }
// pool.refresh();
// sendNoContent(exchange);
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/api/ShowJvmHandler.java
// public class ShowJvmHandler extends AbstractApi {
// private static final Logger LOG = LoggerFactory.getLogger(ShowJvmHandler.class);
// private static final Pattern RE_ID = Pattern.compile("/([a-zA-Z0-9]+)$");
//
// public ShowJvmHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// Matcher m = RE_ID.matcher(exchange.getRequestURI().getPath());
//
// try {
// if (m.find()) {
// String id = m.group(1);
// JsonObjectBuilder jvmStatus = Json.createObjectBuilder();
// JsonArrayBuilder monitorStats = Json.createArrayBuilder();
// JvmProcess process = getContainer()
// .getPool()
// .getProcess(id);
//
// process.getMonitorStats()
// .stream()
// .filter(Objects::nonNull)
// .map(MonitorStat::toJson)
// .forEach(monitorStats::add);
//
// jvmStatus.add("id", process.getId());
// jvmStatus.add("pid", process.getPid());
// jvmStatus.add("uptime", process.getUptime());
// jvmStatus.add("options", process.getJvmOptions().stream()
// .collect(Collectors.joining(" ")));
// jvmStatus.add("stats", monitorStats.build());
// sendJson(exchange, jvmStatus.build());
// } else {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// } catch (Exception ex) {
// LOG.error("", ex);
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// }
// }
| import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import me.geso.routes.RoutingResult;
import me.geso.routes.WebRouter;
import net.unit8.falchion.api.ListJvmHandler;
import net.unit8.falchion.api.ReadyJvmHandler;
import net.unit8.falchion.api.RefreshContainerHandler;
import net.unit8.falchion.api.ShowJvmHandler;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.InetSocketAddress;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; | package net.unit8.falchion;
/**
* Provides RESTful APIs for managing the container.
*
* @author kawasima
*/
public class ApiServer {
final HttpServer httpServer;
private ExecutorService executor;
public ApiServer(Container container, int port) {
ListJvmHandler listJvmHandler = new ListJvmHandler(container);
RefreshContainerHandler refreshContainerHandler = new RefreshContainerHandler(container); | // Path: falchion-container/src/main/java/net/unit8/falchion/api/ListJvmHandler.java
// public class ListJvmHandler extends AbstractApi {
// public ListJvmHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
// getContainer().getPool().getActiveProcesses().forEach(p ->
// arrayBuilder.add(Json.createObjectBuilder()
// .add("id", p.getId())
// .add("pid", p.getPid())));
//
// sendJson(exchange, arrayBuilder.build());
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/api/ReadyJvmHandler.java
// public class ReadyJvmHandler extends AbstractApi {
// private static final Pattern RE_ID = Pattern.compile("/([a-zA-Z0-9]+)/ready$");
//
// public ReadyJvmHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// Matcher m = RE_ID.matcher(exchange.getRequestURI().getPath());
// try {
// if (m.find()) {
// String id = m.group(1);
// JvmProcess process = getContainer()
// .getPool()
// .getProcessByPid(Long.parseLong(id));
// process.ready();
//
// sendNoContent(exchange);
// } else {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// } catch (Exception ex) {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/api/RefreshContainerHandler.java
// public class RefreshContainerHandler extends AbstractApi {
// private static final Logger LOG = LoggerFactory.getLogger(RefreshContainerHandler.class);
// private static final Pattern RE_ID = Pattern.compile("/refresh/([a-zA-Z0-9.-]+)$");
//
// public RefreshContainerHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// Matcher m = RE_ID.matcher(exchange.getRequestURI().getPath());
// Container container = getContainer();
// JvmPool pool = container.getPool();
// if (m.find()) {
// String version = m.group(1);
// String classpath = container.createClasspath(container.getBasedir(), version);
// if (Objects.equals(classpath, container.getBasedir())) {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// return;
// }
// pool.setClasspath(classpath);
// LOG.info("The version of the application has been changed. New version is '{}'", version);
// }
// pool.refresh();
// sendNoContent(exchange);
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/api/ShowJvmHandler.java
// public class ShowJvmHandler extends AbstractApi {
// private static final Logger LOG = LoggerFactory.getLogger(ShowJvmHandler.class);
// private static final Pattern RE_ID = Pattern.compile("/([a-zA-Z0-9]+)$");
//
// public ShowJvmHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// Matcher m = RE_ID.matcher(exchange.getRequestURI().getPath());
//
// try {
// if (m.find()) {
// String id = m.group(1);
// JsonObjectBuilder jvmStatus = Json.createObjectBuilder();
// JsonArrayBuilder monitorStats = Json.createArrayBuilder();
// JvmProcess process = getContainer()
// .getPool()
// .getProcess(id);
//
// process.getMonitorStats()
// .stream()
// .filter(Objects::nonNull)
// .map(MonitorStat::toJson)
// .forEach(monitorStats::add);
//
// jvmStatus.add("id", process.getId());
// jvmStatus.add("pid", process.getPid());
// jvmStatus.add("uptime", process.getUptime());
// jvmStatus.add("options", process.getJvmOptions().stream()
// .collect(Collectors.joining(" ")));
// jvmStatus.add("stats", monitorStats.build());
// sendJson(exchange, jvmStatus.build());
// } else {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// } catch (Exception ex) {
// LOG.error("", ex);
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// }
// }
// Path: falchion-container/src/main/java/net/unit8/falchion/ApiServer.java
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import me.geso.routes.RoutingResult;
import me.geso.routes.WebRouter;
import net.unit8.falchion.api.ListJvmHandler;
import net.unit8.falchion.api.ReadyJvmHandler;
import net.unit8.falchion.api.RefreshContainerHandler;
import net.unit8.falchion.api.ShowJvmHandler;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.InetSocketAddress;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
package net.unit8.falchion;
/**
* Provides RESTful APIs for managing the container.
*
* @author kawasima
*/
public class ApiServer {
final HttpServer httpServer;
private ExecutorService executor;
public ApiServer(Container container, int port) {
ListJvmHandler listJvmHandler = new ListJvmHandler(container);
RefreshContainerHandler refreshContainerHandler = new RefreshContainerHandler(container); | ReadyJvmHandler readyJvmHandler = new ReadyJvmHandler(container); |
kawasima/falchion | falchion-container/src/main/java/net/unit8/falchion/ApiServer.java | // Path: falchion-container/src/main/java/net/unit8/falchion/api/ListJvmHandler.java
// public class ListJvmHandler extends AbstractApi {
// public ListJvmHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
// getContainer().getPool().getActiveProcesses().forEach(p ->
// arrayBuilder.add(Json.createObjectBuilder()
// .add("id", p.getId())
// .add("pid", p.getPid())));
//
// sendJson(exchange, arrayBuilder.build());
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/api/ReadyJvmHandler.java
// public class ReadyJvmHandler extends AbstractApi {
// private static final Pattern RE_ID = Pattern.compile("/([a-zA-Z0-9]+)/ready$");
//
// public ReadyJvmHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// Matcher m = RE_ID.matcher(exchange.getRequestURI().getPath());
// try {
// if (m.find()) {
// String id = m.group(1);
// JvmProcess process = getContainer()
// .getPool()
// .getProcessByPid(Long.parseLong(id));
// process.ready();
//
// sendNoContent(exchange);
// } else {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// } catch (Exception ex) {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/api/RefreshContainerHandler.java
// public class RefreshContainerHandler extends AbstractApi {
// private static final Logger LOG = LoggerFactory.getLogger(RefreshContainerHandler.class);
// private static final Pattern RE_ID = Pattern.compile("/refresh/([a-zA-Z0-9.-]+)$");
//
// public RefreshContainerHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// Matcher m = RE_ID.matcher(exchange.getRequestURI().getPath());
// Container container = getContainer();
// JvmPool pool = container.getPool();
// if (m.find()) {
// String version = m.group(1);
// String classpath = container.createClasspath(container.getBasedir(), version);
// if (Objects.equals(classpath, container.getBasedir())) {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// return;
// }
// pool.setClasspath(classpath);
// LOG.info("The version of the application has been changed. New version is '{}'", version);
// }
// pool.refresh();
// sendNoContent(exchange);
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/api/ShowJvmHandler.java
// public class ShowJvmHandler extends AbstractApi {
// private static final Logger LOG = LoggerFactory.getLogger(ShowJvmHandler.class);
// private static final Pattern RE_ID = Pattern.compile("/([a-zA-Z0-9]+)$");
//
// public ShowJvmHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// Matcher m = RE_ID.matcher(exchange.getRequestURI().getPath());
//
// try {
// if (m.find()) {
// String id = m.group(1);
// JsonObjectBuilder jvmStatus = Json.createObjectBuilder();
// JsonArrayBuilder monitorStats = Json.createArrayBuilder();
// JvmProcess process = getContainer()
// .getPool()
// .getProcess(id);
//
// process.getMonitorStats()
// .stream()
// .filter(Objects::nonNull)
// .map(MonitorStat::toJson)
// .forEach(monitorStats::add);
//
// jvmStatus.add("id", process.getId());
// jvmStatus.add("pid", process.getPid());
// jvmStatus.add("uptime", process.getUptime());
// jvmStatus.add("options", process.getJvmOptions().stream()
// .collect(Collectors.joining(" ")));
// jvmStatus.add("stats", monitorStats.build());
// sendJson(exchange, jvmStatus.build());
// } else {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// } catch (Exception ex) {
// LOG.error("", ex);
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// }
// }
| import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import me.geso.routes.RoutingResult;
import me.geso.routes.WebRouter;
import net.unit8.falchion.api.ListJvmHandler;
import net.unit8.falchion.api.ReadyJvmHandler;
import net.unit8.falchion.api.RefreshContainerHandler;
import net.unit8.falchion.api.ShowJvmHandler;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.InetSocketAddress;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; | package net.unit8.falchion;
/**
* Provides RESTful APIs for managing the container.
*
* @author kawasima
*/
public class ApiServer {
final HttpServer httpServer;
private ExecutorService executor;
public ApiServer(Container container, int port) {
ListJvmHandler listJvmHandler = new ListJvmHandler(container);
RefreshContainerHandler refreshContainerHandler = new RefreshContainerHandler(container);
ReadyJvmHandler readyJvmHandler = new ReadyJvmHandler(container); | // Path: falchion-container/src/main/java/net/unit8/falchion/api/ListJvmHandler.java
// public class ListJvmHandler extends AbstractApi {
// public ListJvmHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
// getContainer().getPool().getActiveProcesses().forEach(p ->
// arrayBuilder.add(Json.createObjectBuilder()
// .add("id", p.getId())
// .add("pid", p.getPid())));
//
// sendJson(exchange, arrayBuilder.build());
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/api/ReadyJvmHandler.java
// public class ReadyJvmHandler extends AbstractApi {
// private static final Pattern RE_ID = Pattern.compile("/([a-zA-Z0-9]+)/ready$");
//
// public ReadyJvmHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// Matcher m = RE_ID.matcher(exchange.getRequestURI().getPath());
// try {
// if (m.find()) {
// String id = m.group(1);
// JvmProcess process = getContainer()
// .getPool()
// .getProcessByPid(Long.parseLong(id));
// process.ready();
//
// sendNoContent(exchange);
// } else {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// } catch (Exception ex) {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/api/RefreshContainerHandler.java
// public class RefreshContainerHandler extends AbstractApi {
// private static final Logger LOG = LoggerFactory.getLogger(RefreshContainerHandler.class);
// private static final Pattern RE_ID = Pattern.compile("/refresh/([a-zA-Z0-9.-]+)$");
//
// public RefreshContainerHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// Matcher m = RE_ID.matcher(exchange.getRequestURI().getPath());
// Container container = getContainer();
// JvmPool pool = container.getPool();
// if (m.find()) {
// String version = m.group(1);
// String classpath = container.createClasspath(container.getBasedir(), version);
// if (Objects.equals(classpath, container.getBasedir())) {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// return;
// }
// pool.setClasspath(classpath);
// LOG.info("The version of the application has been changed. New version is '{}'", version);
// }
// pool.refresh();
// sendNoContent(exchange);
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/api/ShowJvmHandler.java
// public class ShowJvmHandler extends AbstractApi {
// private static final Logger LOG = LoggerFactory.getLogger(ShowJvmHandler.class);
// private static final Pattern RE_ID = Pattern.compile("/([a-zA-Z0-9]+)$");
//
// public ShowJvmHandler(Container container) {
// super(container);
// }
//
// @Override
// public void handle(HttpExchange exchange) throws IOException {
// Matcher m = RE_ID.matcher(exchange.getRequestURI().getPath());
//
// try {
// if (m.find()) {
// String id = m.group(1);
// JsonObjectBuilder jvmStatus = Json.createObjectBuilder();
// JsonArrayBuilder monitorStats = Json.createArrayBuilder();
// JvmProcess process = getContainer()
// .getPool()
// .getProcess(id);
//
// process.getMonitorStats()
// .stream()
// .filter(Objects::nonNull)
// .map(MonitorStat::toJson)
// .forEach(monitorStats::add);
//
// jvmStatus.add("id", process.getId());
// jvmStatus.add("pid", process.getPid());
// jvmStatus.add("uptime", process.getUptime());
// jvmStatus.add("options", process.getJvmOptions().stream()
// .collect(Collectors.joining(" ")));
// jvmStatus.add("stats", monitorStats.build());
// sendJson(exchange, jvmStatus.build());
// } else {
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// } catch (Exception ex) {
// LOG.error("", ex);
// sendBadRequest(exchange, exchange.getRequestURI().getPath());
// }
// }
// }
// Path: falchion-container/src/main/java/net/unit8/falchion/ApiServer.java
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import me.geso.routes.RoutingResult;
import me.geso.routes.WebRouter;
import net.unit8.falchion.api.ListJvmHandler;
import net.unit8.falchion.api.ReadyJvmHandler;
import net.unit8.falchion.api.RefreshContainerHandler;
import net.unit8.falchion.api.ShowJvmHandler;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.InetSocketAddress;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
package net.unit8.falchion;
/**
* Provides RESTful APIs for managing the container.
*
* @author kawasima
*/
public class ApiServer {
final HttpServer httpServer;
private ExecutorService executor;
public ApiServer(Container container, int port) {
ListJvmHandler listJvmHandler = new ListJvmHandler(container);
RefreshContainerHandler refreshContainerHandler = new RefreshContainerHandler(container);
ReadyJvmHandler readyJvmHandler = new ReadyJvmHandler(container); | ShowJvmHandler showJvmHandler = new ShowJvmHandler(container); |
kawasima/falchion | falchion-container/src/main/java/net/unit8/falchion/JvmProcess.java | // Path: falchion-container/src/main/java/net/unit8/falchion/monitor/JvmMonitor.java
// public interface JvmMonitor {
// void start(JvmProcess process);
// MonitorStat getStat();
// void stop();
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/monitor/MonitorStat.java
// public interface MonitorStat {
// JsonObject toJson();
// }
| import net.unit8.falchion.monitor.JvmMonitor;
import net.unit8.falchion.monitor.MonitorStat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors; | package net.unit8.falchion;
/**
* @author kawasima
*/
public class JvmProcess implements Callable<JvmResult> {
private static final Logger LOG = LoggerFactory.getLogger(JvmProcess.class);
private static final DateTimeFormatter fmtIO = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
private final String id;
private long pid = -1;
private final String mainClass;
private String classpath;
private List<String> jvmOptions;
private final ProcessBuilder processBuilder;
private transient Process process;
private long startedAt;
private final CompletableFuture<Void> ready;
| // Path: falchion-container/src/main/java/net/unit8/falchion/monitor/JvmMonitor.java
// public interface JvmMonitor {
// void start(JvmProcess process);
// MonitorStat getStat();
// void stop();
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/monitor/MonitorStat.java
// public interface MonitorStat {
// JsonObject toJson();
// }
// Path: falchion-container/src/main/java/net/unit8/falchion/JvmProcess.java
import net.unit8.falchion.monitor.JvmMonitor;
import net.unit8.falchion.monitor.MonitorStat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
package net.unit8.falchion;
/**
* @author kawasima
*/
public class JvmProcess implements Callable<JvmResult> {
private static final Logger LOG = LoggerFactory.getLogger(JvmProcess.class);
private static final DateTimeFormatter fmtIO = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
private final String id;
private long pid = -1;
private final String mainClass;
private String classpath;
private List<String> jvmOptions;
private final ProcessBuilder processBuilder;
private transient Process process;
private long startedAt;
private final CompletableFuture<Void> ready;
| private final Set<JvmMonitor> monitors; |
kawasima/falchion | falchion-container/src/main/java/net/unit8/falchion/JvmProcess.java | // Path: falchion-container/src/main/java/net/unit8/falchion/monitor/JvmMonitor.java
// public interface JvmMonitor {
// void start(JvmProcess process);
// MonitorStat getStat();
// void stop();
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/monitor/MonitorStat.java
// public interface MonitorStat {
// JsonObject toJson();
// }
| import net.unit8.falchion.monitor.JvmMonitor;
import net.unit8.falchion.monitor.MonitorStat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors; |
public String getMainClass() {
return mainClass;
}
public void addMonitor(JvmMonitor... monitors) {
this.monitors.addAll(Arrays.asList(monitors));
}
public void kill() throws IOException {
try {
Process killProcess = new ProcessBuilder("kill", "-TERM", Long.toString(pid)).start();
int killResult = killProcess.waitFor();
if (killResult != 0)
throw new IOException("kill " + pid + " is failure");
} catch (InterruptedException ex) {
LOG.warn("Kill the process (pid={}) is canceled.", pid);
}
}
public void setIoDir(File directory) {
if (process != null) {
throw new IllegalStateException("You should call setIoDir before starting process");
}
String prefix = fmtIO.format(LocalDateTime.now()) + "." + id;
processBuilder
.redirectError(new File(directory, prefix + ".err"))
.redirectOutput(new File(directory, prefix + ".out"));
}
| // Path: falchion-container/src/main/java/net/unit8/falchion/monitor/JvmMonitor.java
// public interface JvmMonitor {
// void start(JvmProcess process);
// MonitorStat getStat();
// void stop();
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/monitor/MonitorStat.java
// public interface MonitorStat {
// JsonObject toJson();
// }
// Path: falchion-container/src/main/java/net/unit8/falchion/JvmProcess.java
import net.unit8.falchion.monitor.JvmMonitor;
import net.unit8.falchion.monitor.MonitorStat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
public String getMainClass() {
return mainClass;
}
public void addMonitor(JvmMonitor... monitors) {
this.monitors.addAll(Arrays.asList(monitors));
}
public void kill() throws IOException {
try {
Process killProcess = new ProcessBuilder("kill", "-TERM", Long.toString(pid)).start();
int killResult = killProcess.waitFor();
if (killResult != 0)
throw new IOException("kill " + pid + " is failure");
} catch (InterruptedException ex) {
LOG.warn("Kill the process (pid={}) is canceled.", pid);
}
}
public void setIoDir(File directory) {
if (process != null) {
throw new IllegalStateException("You should call setIoDir before starting process");
}
String prefix = fmtIO.format(LocalDateTime.now()) + "." + id;
processBuilder
.redirectError(new File(directory, prefix + ".err"))
.redirectOutput(new File(directory, prefix + ".out"));
}
| public List<MonitorStat> getMonitorStats() { |
kawasima/falchion | falchion-example-jetty9/src/main/java/net/unit8/falchion/example/jetty9/Main.java | // Path: falchion-jetty9-connector/src/main/java/net/unit8/falchion/jetty9/ReusePortConnector.java
// public class ReusePortConnector extends ServerConnector {
// public ReusePortConnector(@Name("server") Server server) {
// super(server);
// }
//
// public ReusePortConnector(@Name("server") Server server, @Name("factories") ConnectionFactory... factories) {
// super(server, factories);
// }
//
// @Override
// public void open() throws IOException {
// ServerSocketChannel serverChannel = ServerSocketChannel.open();
// serverChannel.setOption(StandardSocketOptions.SO_REUSEPORT, true);
//
// InetSocketAddress bindAddress = getHost() == null ? new InetSocketAddress(getPort()) : new InetSocketAddress(getHost(), getPort());
// serverChannel.socket().setReuseAddress(getReuseAddress());
// serverChannel.socket().bind(bindAddress, getAcceptQueueSize());
// serverChannel.configureBlocking(true);
// addBean(serverChannel);
// try {
// Field acceptChannel = ServerConnector.class.getDeclaredField("_acceptChannel");
// acceptChannel.setAccessible(true);
// acceptChannel.set(this, serverChannel);
// } catch (Exception ex) {
// throw new IOException(ex);
// }
// }
// }
| import com.codahale.metrics.jmx.JmxReporter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.jetty9.InstrumentedHandler;
import net.unit8.falchion.jetty9.ReusePortConnector;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.HandlerWrapper;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.management.ManagementFactory;
import java.util.Random;
import java.util.UUID; | package net.unit8.falchion.example.jetty9;
/**
* @author kawasima
*/
public class Main {
public static void main(String[] args) throws Exception {
MetricRegistry metrics = new MetricRegistry();
String serverId = UUID.randomUUID().toString();
Server server = new Server(); | // Path: falchion-jetty9-connector/src/main/java/net/unit8/falchion/jetty9/ReusePortConnector.java
// public class ReusePortConnector extends ServerConnector {
// public ReusePortConnector(@Name("server") Server server) {
// super(server);
// }
//
// public ReusePortConnector(@Name("server") Server server, @Name("factories") ConnectionFactory... factories) {
// super(server, factories);
// }
//
// @Override
// public void open() throws IOException {
// ServerSocketChannel serverChannel = ServerSocketChannel.open();
// serverChannel.setOption(StandardSocketOptions.SO_REUSEPORT, true);
//
// InetSocketAddress bindAddress = getHost() == null ? new InetSocketAddress(getPort()) : new InetSocketAddress(getHost(), getPort());
// serverChannel.socket().setReuseAddress(getReuseAddress());
// serverChannel.socket().bind(bindAddress, getAcceptQueueSize());
// serverChannel.configureBlocking(true);
// addBean(serverChannel);
// try {
// Field acceptChannel = ServerConnector.class.getDeclaredField("_acceptChannel");
// acceptChannel.setAccessible(true);
// acceptChannel.set(this, serverChannel);
// } catch (Exception ex) {
// throw new IOException(ex);
// }
// }
// }
// Path: falchion-example-jetty9/src/main/java/net/unit8/falchion/example/jetty9/Main.java
import com.codahale.metrics.jmx.JmxReporter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.jetty9.InstrumentedHandler;
import net.unit8.falchion.jetty9.ReusePortConnector;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.HandlerWrapper;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.management.ManagementFactory;
import java.util.Random;
import java.util.UUID;
package net.unit8.falchion.example.jetty9;
/**
* @author kawasima
*/
public class Main {
public static void main(String[] args) throws Exception {
MetricRegistry metrics = new MetricRegistry();
String serverId = UUID.randomUUID().toString();
Server server = new Server(); | ReusePortConnector connector = new ReusePortConnector(server); |
kawasima/falchion | falchion-example-enkan/src/main/java/net/unit8/falchion/example/ExampleSystemFactory.java | // Path: falchion-jetty9-connector/src/main/java/net/unit8/falchion/jetty9/ReusePortConnector.java
// public class ReusePortConnector extends ServerConnector {
// public ReusePortConnector(@Name("server") Server server) {
// super(server);
// }
//
// public ReusePortConnector(@Name("server") Server server, @Name("factories") ConnectionFactory... factories) {
// super(server, factories);
// }
//
// @Override
// public void open() throws IOException {
// ServerSocketChannel serverChannel = ServerSocketChannel.open();
// serverChannel.setOption(StandardSocketOptions.SO_REUSEPORT, true);
//
// InetSocketAddress bindAddress = getHost() == null ? new InetSocketAddress(getPort()) : new InetSocketAddress(getHost(), getPort());
// serverChannel.socket().setReuseAddress(getReuseAddress());
// serverChannel.socket().bind(bindAddress, getAcceptQueueSize());
// serverChannel.configureBlocking(true);
// addBean(serverChannel);
// try {
// Field acceptChannel = ServerConnector.class.getDeclaredField("_acceptChannel");
// acceptChannel.setAccessible(true);
// acceptChannel.set(this, serverChannel);
// } catch (Exception ex) {
// throw new IOException(ex);
// }
// }
// }
| import enkan.Env;
import enkan.component.ApplicationComponent;
import enkan.component.falchion.FalchionStartNotifier;
import enkan.component.freemarker.FreemarkerTemplateEngine;
import enkan.component.jetty.JettyComponent;
import enkan.component.metrics.MetricsComponent;
import enkan.config.EnkanSystemFactory;
import enkan.system.EnkanSystem;
import net.unit8.falchion.jetty9.ReusePortConnector;
import org.eclipse.jetty.server.ServerConnector;
import java.util.Objects;
import static enkan.component.ComponentRelationship.component;
import static enkan.util.BeanBuilder.builder; | package net.unit8.falchion.example;
public class ExampleSystemFactory implements EnkanSystemFactory {
@Override
public EnkanSystem create() {
EnkanSystem system = EnkanSystem.of(
"http", builder(new JettyComponent())
.set(JettyComponent::setServerConnectorFactory, (server, options) -> { | // Path: falchion-jetty9-connector/src/main/java/net/unit8/falchion/jetty9/ReusePortConnector.java
// public class ReusePortConnector extends ServerConnector {
// public ReusePortConnector(@Name("server") Server server) {
// super(server);
// }
//
// public ReusePortConnector(@Name("server") Server server, @Name("factories") ConnectionFactory... factories) {
// super(server, factories);
// }
//
// @Override
// public void open() throws IOException {
// ServerSocketChannel serverChannel = ServerSocketChannel.open();
// serverChannel.setOption(StandardSocketOptions.SO_REUSEPORT, true);
//
// InetSocketAddress bindAddress = getHost() == null ? new InetSocketAddress(getPort()) : new InetSocketAddress(getHost(), getPort());
// serverChannel.socket().setReuseAddress(getReuseAddress());
// serverChannel.socket().bind(bindAddress, getAcceptQueueSize());
// serverChannel.configureBlocking(true);
// addBean(serverChannel);
// try {
// Field acceptChannel = ServerConnector.class.getDeclaredField("_acceptChannel");
// acceptChannel.setAccessible(true);
// acceptChannel.set(this, serverChannel);
// } catch (Exception ex) {
// throw new IOException(ex);
// }
// }
// }
// Path: falchion-example-enkan/src/main/java/net/unit8/falchion/example/ExampleSystemFactory.java
import enkan.Env;
import enkan.component.ApplicationComponent;
import enkan.component.falchion.FalchionStartNotifier;
import enkan.component.freemarker.FreemarkerTemplateEngine;
import enkan.component.jetty.JettyComponent;
import enkan.component.metrics.MetricsComponent;
import enkan.config.EnkanSystemFactory;
import enkan.system.EnkanSystem;
import net.unit8.falchion.jetty9.ReusePortConnector;
import org.eclipse.jetty.server.ServerConnector;
import java.util.Objects;
import static enkan.component.ComponentRelationship.component;
import static enkan.util.BeanBuilder.builder;
package net.unit8.falchion.example;
public class ExampleSystemFactory implements EnkanSystemFactory {
@Override
public EnkanSystem create() {
EnkanSystem system = EnkanSystem.of(
"http", builder(new JettyComponent())
.set(JettyComponent::setServerConnectorFactory, (server, options) -> { | ServerConnector connector = new ReusePortConnector(server); |
kawasima/falchion | falchion-container/src/main/java/net/unit8/falchion/monitor/JstatMonitor.java | // Path: falchion-container/src/main/java/net/unit8/falchion/JvmProcess.java
// public class JvmProcess implements Callable<JvmResult> {
// private static final Logger LOG = LoggerFactory.getLogger(JvmProcess.class);
//
// private static final DateTimeFormatter fmtIO = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
//
// private final String id;
// private long pid = -1;
// private final String mainClass;
// private String classpath;
// private List<String> jvmOptions;
//
// private final ProcessBuilder processBuilder;
// private transient Process process;
// private long startedAt;
// private final CompletableFuture<Void> ready;
//
// private final Set<JvmMonitor> monitors;
//
// private static final String ID_CHARS = "0123456789abcdefghijklmnopqrstuvwxyz";
//
// private String generateId(int length) {
// return new Random().ints(0, ID_CHARS.length())
// .mapToObj(ID_CHARS::charAt)
// .limit(length)
// .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
// .toString();
// }
//
// public JvmProcess(String mainClass, String classpath) {
// this.id = generateId(5);
// this.mainClass = mainClass;
// this.classpath = classpath;
// this.ready = new CompletableFuture<>();
// this.monitors = new HashSet<>();
//
// processBuilder = new ProcessBuilder().inheritIO();
// }
//
// public CompletableFuture<Void> waitForReady() {
// return ready;
// }
//
// public void ready() {
// ready.complete(null);
// monitors.forEach(m -> m.start(this));
// }
//
// @Override
// public JvmResult call() throws Exception {
// String javaHome = System.getProperty("java.home");
// List<String> commandArgs = new ArrayList<>(Arrays.asList(javaHome + "/bin/java", "-cp", classpath));
// if (jvmOptions != null) {
// commandArgs.addAll(jvmOptions);
// }
// commandArgs.add(mainClass);
// processBuilder.command(commandArgs);
// try {
// process = processBuilder.start();
// startedAt = System.currentTimeMillis();
// pid = process.pid();
// LOG.info("process started: id={}, pid={}", id, pid);
//
// //return new JvmResult(id, pid, process.waitFor());
// return new JvmResult(id, pid, process.onExit()
// .whenComplete((result, ex) -> {
// if (ex == null) {
//
// }
// })
// .get().exitValue());
// } catch (InterruptedException ex) {
// LOG.info("process interrupted: id={}, pid={}", id, pid);
// try {
// process.waitFor(3, TimeUnit.SECONDS);
// } catch (InterruptedException ignore) {
// }
// process.destroy();
// LOG.info("process destroy: id={}, pid={}", id, pid);
// return new JvmResult(id, pid, -1);
// } catch (Exception ex) {
// LOG.error("Process start failure", ex);
// throw ex;
// } finally {
// monitors.forEach(JvmMonitor::stop);
//
// if (process != null) {
// process.getInputStream().close();
// process.getOutputStream().close();
// process.getErrorStream().close();
// }
// }
// }
//
// public String getId() {
// return id;
// }
//
// public long getPid() {
// return pid;
// }
//
// public long getUptime(){
// return System.currentTimeMillis() - startedAt;
// }
//
// public String getMainClass() {
// return mainClass;
// }
//
// public void addMonitor(JvmMonitor... monitors) {
// this.monitors.addAll(Arrays.asList(monitors));
// }
//
// public void kill() throws IOException {
// try {
// Process killProcess = new ProcessBuilder("kill", "-TERM", Long.toString(pid)).start();
// int killResult = killProcess.waitFor();
// if (killResult != 0)
// throw new IOException("kill " + pid + " is failure");
// } catch (InterruptedException ex) {
// LOG.warn("Kill the process (pid={}) is canceled.", pid);
// }
// }
//
// public void setIoDir(File directory) {
// if (process != null) {
// throw new IllegalStateException("You should call setIoDir before starting process");
// }
// String prefix = fmtIO.format(LocalDateTime.now()) + "." + id;
// processBuilder
// .redirectError(new File(directory, prefix + ".err"))
// .redirectOutput(new File(directory, prefix + ".out"));
// }
//
// public List<MonitorStat> getMonitorStats() {
// return monitors.stream()
// .map(JvmMonitor::getStat)
// .collect(Collectors.toList());
// }
//
// public void setJvmOptions(List<String> options) {
// this.jvmOptions = options;
// }
//
// public List<String> getJvmOptions() {
// return jvmOptions;
// }
//
// void setClasspath(String classpath) {
// this.classpath = classpath;
// }
//
// @Override
// public String toString() {
// return "JvmProcess{id=" + id + ", pid=" + pid + "}";
// }
// }
| import net.unit8.falchion.JvmProcess;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UncheckedIOException; | package net.unit8.falchion.monitor;
/**
* @author kawasima
*/
public class JstatMonitor implements GcMonitor {
private static final Logger LOG = LoggerFactory.getLogger(JstatMonitor.class);
private Process process;
private GcStat stat;
private Thread monitorThread;
@Override | // Path: falchion-container/src/main/java/net/unit8/falchion/JvmProcess.java
// public class JvmProcess implements Callable<JvmResult> {
// private static final Logger LOG = LoggerFactory.getLogger(JvmProcess.class);
//
// private static final DateTimeFormatter fmtIO = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
//
// private final String id;
// private long pid = -1;
// private final String mainClass;
// private String classpath;
// private List<String> jvmOptions;
//
// private final ProcessBuilder processBuilder;
// private transient Process process;
// private long startedAt;
// private final CompletableFuture<Void> ready;
//
// private final Set<JvmMonitor> monitors;
//
// private static final String ID_CHARS = "0123456789abcdefghijklmnopqrstuvwxyz";
//
// private String generateId(int length) {
// return new Random().ints(0, ID_CHARS.length())
// .mapToObj(ID_CHARS::charAt)
// .limit(length)
// .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
// .toString();
// }
//
// public JvmProcess(String mainClass, String classpath) {
// this.id = generateId(5);
// this.mainClass = mainClass;
// this.classpath = classpath;
// this.ready = new CompletableFuture<>();
// this.monitors = new HashSet<>();
//
// processBuilder = new ProcessBuilder().inheritIO();
// }
//
// public CompletableFuture<Void> waitForReady() {
// return ready;
// }
//
// public void ready() {
// ready.complete(null);
// monitors.forEach(m -> m.start(this));
// }
//
// @Override
// public JvmResult call() throws Exception {
// String javaHome = System.getProperty("java.home");
// List<String> commandArgs = new ArrayList<>(Arrays.asList(javaHome + "/bin/java", "-cp", classpath));
// if (jvmOptions != null) {
// commandArgs.addAll(jvmOptions);
// }
// commandArgs.add(mainClass);
// processBuilder.command(commandArgs);
// try {
// process = processBuilder.start();
// startedAt = System.currentTimeMillis();
// pid = process.pid();
// LOG.info("process started: id={}, pid={}", id, pid);
//
// //return new JvmResult(id, pid, process.waitFor());
// return new JvmResult(id, pid, process.onExit()
// .whenComplete((result, ex) -> {
// if (ex == null) {
//
// }
// })
// .get().exitValue());
// } catch (InterruptedException ex) {
// LOG.info("process interrupted: id={}, pid={}", id, pid);
// try {
// process.waitFor(3, TimeUnit.SECONDS);
// } catch (InterruptedException ignore) {
// }
// process.destroy();
// LOG.info("process destroy: id={}, pid={}", id, pid);
// return new JvmResult(id, pid, -1);
// } catch (Exception ex) {
// LOG.error("Process start failure", ex);
// throw ex;
// } finally {
// monitors.forEach(JvmMonitor::stop);
//
// if (process != null) {
// process.getInputStream().close();
// process.getOutputStream().close();
// process.getErrorStream().close();
// }
// }
// }
//
// public String getId() {
// return id;
// }
//
// public long getPid() {
// return pid;
// }
//
// public long getUptime(){
// return System.currentTimeMillis() - startedAt;
// }
//
// public String getMainClass() {
// return mainClass;
// }
//
// public void addMonitor(JvmMonitor... monitors) {
// this.monitors.addAll(Arrays.asList(monitors));
// }
//
// public void kill() throws IOException {
// try {
// Process killProcess = new ProcessBuilder("kill", "-TERM", Long.toString(pid)).start();
// int killResult = killProcess.waitFor();
// if (killResult != 0)
// throw new IOException("kill " + pid + " is failure");
// } catch (InterruptedException ex) {
// LOG.warn("Kill the process (pid={}) is canceled.", pid);
// }
// }
//
// public void setIoDir(File directory) {
// if (process != null) {
// throw new IllegalStateException("You should call setIoDir before starting process");
// }
// String prefix = fmtIO.format(LocalDateTime.now()) + "." + id;
// processBuilder
// .redirectError(new File(directory, prefix + ".err"))
// .redirectOutput(new File(directory, prefix + ".out"));
// }
//
// public List<MonitorStat> getMonitorStats() {
// return monitors.stream()
// .map(JvmMonitor::getStat)
// .collect(Collectors.toList());
// }
//
// public void setJvmOptions(List<String> options) {
// this.jvmOptions = options;
// }
//
// public List<String> getJvmOptions() {
// return jvmOptions;
// }
//
// void setClasspath(String classpath) {
// this.classpath = classpath;
// }
//
// @Override
// public String toString() {
// return "JvmProcess{id=" + id + ", pid=" + pid + "}";
// }
// }
// Path: falchion-container/src/main/java/net/unit8/falchion/monitor/JstatMonitor.java
import net.unit8.falchion.JvmProcess;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
package net.unit8.falchion.monitor;
/**
* @author kawasima
*/
public class JstatMonitor implements GcMonitor {
private static final Logger LOG = LoggerFactory.getLogger(JstatMonitor.class);
private Process process;
private GcStat stat;
private Thread monitorThread;
@Override | public void start(JvmProcess jvmProcess) { |
kawasima/falchion | falchion-container/src/main/java/net/unit8/falchion/Container.java | // Path: falchion-container/src/main/java/net/unit8/falchion/evaluator/Evaluator.java
// @FunctionalInterface
// public interface Evaluator {
// JvmProcess evaluate(Collection<JvmProcess> processes);
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/monitor/MonitorSupplier.java
// public enum MonitorSupplier {
// GCUTIL_JSTAT(JstatMonitor::new),
// METRICS_JMX(MetricsJmxMonitor::new);
//
// private Supplier<JvmMonitor> monitorSupplier;
//
// MonitorSupplier(Supplier<JvmMonitor> monitorSupplier) {
// this.monitorSupplier = monitorSupplier;
// }
//
// public JvmMonitor createMonitor() {
// return monitorSupplier.get();
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/supplier/AutoOptimizableProcessSupplier.java
// public class AutoOptimizableProcessSupplier implements Supplier<JvmProcess> {
// private static final Logger LOG = LoggerFactory.getLogger(AutoOptimizableProcessSupplier.class);
//
// private StandardOptionProvider standardOptionProvider;
// private Evaluator evaluator;
// private Supplier<JvmProcess> baseSupplier;
// private double variance = 0.1;
//
// public AutoOptimizableProcessSupplier(Supplier<JvmProcess> baseSupplier, Evaluator evaluator) {
// this.baseSupplier = baseSupplier;
// this.evaluator = evaluator;
// standardOptionProvider = new StandardOptionProvider(128, 128, variance);
// }
//
// @Override
// public JvmProcess get() {
// JvmProcess process = baseSupplier.get();
// List<String> options = new ArrayList<>(standardOptionProvider.getOptions());
// process.setJvmOptions(options);
// return process;
// }
//
// public void feedback(Collection<JvmProcess> processes) {
// JvmProcess best = evaluator.evaluate(processes);
// LOG.info("best param {}", best.getJvmOptions());
// standardOptionProvider = new StandardOptionProvider(String.join(" ", best.getJvmOptions()), variance);
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/supplier/StandardProcessSupplier.java
// public class StandardProcessSupplier implements Supplier<JvmProcess> {
// private String javaOpts;
// private String mainClass;
// private String classpath;
// private File logDir;
// private Set<MonitorSupplier> monitorSuppliers;
// private StandardOptionProvider standardOptionProvider;
//
// public StandardProcessSupplier(String mainClass, String classpath, String javaOpts, File logDir, Set<MonitorSupplier> monitorSuppliers) {
// this.javaOpts = javaOpts;
// this.mainClass = mainClass;
// this.classpath = classpath;
// this.logDir = logDir;
// this.monitorSuppliers = monitorSuppliers;
// standardOptionProvider = new StandardOptionProvider(javaOpts, 0.0);
// }
//
// @Override
// public JvmProcess get() {
// JvmProcess p = new JvmProcess(mainClass, classpath);
// p.setJvmOptions(standardOptionProvider.getOptions());
// if (logDir != null && logDir.isDirectory()) {
// p.setIoDir(logDir);
// }
// monitorSuppliers.forEach(ms -> p.addMonitor(ms.createMonitor()));
// return p;
// }
// }
| import net.unit8.falchion.evaluator.Evaluator;
import net.unit8.falchion.monitor.MonitorSupplier;
import net.unit8.falchion.supplier.AutoOptimizableProcessSupplier;
import net.unit8.falchion.supplier.StandardProcessSupplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static java.util.stream.Collectors.joining; | package net.unit8.falchion;
/**
* Manages some JVM processes.
*
* @author kawasima
*/
public class Container {
private static final Logger LOG = LoggerFactory.getLogger(Container.class);
private int poolSize;
private JvmPool pool;
private File logDir;
private long lifetime;
private boolean autoTuning; | // Path: falchion-container/src/main/java/net/unit8/falchion/evaluator/Evaluator.java
// @FunctionalInterface
// public interface Evaluator {
// JvmProcess evaluate(Collection<JvmProcess> processes);
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/monitor/MonitorSupplier.java
// public enum MonitorSupplier {
// GCUTIL_JSTAT(JstatMonitor::new),
// METRICS_JMX(MetricsJmxMonitor::new);
//
// private Supplier<JvmMonitor> monitorSupplier;
//
// MonitorSupplier(Supplier<JvmMonitor> monitorSupplier) {
// this.monitorSupplier = monitorSupplier;
// }
//
// public JvmMonitor createMonitor() {
// return monitorSupplier.get();
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/supplier/AutoOptimizableProcessSupplier.java
// public class AutoOptimizableProcessSupplier implements Supplier<JvmProcess> {
// private static final Logger LOG = LoggerFactory.getLogger(AutoOptimizableProcessSupplier.class);
//
// private StandardOptionProvider standardOptionProvider;
// private Evaluator evaluator;
// private Supplier<JvmProcess> baseSupplier;
// private double variance = 0.1;
//
// public AutoOptimizableProcessSupplier(Supplier<JvmProcess> baseSupplier, Evaluator evaluator) {
// this.baseSupplier = baseSupplier;
// this.evaluator = evaluator;
// standardOptionProvider = new StandardOptionProvider(128, 128, variance);
// }
//
// @Override
// public JvmProcess get() {
// JvmProcess process = baseSupplier.get();
// List<String> options = new ArrayList<>(standardOptionProvider.getOptions());
// process.setJvmOptions(options);
// return process;
// }
//
// public void feedback(Collection<JvmProcess> processes) {
// JvmProcess best = evaluator.evaluate(processes);
// LOG.info("best param {}", best.getJvmOptions());
// standardOptionProvider = new StandardOptionProvider(String.join(" ", best.getJvmOptions()), variance);
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/supplier/StandardProcessSupplier.java
// public class StandardProcessSupplier implements Supplier<JvmProcess> {
// private String javaOpts;
// private String mainClass;
// private String classpath;
// private File logDir;
// private Set<MonitorSupplier> monitorSuppliers;
// private StandardOptionProvider standardOptionProvider;
//
// public StandardProcessSupplier(String mainClass, String classpath, String javaOpts, File logDir, Set<MonitorSupplier> monitorSuppliers) {
// this.javaOpts = javaOpts;
// this.mainClass = mainClass;
// this.classpath = classpath;
// this.logDir = logDir;
// this.monitorSuppliers = monitorSuppliers;
// standardOptionProvider = new StandardOptionProvider(javaOpts, 0.0);
// }
//
// @Override
// public JvmProcess get() {
// JvmProcess p = new JvmProcess(mainClass, classpath);
// p.setJvmOptions(standardOptionProvider.getOptions());
// if (logDir != null && logDir.isDirectory()) {
// p.setIoDir(logDir);
// }
// monitorSuppliers.forEach(ms -> p.addMonitor(ms.createMonitor()));
// return p;
// }
// }
// Path: falchion-container/src/main/java/net/unit8/falchion/Container.java
import net.unit8.falchion.evaluator.Evaluator;
import net.unit8.falchion.monitor.MonitorSupplier;
import net.unit8.falchion.supplier.AutoOptimizableProcessSupplier;
import net.unit8.falchion.supplier.StandardProcessSupplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static java.util.stream.Collectors.joining;
package net.unit8.falchion;
/**
* Manages some JVM processes.
*
* @author kawasima
*/
public class Container {
private static final Logger LOG = LoggerFactory.getLogger(Container.class);
private int poolSize;
private JvmPool pool;
private File logDir;
private long lifetime;
private boolean autoTuning; | private Evaluator evaluator; |
kawasima/falchion | falchion-container/src/main/java/net/unit8/falchion/Container.java | // Path: falchion-container/src/main/java/net/unit8/falchion/evaluator/Evaluator.java
// @FunctionalInterface
// public interface Evaluator {
// JvmProcess evaluate(Collection<JvmProcess> processes);
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/monitor/MonitorSupplier.java
// public enum MonitorSupplier {
// GCUTIL_JSTAT(JstatMonitor::new),
// METRICS_JMX(MetricsJmxMonitor::new);
//
// private Supplier<JvmMonitor> monitorSupplier;
//
// MonitorSupplier(Supplier<JvmMonitor> monitorSupplier) {
// this.monitorSupplier = monitorSupplier;
// }
//
// public JvmMonitor createMonitor() {
// return monitorSupplier.get();
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/supplier/AutoOptimizableProcessSupplier.java
// public class AutoOptimizableProcessSupplier implements Supplier<JvmProcess> {
// private static final Logger LOG = LoggerFactory.getLogger(AutoOptimizableProcessSupplier.class);
//
// private StandardOptionProvider standardOptionProvider;
// private Evaluator evaluator;
// private Supplier<JvmProcess> baseSupplier;
// private double variance = 0.1;
//
// public AutoOptimizableProcessSupplier(Supplier<JvmProcess> baseSupplier, Evaluator evaluator) {
// this.baseSupplier = baseSupplier;
// this.evaluator = evaluator;
// standardOptionProvider = new StandardOptionProvider(128, 128, variance);
// }
//
// @Override
// public JvmProcess get() {
// JvmProcess process = baseSupplier.get();
// List<String> options = new ArrayList<>(standardOptionProvider.getOptions());
// process.setJvmOptions(options);
// return process;
// }
//
// public void feedback(Collection<JvmProcess> processes) {
// JvmProcess best = evaluator.evaluate(processes);
// LOG.info("best param {}", best.getJvmOptions());
// standardOptionProvider = new StandardOptionProvider(String.join(" ", best.getJvmOptions()), variance);
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/supplier/StandardProcessSupplier.java
// public class StandardProcessSupplier implements Supplier<JvmProcess> {
// private String javaOpts;
// private String mainClass;
// private String classpath;
// private File logDir;
// private Set<MonitorSupplier> monitorSuppliers;
// private StandardOptionProvider standardOptionProvider;
//
// public StandardProcessSupplier(String mainClass, String classpath, String javaOpts, File logDir, Set<MonitorSupplier> monitorSuppliers) {
// this.javaOpts = javaOpts;
// this.mainClass = mainClass;
// this.classpath = classpath;
// this.logDir = logDir;
// this.monitorSuppliers = monitorSuppliers;
// standardOptionProvider = new StandardOptionProvider(javaOpts, 0.0);
// }
//
// @Override
// public JvmProcess get() {
// JvmProcess p = new JvmProcess(mainClass, classpath);
// p.setJvmOptions(standardOptionProvider.getOptions());
// if (logDir != null && logDir.isDirectory()) {
// p.setIoDir(logDir);
// }
// monitorSuppliers.forEach(ms -> p.addMonitor(ms.createMonitor()));
// return p;
// }
// }
| import net.unit8.falchion.evaluator.Evaluator;
import net.unit8.falchion.monitor.MonitorSupplier;
import net.unit8.falchion.supplier.AutoOptimizableProcessSupplier;
import net.unit8.falchion.supplier.StandardProcessSupplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static java.util.stream.Collectors.joining; | package net.unit8.falchion;
/**
* Manages some JVM processes.
*
* @author kawasima
*/
public class Container {
private static final Logger LOG = LoggerFactory.getLogger(Container.class);
private int poolSize;
private JvmPool pool;
private File logDir;
private long lifetime;
private boolean autoTuning;
private Evaluator evaluator;
private String javaOpts;
private String basedir;
private ScheduledExecutorService autoRefreshTimer;
| // Path: falchion-container/src/main/java/net/unit8/falchion/evaluator/Evaluator.java
// @FunctionalInterface
// public interface Evaluator {
// JvmProcess evaluate(Collection<JvmProcess> processes);
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/monitor/MonitorSupplier.java
// public enum MonitorSupplier {
// GCUTIL_JSTAT(JstatMonitor::new),
// METRICS_JMX(MetricsJmxMonitor::new);
//
// private Supplier<JvmMonitor> monitorSupplier;
//
// MonitorSupplier(Supplier<JvmMonitor> monitorSupplier) {
// this.monitorSupplier = monitorSupplier;
// }
//
// public JvmMonitor createMonitor() {
// return monitorSupplier.get();
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/supplier/AutoOptimizableProcessSupplier.java
// public class AutoOptimizableProcessSupplier implements Supplier<JvmProcess> {
// private static final Logger LOG = LoggerFactory.getLogger(AutoOptimizableProcessSupplier.class);
//
// private StandardOptionProvider standardOptionProvider;
// private Evaluator evaluator;
// private Supplier<JvmProcess> baseSupplier;
// private double variance = 0.1;
//
// public AutoOptimizableProcessSupplier(Supplier<JvmProcess> baseSupplier, Evaluator evaluator) {
// this.baseSupplier = baseSupplier;
// this.evaluator = evaluator;
// standardOptionProvider = new StandardOptionProvider(128, 128, variance);
// }
//
// @Override
// public JvmProcess get() {
// JvmProcess process = baseSupplier.get();
// List<String> options = new ArrayList<>(standardOptionProvider.getOptions());
// process.setJvmOptions(options);
// return process;
// }
//
// public void feedback(Collection<JvmProcess> processes) {
// JvmProcess best = evaluator.evaluate(processes);
// LOG.info("best param {}", best.getJvmOptions());
// standardOptionProvider = new StandardOptionProvider(String.join(" ", best.getJvmOptions()), variance);
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/supplier/StandardProcessSupplier.java
// public class StandardProcessSupplier implements Supplier<JvmProcess> {
// private String javaOpts;
// private String mainClass;
// private String classpath;
// private File logDir;
// private Set<MonitorSupplier> monitorSuppliers;
// private StandardOptionProvider standardOptionProvider;
//
// public StandardProcessSupplier(String mainClass, String classpath, String javaOpts, File logDir, Set<MonitorSupplier> monitorSuppliers) {
// this.javaOpts = javaOpts;
// this.mainClass = mainClass;
// this.classpath = classpath;
// this.logDir = logDir;
// this.monitorSuppliers = monitorSuppliers;
// standardOptionProvider = new StandardOptionProvider(javaOpts, 0.0);
// }
//
// @Override
// public JvmProcess get() {
// JvmProcess p = new JvmProcess(mainClass, classpath);
// p.setJvmOptions(standardOptionProvider.getOptions());
// if (logDir != null && logDir.isDirectory()) {
// p.setIoDir(logDir);
// }
// monitorSuppliers.forEach(ms -> p.addMonitor(ms.createMonitor()));
// return p;
// }
// }
// Path: falchion-container/src/main/java/net/unit8/falchion/Container.java
import net.unit8.falchion.evaluator.Evaluator;
import net.unit8.falchion.monitor.MonitorSupplier;
import net.unit8.falchion.supplier.AutoOptimizableProcessSupplier;
import net.unit8.falchion.supplier.StandardProcessSupplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static java.util.stream.Collectors.joining;
package net.unit8.falchion;
/**
* Manages some JVM processes.
*
* @author kawasima
*/
public class Container {
private static final Logger LOG = LoggerFactory.getLogger(Container.class);
private int poolSize;
private JvmPool pool;
private File logDir;
private long lifetime;
private boolean autoTuning;
private Evaluator evaluator;
private String javaOpts;
private String basedir;
private ScheduledExecutorService autoRefreshTimer;
| private Set<MonitorSupplier> monitorSuppliers; |
kawasima/falchion | falchion-container/src/main/java/net/unit8/falchion/Container.java | // Path: falchion-container/src/main/java/net/unit8/falchion/evaluator/Evaluator.java
// @FunctionalInterface
// public interface Evaluator {
// JvmProcess evaluate(Collection<JvmProcess> processes);
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/monitor/MonitorSupplier.java
// public enum MonitorSupplier {
// GCUTIL_JSTAT(JstatMonitor::new),
// METRICS_JMX(MetricsJmxMonitor::new);
//
// private Supplier<JvmMonitor> monitorSupplier;
//
// MonitorSupplier(Supplier<JvmMonitor> monitorSupplier) {
// this.monitorSupplier = monitorSupplier;
// }
//
// public JvmMonitor createMonitor() {
// return monitorSupplier.get();
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/supplier/AutoOptimizableProcessSupplier.java
// public class AutoOptimizableProcessSupplier implements Supplier<JvmProcess> {
// private static final Logger LOG = LoggerFactory.getLogger(AutoOptimizableProcessSupplier.class);
//
// private StandardOptionProvider standardOptionProvider;
// private Evaluator evaluator;
// private Supplier<JvmProcess> baseSupplier;
// private double variance = 0.1;
//
// public AutoOptimizableProcessSupplier(Supplier<JvmProcess> baseSupplier, Evaluator evaluator) {
// this.baseSupplier = baseSupplier;
// this.evaluator = evaluator;
// standardOptionProvider = new StandardOptionProvider(128, 128, variance);
// }
//
// @Override
// public JvmProcess get() {
// JvmProcess process = baseSupplier.get();
// List<String> options = new ArrayList<>(standardOptionProvider.getOptions());
// process.setJvmOptions(options);
// return process;
// }
//
// public void feedback(Collection<JvmProcess> processes) {
// JvmProcess best = evaluator.evaluate(processes);
// LOG.info("best param {}", best.getJvmOptions());
// standardOptionProvider = new StandardOptionProvider(String.join(" ", best.getJvmOptions()), variance);
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/supplier/StandardProcessSupplier.java
// public class StandardProcessSupplier implements Supplier<JvmProcess> {
// private String javaOpts;
// private String mainClass;
// private String classpath;
// private File logDir;
// private Set<MonitorSupplier> monitorSuppliers;
// private StandardOptionProvider standardOptionProvider;
//
// public StandardProcessSupplier(String mainClass, String classpath, String javaOpts, File logDir, Set<MonitorSupplier> monitorSuppliers) {
// this.javaOpts = javaOpts;
// this.mainClass = mainClass;
// this.classpath = classpath;
// this.logDir = logDir;
// this.monitorSuppliers = monitorSuppliers;
// standardOptionProvider = new StandardOptionProvider(javaOpts, 0.0);
// }
//
// @Override
// public JvmProcess get() {
// JvmProcess p = new JvmProcess(mainClass, classpath);
// p.setJvmOptions(standardOptionProvider.getOptions());
// if (logDir != null && logDir.isDirectory()) {
// p.setIoDir(logDir);
// }
// monitorSuppliers.forEach(ms -> p.addMonitor(ms.createMonitor()));
// return p;
// }
// }
| import net.unit8.falchion.evaluator.Evaluator;
import net.unit8.falchion.monitor.MonitorSupplier;
import net.unit8.falchion.supplier.AutoOptimizableProcessSupplier;
import net.unit8.falchion.supplier.StandardProcessSupplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static java.util.stream.Collectors.joining; | package net.unit8.falchion;
/**
* Manages some JVM processes.
*
* @author kawasima
*/
public class Container {
private static final Logger LOG = LoggerFactory.getLogger(Container.class);
private int poolSize;
private JvmPool pool;
private File logDir;
private long lifetime;
private boolean autoTuning;
private Evaluator evaluator;
private String javaOpts;
private String basedir;
private ScheduledExecutorService autoRefreshTimer;
private Set<MonitorSupplier> monitorSuppliers;
/**
* Creates a container.
*
* @param poolSize The size of JVM pool.
*/
public Container(int poolSize) {
this.poolSize = poolSize;
}
/**
* Gets the classpath that is applied for a child process.
*
* @return a String contains classpath
*/
private String getClasspath() {
LOG.info(System.getProperty("java.class.path"));
return Arrays.stream(System.getProperty("java.class.path").split(File.pathSeparator))
.map(File::new)
.map(File::getAbsolutePath)
.collect(joining(":"));
}
/**
* Starts the container.
*
* @param mainClass the name of main class
* @param classpath the classpath is applied for a child process
*/
public void start(final String mainClass, String classpath) { | // Path: falchion-container/src/main/java/net/unit8/falchion/evaluator/Evaluator.java
// @FunctionalInterface
// public interface Evaluator {
// JvmProcess evaluate(Collection<JvmProcess> processes);
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/monitor/MonitorSupplier.java
// public enum MonitorSupplier {
// GCUTIL_JSTAT(JstatMonitor::new),
// METRICS_JMX(MetricsJmxMonitor::new);
//
// private Supplier<JvmMonitor> monitorSupplier;
//
// MonitorSupplier(Supplier<JvmMonitor> monitorSupplier) {
// this.monitorSupplier = monitorSupplier;
// }
//
// public JvmMonitor createMonitor() {
// return monitorSupplier.get();
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/supplier/AutoOptimizableProcessSupplier.java
// public class AutoOptimizableProcessSupplier implements Supplier<JvmProcess> {
// private static final Logger LOG = LoggerFactory.getLogger(AutoOptimizableProcessSupplier.class);
//
// private StandardOptionProvider standardOptionProvider;
// private Evaluator evaluator;
// private Supplier<JvmProcess> baseSupplier;
// private double variance = 0.1;
//
// public AutoOptimizableProcessSupplier(Supplier<JvmProcess> baseSupplier, Evaluator evaluator) {
// this.baseSupplier = baseSupplier;
// this.evaluator = evaluator;
// standardOptionProvider = new StandardOptionProvider(128, 128, variance);
// }
//
// @Override
// public JvmProcess get() {
// JvmProcess process = baseSupplier.get();
// List<String> options = new ArrayList<>(standardOptionProvider.getOptions());
// process.setJvmOptions(options);
// return process;
// }
//
// public void feedback(Collection<JvmProcess> processes) {
// JvmProcess best = evaluator.evaluate(processes);
// LOG.info("best param {}", best.getJvmOptions());
// standardOptionProvider = new StandardOptionProvider(String.join(" ", best.getJvmOptions()), variance);
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/supplier/StandardProcessSupplier.java
// public class StandardProcessSupplier implements Supplier<JvmProcess> {
// private String javaOpts;
// private String mainClass;
// private String classpath;
// private File logDir;
// private Set<MonitorSupplier> monitorSuppliers;
// private StandardOptionProvider standardOptionProvider;
//
// public StandardProcessSupplier(String mainClass, String classpath, String javaOpts, File logDir, Set<MonitorSupplier> monitorSuppliers) {
// this.javaOpts = javaOpts;
// this.mainClass = mainClass;
// this.classpath = classpath;
// this.logDir = logDir;
// this.monitorSuppliers = monitorSuppliers;
// standardOptionProvider = new StandardOptionProvider(javaOpts, 0.0);
// }
//
// @Override
// public JvmProcess get() {
// JvmProcess p = new JvmProcess(mainClass, classpath);
// p.setJvmOptions(standardOptionProvider.getOptions());
// if (logDir != null && logDir.isDirectory()) {
// p.setIoDir(logDir);
// }
// monitorSuppliers.forEach(ms -> p.addMonitor(ms.createMonitor()));
// return p;
// }
// }
// Path: falchion-container/src/main/java/net/unit8/falchion/Container.java
import net.unit8.falchion.evaluator.Evaluator;
import net.unit8.falchion.monitor.MonitorSupplier;
import net.unit8.falchion.supplier.AutoOptimizableProcessSupplier;
import net.unit8.falchion.supplier.StandardProcessSupplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static java.util.stream.Collectors.joining;
package net.unit8.falchion;
/**
* Manages some JVM processes.
*
* @author kawasima
*/
public class Container {
private static final Logger LOG = LoggerFactory.getLogger(Container.class);
private int poolSize;
private JvmPool pool;
private File logDir;
private long lifetime;
private boolean autoTuning;
private Evaluator evaluator;
private String javaOpts;
private String basedir;
private ScheduledExecutorService autoRefreshTimer;
private Set<MonitorSupplier> monitorSuppliers;
/**
* Creates a container.
*
* @param poolSize The size of JVM pool.
*/
public Container(int poolSize) {
this.poolSize = poolSize;
}
/**
* Gets the classpath that is applied for a child process.
*
* @return a String contains classpath
*/
private String getClasspath() {
LOG.info(System.getProperty("java.class.path"));
return Arrays.stream(System.getProperty("java.class.path").split(File.pathSeparator))
.map(File::new)
.map(File::getAbsolutePath)
.collect(joining(":"));
}
/**
* Starts the container.
*
* @param mainClass the name of main class
* @param classpath the classpath is applied for a child process
*/
public void start(final String mainClass, String classpath) { | Supplier<JvmProcess> processSupplier = new StandardProcessSupplier( |
kawasima/falchion | falchion-container/src/main/java/net/unit8/falchion/Container.java | // Path: falchion-container/src/main/java/net/unit8/falchion/evaluator/Evaluator.java
// @FunctionalInterface
// public interface Evaluator {
// JvmProcess evaluate(Collection<JvmProcess> processes);
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/monitor/MonitorSupplier.java
// public enum MonitorSupplier {
// GCUTIL_JSTAT(JstatMonitor::new),
// METRICS_JMX(MetricsJmxMonitor::new);
//
// private Supplier<JvmMonitor> monitorSupplier;
//
// MonitorSupplier(Supplier<JvmMonitor> monitorSupplier) {
// this.monitorSupplier = monitorSupplier;
// }
//
// public JvmMonitor createMonitor() {
// return monitorSupplier.get();
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/supplier/AutoOptimizableProcessSupplier.java
// public class AutoOptimizableProcessSupplier implements Supplier<JvmProcess> {
// private static final Logger LOG = LoggerFactory.getLogger(AutoOptimizableProcessSupplier.class);
//
// private StandardOptionProvider standardOptionProvider;
// private Evaluator evaluator;
// private Supplier<JvmProcess> baseSupplier;
// private double variance = 0.1;
//
// public AutoOptimizableProcessSupplier(Supplier<JvmProcess> baseSupplier, Evaluator evaluator) {
// this.baseSupplier = baseSupplier;
// this.evaluator = evaluator;
// standardOptionProvider = new StandardOptionProvider(128, 128, variance);
// }
//
// @Override
// public JvmProcess get() {
// JvmProcess process = baseSupplier.get();
// List<String> options = new ArrayList<>(standardOptionProvider.getOptions());
// process.setJvmOptions(options);
// return process;
// }
//
// public void feedback(Collection<JvmProcess> processes) {
// JvmProcess best = evaluator.evaluate(processes);
// LOG.info("best param {}", best.getJvmOptions());
// standardOptionProvider = new StandardOptionProvider(String.join(" ", best.getJvmOptions()), variance);
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/supplier/StandardProcessSupplier.java
// public class StandardProcessSupplier implements Supplier<JvmProcess> {
// private String javaOpts;
// private String mainClass;
// private String classpath;
// private File logDir;
// private Set<MonitorSupplier> monitorSuppliers;
// private StandardOptionProvider standardOptionProvider;
//
// public StandardProcessSupplier(String mainClass, String classpath, String javaOpts, File logDir, Set<MonitorSupplier> monitorSuppliers) {
// this.javaOpts = javaOpts;
// this.mainClass = mainClass;
// this.classpath = classpath;
// this.logDir = logDir;
// this.monitorSuppliers = monitorSuppliers;
// standardOptionProvider = new StandardOptionProvider(javaOpts, 0.0);
// }
//
// @Override
// public JvmProcess get() {
// JvmProcess p = new JvmProcess(mainClass, classpath);
// p.setJvmOptions(standardOptionProvider.getOptions());
// if (logDir != null && logDir.isDirectory()) {
// p.setIoDir(logDir);
// }
// monitorSuppliers.forEach(ms -> p.addMonitor(ms.createMonitor()));
// return p;
// }
// }
| import net.unit8.falchion.evaluator.Evaluator;
import net.unit8.falchion.monitor.MonitorSupplier;
import net.unit8.falchion.supplier.AutoOptimizableProcessSupplier;
import net.unit8.falchion.supplier.StandardProcessSupplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static java.util.stream.Collectors.joining; | package net.unit8.falchion;
/**
* Manages some JVM processes.
*
* @author kawasima
*/
public class Container {
private static final Logger LOG = LoggerFactory.getLogger(Container.class);
private int poolSize;
private JvmPool pool;
private File logDir;
private long lifetime;
private boolean autoTuning;
private Evaluator evaluator;
private String javaOpts;
private String basedir;
private ScheduledExecutorService autoRefreshTimer;
private Set<MonitorSupplier> monitorSuppliers;
/**
* Creates a container.
*
* @param poolSize The size of JVM pool.
*/
public Container(int poolSize) {
this.poolSize = poolSize;
}
/**
* Gets the classpath that is applied for a child process.
*
* @return a String contains classpath
*/
private String getClasspath() {
LOG.info(System.getProperty("java.class.path"));
return Arrays.stream(System.getProperty("java.class.path").split(File.pathSeparator))
.map(File::new)
.map(File::getAbsolutePath)
.collect(joining(":"));
}
/**
* Starts the container.
*
* @param mainClass the name of main class
* @param classpath the classpath is applied for a child process
*/
public void start(final String mainClass, String classpath) {
Supplier<JvmProcess> processSupplier = new StandardProcessSupplier(
mainClass, classpath, javaOpts, logDir, monitorSuppliers);
if (autoTuning) {
LOG.info("Auto tuning setup using evaluator {}", evaluator); | // Path: falchion-container/src/main/java/net/unit8/falchion/evaluator/Evaluator.java
// @FunctionalInterface
// public interface Evaluator {
// JvmProcess evaluate(Collection<JvmProcess> processes);
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/monitor/MonitorSupplier.java
// public enum MonitorSupplier {
// GCUTIL_JSTAT(JstatMonitor::new),
// METRICS_JMX(MetricsJmxMonitor::new);
//
// private Supplier<JvmMonitor> monitorSupplier;
//
// MonitorSupplier(Supplier<JvmMonitor> monitorSupplier) {
// this.monitorSupplier = monitorSupplier;
// }
//
// public JvmMonitor createMonitor() {
// return monitorSupplier.get();
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/supplier/AutoOptimizableProcessSupplier.java
// public class AutoOptimizableProcessSupplier implements Supplier<JvmProcess> {
// private static final Logger LOG = LoggerFactory.getLogger(AutoOptimizableProcessSupplier.class);
//
// private StandardOptionProvider standardOptionProvider;
// private Evaluator evaluator;
// private Supplier<JvmProcess> baseSupplier;
// private double variance = 0.1;
//
// public AutoOptimizableProcessSupplier(Supplier<JvmProcess> baseSupplier, Evaluator evaluator) {
// this.baseSupplier = baseSupplier;
// this.evaluator = evaluator;
// standardOptionProvider = new StandardOptionProvider(128, 128, variance);
// }
//
// @Override
// public JvmProcess get() {
// JvmProcess process = baseSupplier.get();
// List<String> options = new ArrayList<>(standardOptionProvider.getOptions());
// process.setJvmOptions(options);
// return process;
// }
//
// public void feedback(Collection<JvmProcess> processes) {
// JvmProcess best = evaluator.evaluate(processes);
// LOG.info("best param {}", best.getJvmOptions());
// standardOptionProvider = new StandardOptionProvider(String.join(" ", best.getJvmOptions()), variance);
// }
// }
//
// Path: falchion-container/src/main/java/net/unit8/falchion/supplier/StandardProcessSupplier.java
// public class StandardProcessSupplier implements Supplier<JvmProcess> {
// private String javaOpts;
// private String mainClass;
// private String classpath;
// private File logDir;
// private Set<MonitorSupplier> monitorSuppliers;
// private StandardOptionProvider standardOptionProvider;
//
// public StandardProcessSupplier(String mainClass, String classpath, String javaOpts, File logDir, Set<MonitorSupplier> monitorSuppliers) {
// this.javaOpts = javaOpts;
// this.mainClass = mainClass;
// this.classpath = classpath;
// this.logDir = logDir;
// this.monitorSuppliers = monitorSuppliers;
// standardOptionProvider = new StandardOptionProvider(javaOpts, 0.0);
// }
//
// @Override
// public JvmProcess get() {
// JvmProcess p = new JvmProcess(mainClass, classpath);
// p.setJvmOptions(standardOptionProvider.getOptions());
// if (logDir != null && logDir.isDirectory()) {
// p.setIoDir(logDir);
// }
// monitorSuppliers.forEach(ms -> p.addMonitor(ms.createMonitor()));
// return p;
// }
// }
// Path: falchion-container/src/main/java/net/unit8/falchion/Container.java
import net.unit8.falchion.evaluator.Evaluator;
import net.unit8.falchion.monitor.MonitorSupplier;
import net.unit8.falchion.supplier.AutoOptimizableProcessSupplier;
import net.unit8.falchion.supplier.StandardProcessSupplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static java.util.stream.Collectors.joining;
package net.unit8.falchion;
/**
* Manages some JVM processes.
*
* @author kawasima
*/
public class Container {
private static final Logger LOG = LoggerFactory.getLogger(Container.class);
private int poolSize;
private JvmPool pool;
private File logDir;
private long lifetime;
private boolean autoTuning;
private Evaluator evaluator;
private String javaOpts;
private String basedir;
private ScheduledExecutorService autoRefreshTimer;
private Set<MonitorSupplier> monitorSuppliers;
/**
* Creates a container.
*
* @param poolSize The size of JVM pool.
*/
public Container(int poolSize) {
this.poolSize = poolSize;
}
/**
* Gets the classpath that is applied for a child process.
*
* @return a String contains classpath
*/
private String getClasspath() {
LOG.info(System.getProperty("java.class.path"));
return Arrays.stream(System.getProperty("java.class.path").split(File.pathSeparator))
.map(File::new)
.map(File::getAbsolutePath)
.collect(joining(":"));
}
/**
* Starts the container.
*
* @param mainClass the name of main class
* @param classpath the classpath is applied for a child process
*/
public void start(final String mainClass, String classpath) {
Supplier<JvmProcess> processSupplier = new StandardProcessSupplier(
mainClass, classpath, javaOpts, logDir, monitorSuppliers);
if (autoTuning) {
LOG.info("Auto tuning setup using evaluator {}", evaluator); | processSupplier = new AutoOptimizableProcessSupplier(processSupplier, evaluator); |
desht/ScrollingMenuSign | src/main/java/me/desht/scrollingmenusign/views/action/ViewUpdateAction.java | // Path: src/main/java/me/desht/scrollingmenusign/enums/SMSMenuAction.java
// public enum SMSMenuAction {
// DO_NOTHING, REPAINT, BLANK_SIGN, DESTROY_SIGN, SCROLLED, DELETE_TEMP, DELETE_PERM
// }
| import me.desht.scrollingmenusign.enums.SMSMenuAction;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; | package me.desht.scrollingmenusign.views.action;
public abstract class ViewUpdateAction {
// private final SMSMenuAction action;
private final CommandSender sender;
public ViewUpdateAction(CommandSender sender) {
// this.action = action;
this.sender = sender;
}
public ViewUpdateAction() {
// this.action = action;
this.sender = null;
}
//
// public SMSMenuAction getAction() {
// return action;
// }
public CommandSender getSender() {
return sender;
}
public static ViewUpdateAction getAction(Object o) { | // Path: src/main/java/me/desht/scrollingmenusign/enums/SMSMenuAction.java
// public enum SMSMenuAction {
// DO_NOTHING, REPAINT, BLANK_SIGN, DESTROY_SIGN, SCROLLED, DELETE_TEMP, DELETE_PERM
// }
// Path: src/main/java/me/desht/scrollingmenusign/views/action/ViewUpdateAction.java
import me.desht.scrollingmenusign.enums.SMSMenuAction;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
package me.desht.scrollingmenusign.views.action;
public abstract class ViewUpdateAction {
// private final SMSMenuAction action;
private final CommandSender sender;
public ViewUpdateAction(CommandSender sender) {
// this.action = action;
this.sender = sender;
}
public ViewUpdateAction() {
// this.action = action;
this.sender = null;
}
//
// public SMSMenuAction getAction() {
// return action;
// }
public CommandSender getSender() {
return sender;
}
public static ViewUpdateAction getAction(Object o) { | if (o instanceof SMSMenuAction) { |
desht/ScrollingMenuSign | src/main/java/me/desht/scrollingmenusign/views/ViewManager.java | // Path: src/main/java/me/desht/scrollingmenusign/views/SMSMapView.java
// public class SMSMapRenderer extends MapRenderer {
// private final SMSMapView view;
//
// public SMSMapRenderer(SMSMapView view) {
// super(true);
// this.view = view;
// }
//
// public SMSMapView getView() {
// return view;
// }
//
// @Override
// public void render(MapView map, MapCanvas canvas, Player player) {
// if (isDirty(player)) {
// BufferedImage img = renderImage(player);
// canvas.drawImage(0, 0, img);
// setDirty(player, false);
// player.sendMap(map);
// }
// }
// }
//
// Path: src/main/java/me/desht/scrollingmenusign/views/SMSView.java
// public class MenuStack {
// final Deque<WeakReference<SMSMenu>> stack;
//
// public MenuStack() {
// stack = new ArrayDeque<WeakReference<SMSMenu>>();
// }
//
// public void pushMenu(SMSMenu menu) {
// stack.push(new WeakReference<SMSMenu>(menu));
// }
//
// public SMSMenu popMenu() {
// return stack.pop().get();
// }
//
// public SMSMenu peek() {
// return stack.peek().get();
// }
//
// public boolean isEmpty() {
// return stack.isEmpty();
// }
// }
//
// Path: src/main/java/me/desht/scrollingmenusign/views/action/RepaintAction.java
// public class RepaintAction extends ViewUpdateAction {
// public RepaintAction() {
// super();
// }
//
// public RepaintAction(CommandSender sender) {
// super(sender);
// }
// }
| import me.desht.dhutils.Debugger;
import me.desht.dhutils.LogUtils;
import me.desht.dhutils.block.BlockUtil;
import me.desht.scrollingmenusign.*;
import me.desht.scrollingmenusign.views.SMSMapView.SMSMapRenderer;
import me.desht.scrollingmenusign.views.SMSView.MenuStack;
import me.desht.scrollingmenusign.views.action.RepaintAction;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.map.MapRenderer;
import org.bukkit.map.MapView;
import org.bukkit.util.Vector;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.Map.Entry; |
private void loadError(String viewName, Throwable e) {
LogUtils.warning("Caught " + e.getClass().getName() + " while loading view " + viewName);
LogUtils.warning(" Exception message: " + e.getMessage());
}
/**
* Register this view in the global view list and get it saved to disk.
*/
public void registerView(SMSView view) {
if (allViewNames.containsKey(view.getName())) {
throw new SMSException("A view named '" + view.getName() + "' already exists.");
}
allViewNames.put(view.getName(), view);
for (Location l : view.getLocations()) {
plugin.getLocationManager().registerLocation(l, view);
}
view.getNativeMenu().addObserver(view);
view.autosave();
}
/**
* Unregister a view: remove it as an observer from its menu (and any active submenus),
* and remove its name & location(s) from the manager.
*
* @param view the view to unregister
*/
private void unregisterView(SMSView view) {
view.getNativeMenu().deleteObserver(view);
for (UUID playerId : view.getSubmenuPlayers()) { | // Path: src/main/java/me/desht/scrollingmenusign/views/SMSMapView.java
// public class SMSMapRenderer extends MapRenderer {
// private final SMSMapView view;
//
// public SMSMapRenderer(SMSMapView view) {
// super(true);
// this.view = view;
// }
//
// public SMSMapView getView() {
// return view;
// }
//
// @Override
// public void render(MapView map, MapCanvas canvas, Player player) {
// if (isDirty(player)) {
// BufferedImage img = renderImage(player);
// canvas.drawImage(0, 0, img);
// setDirty(player, false);
// player.sendMap(map);
// }
// }
// }
//
// Path: src/main/java/me/desht/scrollingmenusign/views/SMSView.java
// public class MenuStack {
// final Deque<WeakReference<SMSMenu>> stack;
//
// public MenuStack() {
// stack = new ArrayDeque<WeakReference<SMSMenu>>();
// }
//
// public void pushMenu(SMSMenu menu) {
// stack.push(new WeakReference<SMSMenu>(menu));
// }
//
// public SMSMenu popMenu() {
// return stack.pop().get();
// }
//
// public SMSMenu peek() {
// return stack.peek().get();
// }
//
// public boolean isEmpty() {
// return stack.isEmpty();
// }
// }
//
// Path: src/main/java/me/desht/scrollingmenusign/views/action/RepaintAction.java
// public class RepaintAction extends ViewUpdateAction {
// public RepaintAction() {
// super();
// }
//
// public RepaintAction(CommandSender sender) {
// super(sender);
// }
// }
// Path: src/main/java/me/desht/scrollingmenusign/views/ViewManager.java
import me.desht.dhutils.Debugger;
import me.desht.dhutils.LogUtils;
import me.desht.dhutils.block.BlockUtil;
import me.desht.scrollingmenusign.*;
import me.desht.scrollingmenusign.views.SMSMapView.SMSMapRenderer;
import me.desht.scrollingmenusign.views.SMSView.MenuStack;
import me.desht.scrollingmenusign.views.action.RepaintAction;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.map.MapRenderer;
import org.bukkit.map.MapView;
import org.bukkit.util.Vector;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.Map.Entry;
private void loadError(String viewName, Throwable e) {
LogUtils.warning("Caught " + e.getClass().getName() + " while loading view " + viewName);
LogUtils.warning(" Exception message: " + e.getMessage());
}
/**
* Register this view in the global view list and get it saved to disk.
*/
public void registerView(SMSView view) {
if (allViewNames.containsKey(view.getName())) {
throw new SMSException("A view named '" + view.getName() + "' already exists.");
}
allViewNames.put(view.getName(), view);
for (Location l : view.getLocations()) {
plugin.getLocationManager().registerLocation(l, view);
}
view.getNativeMenu().addObserver(view);
view.autosave();
}
/**
* Unregister a view: remove it as an observer from its menu (and any active submenus),
* and remove its name & location(s) from the manager.
*
* @param view the view to unregister
*/
private void unregisterView(SMSView view) {
view.getNativeMenu().deleteObserver(view);
for (UUID playerId : view.getSubmenuPlayers()) { | MenuStack mst = view.getMenuStack(playerId); |
desht/ScrollingMenuSign | src/main/java/me/desht/scrollingmenusign/views/ViewManager.java | // Path: src/main/java/me/desht/scrollingmenusign/views/SMSMapView.java
// public class SMSMapRenderer extends MapRenderer {
// private final SMSMapView view;
//
// public SMSMapRenderer(SMSMapView view) {
// super(true);
// this.view = view;
// }
//
// public SMSMapView getView() {
// return view;
// }
//
// @Override
// public void render(MapView map, MapCanvas canvas, Player player) {
// if (isDirty(player)) {
// BufferedImage img = renderImage(player);
// canvas.drawImage(0, 0, img);
// setDirty(player, false);
// player.sendMap(map);
// }
// }
// }
//
// Path: src/main/java/me/desht/scrollingmenusign/views/SMSView.java
// public class MenuStack {
// final Deque<WeakReference<SMSMenu>> stack;
//
// public MenuStack() {
// stack = new ArrayDeque<WeakReference<SMSMenu>>();
// }
//
// public void pushMenu(SMSMenu menu) {
// stack.push(new WeakReference<SMSMenu>(menu));
// }
//
// public SMSMenu popMenu() {
// return stack.pop().get();
// }
//
// public SMSMenu peek() {
// return stack.peek().get();
// }
//
// public boolean isEmpty() {
// return stack.isEmpty();
// }
// }
//
// Path: src/main/java/me/desht/scrollingmenusign/views/action/RepaintAction.java
// public class RepaintAction extends ViewUpdateAction {
// public RepaintAction() {
// super();
// }
//
// public RepaintAction(CommandSender sender) {
// super(sender);
// }
// }
| import me.desht.dhutils.Debugger;
import me.desht.dhutils.LogUtils;
import me.desht.dhutils.block.BlockUtil;
import me.desht.scrollingmenusign.*;
import me.desht.scrollingmenusign.views.SMSMapView.SMSMapRenderer;
import me.desht.scrollingmenusign.views.SMSView.MenuStack;
import me.desht.scrollingmenusign.views.action.RepaintAction;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.map.MapRenderer;
import org.bukkit.map.MapView;
import org.bukkit.util.Vector;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.Map.Entry; | public void loadDeferred(World world) {
for (SMSView view : listViews()) {
List<Vector> l = view.getDeferredLocations(world.getName());
if (l == null) {
continue;
}
for (Vector vec : l) {
try {
view.addLocation(new Location(world, vec.getBlockX(), vec.getBlockY(), vec.getBlockZ()));
Debugger.getInstance().debug("added loc " + world.getName() + ", " + vec + " to view " + view.getName());
} catch (SMSException e) {
LogUtils.warning("Can't add location " + world.getName() + ", " + vec + " to view " + view.getName());
LogUtils.warning(" Exception message: " + e.getMessage());
}
}
l.clear();
}
}
/**
* Given a map ID, return the map view object for that ID, if any.
*
* @param mapId The ID of the map
* @return The SMSMapView object for the ID, or null if this map ID isn't used for a SMSMapView
*/
public SMSMapView getMapViewForId(short mapId) {
MapView mv = Bukkit.getMap(mapId);
if (mv != null) {
for (MapRenderer r : mv.getRenderers()) { | // Path: src/main/java/me/desht/scrollingmenusign/views/SMSMapView.java
// public class SMSMapRenderer extends MapRenderer {
// private final SMSMapView view;
//
// public SMSMapRenderer(SMSMapView view) {
// super(true);
// this.view = view;
// }
//
// public SMSMapView getView() {
// return view;
// }
//
// @Override
// public void render(MapView map, MapCanvas canvas, Player player) {
// if (isDirty(player)) {
// BufferedImage img = renderImage(player);
// canvas.drawImage(0, 0, img);
// setDirty(player, false);
// player.sendMap(map);
// }
// }
// }
//
// Path: src/main/java/me/desht/scrollingmenusign/views/SMSView.java
// public class MenuStack {
// final Deque<WeakReference<SMSMenu>> stack;
//
// public MenuStack() {
// stack = new ArrayDeque<WeakReference<SMSMenu>>();
// }
//
// public void pushMenu(SMSMenu menu) {
// stack.push(new WeakReference<SMSMenu>(menu));
// }
//
// public SMSMenu popMenu() {
// return stack.pop().get();
// }
//
// public SMSMenu peek() {
// return stack.peek().get();
// }
//
// public boolean isEmpty() {
// return stack.isEmpty();
// }
// }
//
// Path: src/main/java/me/desht/scrollingmenusign/views/action/RepaintAction.java
// public class RepaintAction extends ViewUpdateAction {
// public RepaintAction() {
// super();
// }
//
// public RepaintAction(CommandSender sender) {
// super(sender);
// }
// }
// Path: src/main/java/me/desht/scrollingmenusign/views/ViewManager.java
import me.desht.dhutils.Debugger;
import me.desht.dhutils.LogUtils;
import me.desht.dhutils.block.BlockUtil;
import me.desht.scrollingmenusign.*;
import me.desht.scrollingmenusign.views.SMSMapView.SMSMapRenderer;
import me.desht.scrollingmenusign.views.SMSView.MenuStack;
import me.desht.scrollingmenusign.views.action.RepaintAction;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.map.MapRenderer;
import org.bukkit.map.MapView;
import org.bukkit.util.Vector;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.Map.Entry;
public void loadDeferred(World world) {
for (SMSView view : listViews()) {
List<Vector> l = view.getDeferredLocations(world.getName());
if (l == null) {
continue;
}
for (Vector vec : l) {
try {
view.addLocation(new Location(world, vec.getBlockX(), vec.getBlockY(), vec.getBlockZ()));
Debugger.getInstance().debug("added loc " + world.getName() + ", " + vec + " to view " + view.getName());
} catch (SMSException e) {
LogUtils.warning("Can't add location " + world.getName() + ", " + vec + " to view " + view.getName());
LogUtils.warning(" Exception message: " + e.getMessage());
}
}
l.clear();
}
}
/**
* Given a map ID, return the map view object for that ID, if any.
*
* @param mapId The ID of the map
* @return The SMSMapView object for the ID, or null if this map ID isn't used for a SMSMapView
*/
public SMSMapView getMapViewForId(short mapId) {
MapView mv = Bukkit.getMap(mapId);
if (mv != null) {
for (MapRenderer r : mv.getRenderers()) { | if (r instanceof SMSMapRenderer) { |
desht/ScrollingMenuSign | src/main/java/me/desht/scrollingmenusign/views/ViewManager.java | // Path: src/main/java/me/desht/scrollingmenusign/views/SMSMapView.java
// public class SMSMapRenderer extends MapRenderer {
// private final SMSMapView view;
//
// public SMSMapRenderer(SMSMapView view) {
// super(true);
// this.view = view;
// }
//
// public SMSMapView getView() {
// return view;
// }
//
// @Override
// public void render(MapView map, MapCanvas canvas, Player player) {
// if (isDirty(player)) {
// BufferedImage img = renderImage(player);
// canvas.drawImage(0, 0, img);
// setDirty(player, false);
// player.sendMap(map);
// }
// }
// }
//
// Path: src/main/java/me/desht/scrollingmenusign/views/SMSView.java
// public class MenuStack {
// final Deque<WeakReference<SMSMenu>> stack;
//
// public MenuStack() {
// stack = new ArrayDeque<WeakReference<SMSMenu>>();
// }
//
// public void pushMenu(SMSMenu menu) {
// stack.push(new WeakReference<SMSMenu>(menu));
// }
//
// public SMSMenu popMenu() {
// return stack.pop().get();
// }
//
// public SMSMenu peek() {
// return stack.peek().get();
// }
//
// public boolean isEmpty() {
// return stack.isEmpty();
// }
// }
//
// Path: src/main/java/me/desht/scrollingmenusign/views/action/RepaintAction.java
// public class RepaintAction extends ViewUpdateAction {
// public RepaintAction() {
// super();
// }
//
// public RepaintAction(CommandSender sender) {
// super(sender);
// }
// }
| import me.desht.dhutils.Debugger;
import me.desht.dhutils.LogUtils;
import me.desht.dhutils.block.BlockUtil;
import me.desht.scrollingmenusign.*;
import me.desht.scrollingmenusign.views.SMSMapView.SMSMapRenderer;
import me.desht.scrollingmenusign.views.SMSView.MenuStack;
import me.desht.scrollingmenusign.views.action.RepaintAction;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.map.MapRenderer;
import org.bukkit.map.MapView;
import org.bukkit.util.Vector;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.Map.Entry; | * @param loc Location of the new view
* @return The newly-created view
* @throws SMSException if the given location is not a suitable location for the new view
*/
public SMSView addPublicHoloViewToMenu(String viewName, SMSMenu menu, Location loc, CommandSender owner) {
SMSView view = new SMSPublicHoloView(viewName, menu, loc);
initialiseView(view, owner);
return view;
}
/**
* Convenience method. Create and register a new SMSPrivateHoloView object, and attach it to
* the given menu.
*
* @param viewName Name for the view; if null a name will be auto-generated
* @param menu The menu to attach the new view to
* @return The newly-created view
* @throws SMSException if the given location is not a suitable location for the new view
*/
public SMSView addPrivateHoloToView(String viewName, SMSMenu menu, CommandSender owner) {
SMSView view = new SMSPrivateHoloView(viewName, menu);
initialiseView(view, owner);
return view;
}
private void initialiseView(SMSView view, CommandSender owner) {
// common setup tasks for a new view
registerView(view);
view.setAttribute(SMSView.OWNER, view.makeOwnerName(owner));
view.setOwnerId(getUniqueId(owner)); | // Path: src/main/java/me/desht/scrollingmenusign/views/SMSMapView.java
// public class SMSMapRenderer extends MapRenderer {
// private final SMSMapView view;
//
// public SMSMapRenderer(SMSMapView view) {
// super(true);
// this.view = view;
// }
//
// public SMSMapView getView() {
// return view;
// }
//
// @Override
// public void render(MapView map, MapCanvas canvas, Player player) {
// if (isDirty(player)) {
// BufferedImage img = renderImage(player);
// canvas.drawImage(0, 0, img);
// setDirty(player, false);
// player.sendMap(map);
// }
// }
// }
//
// Path: src/main/java/me/desht/scrollingmenusign/views/SMSView.java
// public class MenuStack {
// final Deque<WeakReference<SMSMenu>> stack;
//
// public MenuStack() {
// stack = new ArrayDeque<WeakReference<SMSMenu>>();
// }
//
// public void pushMenu(SMSMenu menu) {
// stack.push(new WeakReference<SMSMenu>(menu));
// }
//
// public SMSMenu popMenu() {
// return stack.pop().get();
// }
//
// public SMSMenu peek() {
// return stack.peek().get();
// }
//
// public boolean isEmpty() {
// return stack.isEmpty();
// }
// }
//
// Path: src/main/java/me/desht/scrollingmenusign/views/action/RepaintAction.java
// public class RepaintAction extends ViewUpdateAction {
// public RepaintAction() {
// super();
// }
//
// public RepaintAction(CommandSender sender) {
// super(sender);
// }
// }
// Path: src/main/java/me/desht/scrollingmenusign/views/ViewManager.java
import me.desht.dhutils.Debugger;
import me.desht.dhutils.LogUtils;
import me.desht.dhutils.block.BlockUtil;
import me.desht.scrollingmenusign.*;
import me.desht.scrollingmenusign.views.SMSMapView.SMSMapRenderer;
import me.desht.scrollingmenusign.views.SMSView.MenuStack;
import me.desht.scrollingmenusign.views.action.RepaintAction;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.map.MapRenderer;
import org.bukkit.map.MapView;
import org.bukkit.util.Vector;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.Map.Entry;
* @param loc Location of the new view
* @return The newly-created view
* @throws SMSException if the given location is not a suitable location for the new view
*/
public SMSView addPublicHoloViewToMenu(String viewName, SMSMenu menu, Location loc, CommandSender owner) {
SMSView view = new SMSPublicHoloView(viewName, menu, loc);
initialiseView(view, owner);
return view;
}
/**
* Convenience method. Create and register a new SMSPrivateHoloView object, and attach it to
* the given menu.
*
* @param viewName Name for the view; if null a name will be auto-generated
* @param menu The menu to attach the new view to
* @return The newly-created view
* @throws SMSException if the given location is not a suitable location for the new view
*/
public SMSView addPrivateHoloToView(String viewName, SMSMenu menu, CommandSender owner) {
SMSView view = new SMSPrivateHoloView(viewName, menu);
initialiseView(view, owner);
return view;
}
private void initialiseView(SMSView view, CommandSender owner) {
// common setup tasks for a new view
registerView(view);
view.setAttribute(SMSView.OWNER, view.makeOwnerName(owner));
view.setOwnerId(getUniqueId(owner)); | view.update(view.getNativeMenu(), new RepaintAction()); |
desht/ScrollingMenuSign | src/main/java/me/desht/scrollingmenusign/views/SMSMapView.java | // Path: src/main/java/me/desht/scrollingmenusign/enums/ViewJustification.java
// public enum ViewJustification {
// LEFT, RIGHT, CENTER, DEFAULT
// }
//
// Path: src/main/java/me/desht/scrollingmenusign/views/action/ViewUpdateAction.java
// public abstract class ViewUpdateAction {
// // private final SMSMenuAction action;
// private final CommandSender sender;
//
// public ViewUpdateAction(CommandSender sender) {
// // this.action = action;
// this.sender = sender;
// }
//
// public ViewUpdateAction() {
// // this.action = action;
// this.sender = null;
// }
// //
// // public SMSMenuAction getAction() {
// // return action;
// // }
//
// public CommandSender getSender() {
// return sender;
// }
//
// public static ViewUpdateAction getAction(Object o) {
// if (o instanceof SMSMenuAction) {
// switch ((SMSMenuAction) o) {
// // return new ViewUpdateAction((SMSMenuAction) o, null);
// case SCROLLED: return new ScrollAction(null, ScrollAction.ScrollDirection.UNKNOWN);
// case REPAINT: return new RepaintAction();
// default: return null;
// }
// } else if (o instanceof ViewUpdateAction) {
// return (ViewUpdateAction) o;
// } else {
// throw new IllegalArgumentException("Expecting a ViewUpdateAction or SMSMenuAction object");
// }
// }
// }
| import me.desht.dhutils.ConfigurationManager;
import me.desht.dhutils.LogUtils;
import me.desht.dhutils.MapUtil;
import me.desht.dhutils.PermissionUtils;
import me.desht.scrollingmenusign.*;
import me.desht.scrollingmenusign.enums.ViewJustification;
import me.desht.scrollingmenusign.views.action.ViewUpdateAction;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.configuration.Configuration;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.map.MapCanvas;
import org.bukkit.map.MapPalette;
import org.bukkit.map.MapRenderer;
import org.bukkit.map.MapView;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Observable; | lore.add(loreStr);
ItemMeta im = item.getItemMeta();
im.setDisplayName(ChatColor.RESET + doVariableSubstitutions(null, getNativeMenu().getTitle()));
im.setLore(lore);
item.setItemMeta(im);
}
/**
* Remove any custom item name & lore from the given item.
*
* @param item the map item
*/
public void removeMapItemName(ItemStack item) {
if (item.getType() != Material.MAP || getMapView().getId() != item.getDurability()) {
LogUtils.warning("SMSMapView: Attempt to remove item name from non map-view item!");
return;
}
ItemMeta im = item.getItemMeta();
im.setDisplayName(null);
im.setLore(null);
item.setItemMeta(im);
}
/* (non-Javadoc)
* @see me.desht.scrollingmenusign.views.SMSScrollableView#update(java.util.Observable, java.lang.Object)
*/
@Override
public void update(Observable menu, Object arg1) {
super.update(menu, arg1);
| // Path: src/main/java/me/desht/scrollingmenusign/enums/ViewJustification.java
// public enum ViewJustification {
// LEFT, RIGHT, CENTER, DEFAULT
// }
//
// Path: src/main/java/me/desht/scrollingmenusign/views/action/ViewUpdateAction.java
// public abstract class ViewUpdateAction {
// // private final SMSMenuAction action;
// private final CommandSender sender;
//
// public ViewUpdateAction(CommandSender sender) {
// // this.action = action;
// this.sender = sender;
// }
//
// public ViewUpdateAction() {
// // this.action = action;
// this.sender = null;
// }
// //
// // public SMSMenuAction getAction() {
// // return action;
// // }
//
// public CommandSender getSender() {
// return sender;
// }
//
// public static ViewUpdateAction getAction(Object o) {
// if (o instanceof SMSMenuAction) {
// switch ((SMSMenuAction) o) {
// // return new ViewUpdateAction((SMSMenuAction) o, null);
// case SCROLLED: return new ScrollAction(null, ScrollAction.ScrollDirection.UNKNOWN);
// case REPAINT: return new RepaintAction();
// default: return null;
// }
// } else if (o instanceof ViewUpdateAction) {
// return (ViewUpdateAction) o;
// } else {
// throw new IllegalArgumentException("Expecting a ViewUpdateAction or SMSMenuAction object");
// }
// }
// }
// Path: src/main/java/me/desht/scrollingmenusign/views/SMSMapView.java
import me.desht.dhutils.ConfigurationManager;
import me.desht.dhutils.LogUtils;
import me.desht.dhutils.MapUtil;
import me.desht.dhutils.PermissionUtils;
import me.desht.scrollingmenusign.*;
import me.desht.scrollingmenusign.enums.ViewJustification;
import me.desht.scrollingmenusign.views.action.ViewUpdateAction;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.configuration.Configuration;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.map.MapCanvas;
import org.bukkit.map.MapPalette;
import org.bukkit.map.MapRenderer;
import org.bukkit.map.MapView;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Observable;
lore.add(loreStr);
ItemMeta im = item.getItemMeta();
im.setDisplayName(ChatColor.RESET + doVariableSubstitutions(null, getNativeMenu().getTitle()));
im.setLore(lore);
item.setItemMeta(im);
}
/**
* Remove any custom item name & lore from the given item.
*
* @param item the map item
*/
public void removeMapItemName(ItemStack item) {
if (item.getType() != Material.MAP || getMapView().getId() != item.getDurability()) {
LogUtils.warning("SMSMapView: Attempt to remove item name from non map-view item!");
return;
}
ItemMeta im = item.getItemMeta();
im.setDisplayName(null);
im.setLore(null);
item.setItemMeta(im);
}
/* (non-Javadoc)
* @see me.desht.scrollingmenusign.views.SMSScrollableView#update(java.util.Observable, java.lang.Object)
*/
@Override
public void update(Observable menu, Object arg1) {
super.update(menu, arg1);
| ViewUpdateAction vu = ViewUpdateAction.getAction(arg1); |
desht/ScrollingMenuSign | src/main/java/me/desht/scrollingmenusign/views/SMSMapView.java | // Path: src/main/java/me/desht/scrollingmenusign/enums/ViewJustification.java
// public enum ViewJustification {
// LEFT, RIGHT, CENTER, DEFAULT
// }
//
// Path: src/main/java/me/desht/scrollingmenusign/views/action/ViewUpdateAction.java
// public abstract class ViewUpdateAction {
// // private final SMSMenuAction action;
// private final CommandSender sender;
//
// public ViewUpdateAction(CommandSender sender) {
// // this.action = action;
// this.sender = sender;
// }
//
// public ViewUpdateAction() {
// // this.action = action;
// this.sender = null;
// }
// //
// // public SMSMenuAction getAction() {
// // return action;
// // }
//
// public CommandSender getSender() {
// return sender;
// }
//
// public static ViewUpdateAction getAction(Object o) {
// if (o instanceof SMSMenuAction) {
// switch ((SMSMenuAction) o) {
// // return new ViewUpdateAction((SMSMenuAction) o, null);
// case SCROLLED: return new ScrollAction(null, ScrollAction.ScrollDirection.UNKNOWN);
// case REPAINT: return new RepaintAction();
// default: return null;
// }
// } else if (o instanceof ViewUpdateAction) {
// return (ViewUpdateAction) o;
// } else {
// throw new IllegalArgumentException("Expecting a ViewUpdateAction or SMSMenuAction object");
// }
// }
// }
| import me.desht.dhutils.ConfigurationManager;
import me.desht.dhutils.LogUtils;
import me.desht.dhutils.MapUtil;
import me.desht.dhutils.PermissionUtils;
import me.desht.scrollingmenusign.*;
import me.desht.scrollingmenusign.enums.ViewJustification;
import me.desht.scrollingmenusign.views.action.ViewUpdateAction;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.configuration.Configuration;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.map.MapCanvas;
import org.bukkit.map.MapPalette;
import org.bukkit.map.MapRenderer;
import org.bukkit.map.MapView;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Observable; | Configuration config = ScrollingMenuSign.getInstance().getConfig();
if (!hasOwnerPermission(player) || !isTypeUsable(player)) {
BufferedImage di = getDeniedImage();
if (di != null) {
g.drawImage(di, 0, 0, null);
} else {
drawMessage(g, new String[]{"Access Denied"});
}
return result;
}
int lineHeight = metrics.getHeight() + getLineSpacing();
int yPos = getY() + lineHeight;
// draw the title line(s)
List<String> titleLines = splitTitle(player);
for (String line : titleLines) {
drawText(g, getTitleJustification(), yPos, line);
yPos += lineHeight;
}
Color c = g.getColor();
g.setColor(MapUtil.getChatColor(7));
yPos++;
int lineY = yPos + 1 - lineHeight;
g.drawLine(x, lineY, x + width, lineY);
g.setColor(c);
String prefixNotSel = ScrollingMenuSign.getInstance().getConfigCache().getPrefixNotSelected();
String prefixSel = ScrollingMenuSign.getInstance().getConfigCache().getPrefixSelected(); | // Path: src/main/java/me/desht/scrollingmenusign/enums/ViewJustification.java
// public enum ViewJustification {
// LEFT, RIGHT, CENTER, DEFAULT
// }
//
// Path: src/main/java/me/desht/scrollingmenusign/views/action/ViewUpdateAction.java
// public abstract class ViewUpdateAction {
// // private final SMSMenuAction action;
// private final CommandSender sender;
//
// public ViewUpdateAction(CommandSender sender) {
// // this.action = action;
// this.sender = sender;
// }
//
// public ViewUpdateAction() {
// // this.action = action;
// this.sender = null;
// }
// //
// // public SMSMenuAction getAction() {
// // return action;
// // }
//
// public CommandSender getSender() {
// return sender;
// }
//
// public static ViewUpdateAction getAction(Object o) {
// if (o instanceof SMSMenuAction) {
// switch ((SMSMenuAction) o) {
// // return new ViewUpdateAction((SMSMenuAction) o, null);
// case SCROLLED: return new ScrollAction(null, ScrollAction.ScrollDirection.UNKNOWN);
// case REPAINT: return new RepaintAction();
// default: return null;
// }
// } else if (o instanceof ViewUpdateAction) {
// return (ViewUpdateAction) o;
// } else {
// throw new IllegalArgumentException("Expecting a ViewUpdateAction or SMSMenuAction object");
// }
// }
// }
// Path: src/main/java/me/desht/scrollingmenusign/views/SMSMapView.java
import me.desht.dhutils.ConfigurationManager;
import me.desht.dhutils.LogUtils;
import me.desht.dhutils.MapUtil;
import me.desht.dhutils.PermissionUtils;
import me.desht.scrollingmenusign.*;
import me.desht.scrollingmenusign.enums.ViewJustification;
import me.desht.scrollingmenusign.views.action.ViewUpdateAction;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.configuration.Configuration;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.map.MapCanvas;
import org.bukkit.map.MapPalette;
import org.bukkit.map.MapRenderer;
import org.bukkit.map.MapView;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Observable;
Configuration config = ScrollingMenuSign.getInstance().getConfig();
if (!hasOwnerPermission(player) || !isTypeUsable(player)) {
BufferedImage di = getDeniedImage();
if (di != null) {
g.drawImage(di, 0, 0, null);
} else {
drawMessage(g, new String[]{"Access Denied"});
}
return result;
}
int lineHeight = metrics.getHeight() + getLineSpacing();
int yPos = getY() + lineHeight;
// draw the title line(s)
List<String> titleLines = splitTitle(player);
for (String line : titleLines) {
drawText(g, getTitleJustification(), yPos, line);
yPos += lineHeight;
}
Color c = g.getColor();
g.setColor(MapUtil.getChatColor(7));
yPos++;
int lineY = yPos + 1 - lineHeight;
g.drawLine(x, lineY, x + width, lineY);
g.setColor(c);
String prefixNotSel = ScrollingMenuSign.getInstance().getConfigCache().getPrefixNotSelected();
String prefixSel = ScrollingMenuSign.getInstance().getConfigCache().getPrefixSelected(); | ViewJustification itemJust = getItemJustification(); |
desht/ScrollingMenuSign | src/main/java/me/desht/scrollingmenusign/ConfigCache.java | // Path: src/main/java/me/desht/scrollingmenusign/util/SMSUtil.java
// public class SMSUtil {
// public static String escape(String s) {
// return StringEscapeUtils.escapeHtml(MiscUtil.unParseColourSpec(s));
// }
//
// public static String unEscape(String s) {
// return MiscUtil.parseColourSpec(StringEscapeUtils.unescapeHtml(s));
// }
//
// /**
// * Given a string specification, try to get an ItemStack.
// * <p>
// * The spec. is of the form "material-name[:data-byte][,amount][,glow]" where
// * material-name is a valid Bukkit material name as understoood by
// * {@link Material#matchMaterial(String)}, data-byte is a numeric byte value,
// * amount is an optional item quantity, and "glow" if present indicates that
// * the item should glow if possible.
// * <p>
// * No item metadata is considered by this method.
// *
// * @param spec the specification
// * @return the return ItemStack
// * @throws SMSException if the specification is invalid
// */
// public static ItemStack parseMaterialSpec(String spec) {
// if (spec == null || spec.isEmpty()) {
// return null;
// }
//
// String[] fields = spec.split(",");
// MaterialData mat = parseMatAndData(fields[0]);
//
// int amount = 1;
// boolean glowing = false;
// for (int i = 1; i < fields.length; i++) {
// if (StringUtils.isNumeric(fields[i])) {
// amount = Integer.parseInt(fields[i]);
// } else if (fields[i].equalsIgnoreCase("glow")) {
// glowing = true;
// }
// }
// ItemStack stack = mat.toItemStack(amount);
// if (glowing && ScrollingMenuSign.getInstance().isProtocolLibEnabled()) {
// ItemGlow.setGlowing(stack, true);
// }
// return stack;
// }
//
// private static MaterialData parseMatAndData(String matData) {
// String[] fields = matData.split("[:()]");
// Material mat = Material.matchMaterial(fields[0]);
// if (mat == null) {
// throw new SMSException("Unknown material " + fields[0]);
// }
// MaterialData res = new MaterialData(mat);
// if (fields.length > 1) {
// if (StringUtils.isNumeric(fields[1])) {
// res.setData(Byte.parseByte(fields[1]));
// } else {
// switch (mat) {
// case INK_SACK:
// Dye dye = new Dye();
// dye.setColor(DyeColor.valueOf(fields[1].toUpperCase()));
// res = dye;
// break;
// case WOOL:
// case CARPET:
// case STAINED_GLASS:
// case STAINED_GLASS_PANE:
// case STAINED_CLAY:
// // maybe one day these will all implement Colorable...
// DyeColor dc2 = DyeColor.valueOf(fields[1].toUpperCase());
// res.setData(dc2.getWoolData());
// break;
// case SAPLING:
// case WOOD:
// TreeSpecies ts = TreeSpecies.valueOf(fields[1].toUpperCase());
// res.setData(ts.getData());
// break;
// }
// }
// }
// return res;
// }
//
// /**
// * Given an ItemStack, freeze it into a parseable form.
// * <p>
// * The returned String is guaranteed to parseable by {@link #parseMaterialSpec(String)}
// * <p>
// * No item metadata is frozen.
// *
// * @param stack the ItemStack to freeze
// * @return a String representing the ItemStack
// */
// public static String freezeMaterialSpec(ItemStack stack) {
// MaterialData m = stack.getData();
// StringBuilder sb = new StringBuilder(m.getItemType().toString());
// if (stack.getDurability() != 0) {
// sb.append(":").append(stack.getDurability());
// }
// if (stack.getAmount() > 1) {
// sb.append(",").append(Integer.toString(stack.getAmount()));
// }
// if (ScrollingMenuSign.getInstance().isProtocolLibEnabled() && ItemGlow.hasGlow(stack)) {
// sb.append(",").append("glow");
// }
// return sb.toString();
// }
//
// public static String formatMoney(double amount) {
// try {
// return ScrollingMenuSign.economy.format(amount);
// } catch (Exception e) {
// LogUtils.warning("Caught exception from " + ScrollingMenuSign.economy.getName() + " while trying to format quantity " + amount + ":");
// e.printStackTrace();
// LogUtils.warning("ScrollingMenuSign will continue but you should verify your economy plugin configuration.");
// }
// return new DecimalFormat("#0.00").format(amount) + " ";
// }
// }
| import me.desht.scrollingmenusign.util.SMSUtil;
import org.bukkit.configuration.Configuration;
import org.bukkit.inventory.ItemStack;
import java.util.regex.Matcher; | package me.desht.scrollingmenusign;
/**
* Cache some config values which are accessed very frequently, to reduce
* lookup/parsing overheads.
*/
public class ConfigCache {
private String prefixSelected;
private String prefixNotSelected;
private boolean physicsProtected;
private boolean breakProtected;
private String submenuBackLabel;
private ItemStack submenuBackIcon;
private String submenuTitlePrefix;
private ItemStack defaultInventoryViewIcon;
private String fallbackUserVarSub;
public void processConfig(Configuration conf) {
setPrefixSelected(conf.getString("sms.item_prefix.selected"));
setPrefixNotSelected(conf.getString("sms.item_prefix.not_selected"));
setPhysicsProtected(conf.getBoolean("sms.no_physics"));
setBreakProtected(conf.getBoolean("sms.no_destroy_signs"));
setSubmenuBackLabel(conf.getString("sms.submenus.back_item.label"));
setSubmenuBackIcon(conf.getString("sms.submenus.back_item.material"));
setSubmenuTitlePrefix(conf.getString("sms.submenus.title_prefix"));
setDefaultInventoryViewIcon(conf.getString("sms.inv_view.default_icon"));
setFallbackUserVarSub(conf.getString("sms.user_variables.fallback_sub"));
}
public String getPrefixSelected() {
return prefixSelected;
}
public void setPrefixSelected(String prefixSelected) { | // Path: src/main/java/me/desht/scrollingmenusign/util/SMSUtil.java
// public class SMSUtil {
// public static String escape(String s) {
// return StringEscapeUtils.escapeHtml(MiscUtil.unParseColourSpec(s));
// }
//
// public static String unEscape(String s) {
// return MiscUtil.parseColourSpec(StringEscapeUtils.unescapeHtml(s));
// }
//
// /**
// * Given a string specification, try to get an ItemStack.
// * <p>
// * The spec. is of the form "material-name[:data-byte][,amount][,glow]" where
// * material-name is a valid Bukkit material name as understoood by
// * {@link Material#matchMaterial(String)}, data-byte is a numeric byte value,
// * amount is an optional item quantity, and "glow" if present indicates that
// * the item should glow if possible.
// * <p>
// * No item metadata is considered by this method.
// *
// * @param spec the specification
// * @return the return ItemStack
// * @throws SMSException if the specification is invalid
// */
// public static ItemStack parseMaterialSpec(String spec) {
// if (spec == null || spec.isEmpty()) {
// return null;
// }
//
// String[] fields = spec.split(",");
// MaterialData mat = parseMatAndData(fields[0]);
//
// int amount = 1;
// boolean glowing = false;
// for (int i = 1; i < fields.length; i++) {
// if (StringUtils.isNumeric(fields[i])) {
// amount = Integer.parseInt(fields[i]);
// } else if (fields[i].equalsIgnoreCase("glow")) {
// glowing = true;
// }
// }
// ItemStack stack = mat.toItemStack(amount);
// if (glowing && ScrollingMenuSign.getInstance().isProtocolLibEnabled()) {
// ItemGlow.setGlowing(stack, true);
// }
// return stack;
// }
//
// private static MaterialData parseMatAndData(String matData) {
// String[] fields = matData.split("[:()]");
// Material mat = Material.matchMaterial(fields[0]);
// if (mat == null) {
// throw new SMSException("Unknown material " + fields[0]);
// }
// MaterialData res = new MaterialData(mat);
// if (fields.length > 1) {
// if (StringUtils.isNumeric(fields[1])) {
// res.setData(Byte.parseByte(fields[1]));
// } else {
// switch (mat) {
// case INK_SACK:
// Dye dye = new Dye();
// dye.setColor(DyeColor.valueOf(fields[1].toUpperCase()));
// res = dye;
// break;
// case WOOL:
// case CARPET:
// case STAINED_GLASS:
// case STAINED_GLASS_PANE:
// case STAINED_CLAY:
// // maybe one day these will all implement Colorable...
// DyeColor dc2 = DyeColor.valueOf(fields[1].toUpperCase());
// res.setData(dc2.getWoolData());
// break;
// case SAPLING:
// case WOOD:
// TreeSpecies ts = TreeSpecies.valueOf(fields[1].toUpperCase());
// res.setData(ts.getData());
// break;
// }
// }
// }
// return res;
// }
//
// /**
// * Given an ItemStack, freeze it into a parseable form.
// * <p>
// * The returned String is guaranteed to parseable by {@link #parseMaterialSpec(String)}
// * <p>
// * No item metadata is frozen.
// *
// * @param stack the ItemStack to freeze
// * @return a String representing the ItemStack
// */
// public static String freezeMaterialSpec(ItemStack stack) {
// MaterialData m = stack.getData();
// StringBuilder sb = new StringBuilder(m.getItemType().toString());
// if (stack.getDurability() != 0) {
// sb.append(":").append(stack.getDurability());
// }
// if (stack.getAmount() > 1) {
// sb.append(",").append(Integer.toString(stack.getAmount()));
// }
// if (ScrollingMenuSign.getInstance().isProtocolLibEnabled() && ItemGlow.hasGlow(stack)) {
// sb.append(",").append("glow");
// }
// return sb.toString();
// }
//
// public static String formatMoney(double amount) {
// try {
// return ScrollingMenuSign.economy.format(amount);
// } catch (Exception e) {
// LogUtils.warning("Caught exception from " + ScrollingMenuSign.economy.getName() + " while trying to format quantity " + amount + ":");
// e.printStackTrace();
// LogUtils.warning("ScrollingMenuSign will continue but you should verify your economy plugin configuration.");
// }
// return new DecimalFormat("#0.00").format(amount) + " ";
// }
// }
// Path: src/main/java/me/desht/scrollingmenusign/ConfigCache.java
import me.desht.scrollingmenusign.util.SMSUtil;
import org.bukkit.configuration.Configuration;
import org.bukkit.inventory.ItemStack;
import java.util.regex.Matcher;
package me.desht.scrollingmenusign;
/**
* Cache some config values which are accessed very frequently, to reduce
* lookup/parsing overheads.
*/
public class ConfigCache {
private String prefixSelected;
private String prefixNotSelected;
private boolean physicsProtected;
private boolean breakProtected;
private String submenuBackLabel;
private ItemStack submenuBackIcon;
private String submenuTitlePrefix;
private ItemStack defaultInventoryViewIcon;
private String fallbackUserVarSub;
public void processConfig(Configuration conf) {
setPrefixSelected(conf.getString("sms.item_prefix.selected"));
setPrefixNotSelected(conf.getString("sms.item_prefix.not_selected"));
setPhysicsProtected(conf.getBoolean("sms.no_physics"));
setBreakProtected(conf.getBoolean("sms.no_destroy_signs"));
setSubmenuBackLabel(conf.getString("sms.submenus.back_item.label"));
setSubmenuBackIcon(conf.getString("sms.submenus.back_item.material"));
setSubmenuTitlePrefix(conf.getString("sms.submenus.title_prefix"));
setDefaultInventoryViewIcon(conf.getString("sms.inv_view.default_icon"));
setFallbackUserVarSub(conf.getString("sms.user_variables.fallback_sub"));
}
public String getPrefixSelected() {
return prefixSelected;
}
public void setPrefixSelected(String prefixSelected) { | this.prefixSelected = SMSUtil.unEscape(prefixSelected.replace("%", "%%")); |
BoD/irondad | src/main/java/org/jraf/irondad/protocol/Connection.java | // Path: src/main/java/org/jraf/irondad/Constants.java
// public class Constants {
// public static final String TAG = "irondad/";
//
// public static final String PROJECT_FULL_NAME = "BoD irondad";
// public static final String PROJECT_URL = "https://github.com/BoD/irondad";
// public static final String VERSION_NAME = "v1.11.1"; // xxx When updating this, don't forget to update the version in pom.xml as well
// }
//
// Path: src/main/java/org/jraf/irondad/util/Log.java
// public class Log {
// public static void w(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " W " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void w(String tag, String msg) {
// System.out.print(getDate() + " W " + tag + " " + msg + "\n");
// }
//
// public static void e(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " E " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void e(String tag, String msg) {
// System.out.print(getDate() + " E " + tag + " " + msg + "\n");
// }
//
// public static void d(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " D " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void d(String tag, String msg) {
// System.out.print(getDate() + " D " + tag + " " + msg + "\n");
// }
//
// public static void i(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " I " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void i(String tag, String msg) {
// System.out.print(getDate() + " I " + tag + " " + msg + "\n");
// }
//
// private static String getDate() {
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd/HH:mm:ss");
// return sdf.format(new Date());
// }
//
// private static String getStackTraceString(Throwable tr) {
// if (tr == null) {
// return "";
// }
//
// StringWriter sw = new StringWriter();
// PrintWriter pw = new PrintWriter(sw);
// tr.printStackTrace(pw);
// return sw.toString();
// }
// }
| import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.jraf.irondad.Constants;
import org.jraf.irondad.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket; | /*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2013 Benoit 'BoD' Lubek (BoD@JRAF.org)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see
* <http://www.gnu.org/licenses/>.
*/
package org.jraf.irondad.protocol;
public class Connection {
private static final String TAG = Constants.TAG + Connection.class.getSimpleName();
private static final String CR_LF = "\r\n";
private Client mClient;
private final BufferedReader mBufferedReader;
private final OutputStream mOutputStream;
public Connection(Client client, Socket socket) throws IOException {
mClient = client;
mBufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
mOutputStream = socket.getOutputStream();
}
public void send(String line) throws IOException { | // Path: src/main/java/org/jraf/irondad/Constants.java
// public class Constants {
// public static final String TAG = "irondad/";
//
// public static final String PROJECT_FULL_NAME = "BoD irondad";
// public static final String PROJECT_URL = "https://github.com/BoD/irondad";
// public static final String VERSION_NAME = "v1.11.1"; // xxx When updating this, don't forget to update the version in pom.xml as well
// }
//
// Path: src/main/java/org/jraf/irondad/util/Log.java
// public class Log {
// public static void w(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " W " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void w(String tag, String msg) {
// System.out.print(getDate() + " W " + tag + " " + msg + "\n");
// }
//
// public static void e(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " E " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void e(String tag, String msg) {
// System.out.print(getDate() + " E " + tag + " " + msg + "\n");
// }
//
// public static void d(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " D " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void d(String tag, String msg) {
// System.out.print(getDate() + " D " + tag + " " + msg + "\n");
// }
//
// public static void i(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " I " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void i(String tag, String msg) {
// System.out.print(getDate() + " I " + tag + " " + msg + "\n");
// }
//
// private static String getDate() {
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd/HH:mm:ss");
// return sdf.format(new Date());
// }
//
// private static String getStackTraceString(Throwable tr) {
// if (tr == null) {
// return "";
// }
//
// StringWriter sw = new StringWriter();
// PrintWriter pw = new PrintWriter(sw);
// tr.printStackTrace(pw);
// return sw.toString();
// }
// }
// Path: src/main/java/org/jraf/irondad/protocol/Connection.java
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.jraf.irondad.Constants;
import org.jraf.irondad.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
/*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2013 Benoit 'BoD' Lubek (BoD@JRAF.org)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see
* <http://www.gnu.org/licenses/>.
*/
package org.jraf.irondad.protocol;
public class Connection {
private static final String TAG = Constants.TAG + Connection.class.getSimpleName();
private static final String CR_LF = "\r\n";
private Client mClient;
private final BufferedReader mBufferedReader;
private final OutputStream mOutputStream;
public Connection(Client client, Socket socket) throws IOException {
mClient = client;
mBufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
mOutputStream = socket.getOutputStream();
}
public void send(String line) throws IOException { | Log.d(TAG, "SND " + line); |
BoD/irondad | src/main/java/org/jraf/irondad/handler/quote/DbManager.java | // Path: src/main/java/org/jraf/irondad/Config.java
// public class Config {
//
// public static final boolean LOGD = true;
//
// }
//
// Path: src/main/java/org/jraf/irondad/Constants.java
// public class Constants {
// public static final String TAG = "irondad/";
//
// public static final String PROJECT_FULL_NAME = "BoD irondad";
// public static final String PROJECT_URL = "https://github.com/BoD/irondad";
// public static final String VERSION_NAME = "v1.11.1"; // xxx When updating this, don't forget to update the version in pom.xml as well
// }
//
// Path: src/main/java/org/jraf/irondad/util/Log.java
// public class Log {
// public static void w(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " W " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void w(String tag, String msg) {
// System.out.print(getDate() + " W " + tag + " " + msg + "\n");
// }
//
// public static void e(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " E " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void e(String tag, String msg) {
// System.out.print(getDate() + " E " + tag + " " + msg + "\n");
// }
//
// public static void d(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " D " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void d(String tag, String msg) {
// System.out.print(getDate() + " D " + tag + " " + msg + "\n");
// }
//
// public static void i(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " I " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void i(String tag, String msg) {
// System.out.print(getDate() + " I " + tag + " " + msg + "\n");
// }
//
// private static String getDate() {
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd/HH:mm:ss");
// return sdf.format(new Date());
// }
//
// private static String getStackTraceString(Throwable tr) {
// if (tr == null) {
// return "";
// }
//
// StringWriter sw = new StringWriter();
// PrintWriter pw = new PrintWriter(sw);
// tr.printStackTrace(pw);
// return sw.toString();
// }
// }
| import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.Random;
import org.jraf.irondad.Config;
import org.jraf.irondad.Constants;
import org.jraf.irondad.util.Log;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet; | /*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2013 Benoit 'BoD' Lubek (BoD@JRAF.org)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see
* <http://www.gnu.org/licenses/>.
*/
package org.jraf.irondad.handler.quote;
public class DbManager {
private static final Random RANDOM = new Random();
| // Path: src/main/java/org/jraf/irondad/Config.java
// public class Config {
//
// public static final boolean LOGD = true;
//
// }
//
// Path: src/main/java/org/jraf/irondad/Constants.java
// public class Constants {
// public static final String TAG = "irondad/";
//
// public static final String PROJECT_FULL_NAME = "BoD irondad";
// public static final String PROJECT_URL = "https://github.com/BoD/irondad";
// public static final String VERSION_NAME = "v1.11.1"; // xxx When updating this, don't forget to update the version in pom.xml as well
// }
//
// Path: src/main/java/org/jraf/irondad/util/Log.java
// public class Log {
// public static void w(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " W " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void w(String tag, String msg) {
// System.out.print(getDate() + " W " + tag + " " + msg + "\n");
// }
//
// public static void e(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " E " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void e(String tag, String msg) {
// System.out.print(getDate() + " E " + tag + " " + msg + "\n");
// }
//
// public static void d(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " D " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void d(String tag, String msg) {
// System.out.print(getDate() + " D " + tag + " " + msg + "\n");
// }
//
// public static void i(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " I " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void i(String tag, String msg) {
// System.out.print(getDate() + " I " + tag + " " + msg + "\n");
// }
//
// private static String getDate() {
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd/HH:mm:ss");
// return sdf.format(new Date());
// }
//
// private static String getStackTraceString(Throwable tr) {
// if (tr == null) {
// return "";
// }
//
// StringWriter sw = new StringWriter();
// PrintWriter pw = new PrintWriter(sw);
// tr.printStackTrace(pw);
// return sw.toString();
// }
// }
// Path: src/main/java/org/jraf/irondad/handler/quote/DbManager.java
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.Random;
import org.jraf.irondad.Config;
import org.jraf.irondad.Constants;
import org.jraf.irondad.util.Log;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2013 Benoit 'BoD' Lubek (BoD@JRAF.org)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see
* <http://www.gnu.org/licenses/>.
*/
package org.jraf.irondad.handler.quote;
public class DbManager {
private static final Random RANDOM = new Random();
| private static final String TAG = Constants.TAG + DbManager.class.getSimpleName(); |
BoD/irondad | src/main/java/org/jraf/irondad/handler/quote/DbManager.java | // Path: src/main/java/org/jraf/irondad/Config.java
// public class Config {
//
// public static final boolean LOGD = true;
//
// }
//
// Path: src/main/java/org/jraf/irondad/Constants.java
// public class Constants {
// public static final String TAG = "irondad/";
//
// public static final String PROJECT_FULL_NAME = "BoD irondad";
// public static final String PROJECT_URL = "https://github.com/BoD/irondad";
// public static final String VERSION_NAME = "v1.11.1"; // xxx When updating this, don't forget to update the version in pom.xml as well
// }
//
// Path: src/main/java/org/jraf/irondad/util/Log.java
// public class Log {
// public static void w(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " W " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void w(String tag, String msg) {
// System.out.print(getDate() + " W " + tag + " " + msg + "\n");
// }
//
// public static void e(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " E " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void e(String tag, String msg) {
// System.out.print(getDate() + " E " + tag + " " + msg + "\n");
// }
//
// public static void d(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " D " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void d(String tag, String msg) {
// System.out.print(getDate() + " D " + tag + " " + msg + "\n");
// }
//
// public static void i(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " I " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void i(String tag, String msg) {
// System.out.print(getDate() + " I " + tag + " " + msg + "\n");
// }
//
// private static String getDate() {
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd/HH:mm:ss");
// return sdf.format(new Date());
// }
//
// private static String getStackTraceString(Throwable tr) {
// if (tr == null) {
// return "";
// }
//
// StringWriter sw = new StringWriter();
// PrintWriter pw = new PrintWriter(sw);
// tr.printStackTrace(pw);
// return sw.toString();
// }
// }
| import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.Random;
import org.jraf.irondad.Config;
import org.jraf.irondad.Constants;
import org.jraf.irondad.util.Log;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet; | "quote" +
" WHERE " +
"channel=?";
private static final String SQL_CHECK_QUOTE_EXISTS = "SELECT " +
"count(_id)" +
" FROM " +
"quote" +
" WHERE " +
"channel=? and _text=?";
private static final String SQL_DELETE = "DELETE " +
" FROM " +
"quote" +
" WHERE " +
"_id=?";
//@formatter:on
public static final int ERR_SQL_PROBLEM = -1;
public static final int ERR_QUOTE_ALREADY_EXISTS = -2;
private Connection mConnection;
private ArrayList<Integer> mRandomOrder;
private int mRandomIdx;
public DbManager(String dbPath) {
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) { | // Path: src/main/java/org/jraf/irondad/Config.java
// public class Config {
//
// public static final boolean LOGD = true;
//
// }
//
// Path: src/main/java/org/jraf/irondad/Constants.java
// public class Constants {
// public static final String TAG = "irondad/";
//
// public static final String PROJECT_FULL_NAME = "BoD irondad";
// public static final String PROJECT_URL = "https://github.com/BoD/irondad";
// public static final String VERSION_NAME = "v1.11.1"; // xxx When updating this, don't forget to update the version in pom.xml as well
// }
//
// Path: src/main/java/org/jraf/irondad/util/Log.java
// public class Log {
// public static void w(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " W " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void w(String tag, String msg) {
// System.out.print(getDate() + " W " + tag + " " + msg + "\n");
// }
//
// public static void e(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " E " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void e(String tag, String msg) {
// System.out.print(getDate() + " E " + tag + " " + msg + "\n");
// }
//
// public static void d(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " D " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void d(String tag, String msg) {
// System.out.print(getDate() + " D " + tag + " " + msg + "\n");
// }
//
// public static void i(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " I " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void i(String tag, String msg) {
// System.out.print(getDate() + " I " + tag + " " + msg + "\n");
// }
//
// private static String getDate() {
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd/HH:mm:ss");
// return sdf.format(new Date());
// }
//
// private static String getStackTraceString(Throwable tr) {
// if (tr == null) {
// return "";
// }
//
// StringWriter sw = new StringWriter();
// PrintWriter pw = new PrintWriter(sw);
// tr.printStackTrace(pw);
// return sw.toString();
// }
// }
// Path: src/main/java/org/jraf/irondad/handler/quote/DbManager.java
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.Random;
import org.jraf.irondad.Config;
import org.jraf.irondad.Constants;
import org.jraf.irondad.util.Log;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
"quote" +
" WHERE " +
"channel=?";
private static final String SQL_CHECK_QUOTE_EXISTS = "SELECT " +
"count(_id)" +
" FROM " +
"quote" +
" WHERE " +
"channel=? and _text=?";
private static final String SQL_DELETE = "DELETE " +
" FROM " +
"quote" +
" WHERE " +
"_id=?";
//@formatter:on
public static final int ERR_SQL_PROBLEM = -1;
public static final int ERR_QUOTE_ALREADY_EXISTS = -2;
private Connection mConnection;
private ArrayList<Integer> mRandomOrder;
private int mRandomIdx;
public DbManager(String dbPath) {
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) { | Log.e(TAG, "DbManager Could not intialize jdbc driver", e); |
BoD/irondad | src/main/java/org/jraf/irondad/handler/quote/DbManager.java | // Path: src/main/java/org/jraf/irondad/Config.java
// public class Config {
//
// public static final boolean LOGD = true;
//
// }
//
// Path: src/main/java/org/jraf/irondad/Constants.java
// public class Constants {
// public static final String TAG = "irondad/";
//
// public static final String PROJECT_FULL_NAME = "BoD irondad";
// public static final String PROJECT_URL = "https://github.com/BoD/irondad";
// public static final String VERSION_NAME = "v1.11.1"; // xxx When updating this, don't forget to update the version in pom.xml as well
// }
//
// Path: src/main/java/org/jraf/irondad/util/Log.java
// public class Log {
// public static void w(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " W " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void w(String tag, String msg) {
// System.out.print(getDate() + " W " + tag + " " + msg + "\n");
// }
//
// public static void e(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " E " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void e(String tag, String msg) {
// System.out.print(getDate() + " E " + tag + " " + msg + "\n");
// }
//
// public static void d(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " D " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void d(String tag, String msg) {
// System.out.print(getDate() + " D " + tag + " " + msg + "\n");
// }
//
// public static void i(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " I " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void i(String tag, String msg) {
// System.out.print(getDate() + " I " + tag + " " + msg + "\n");
// }
//
// private static String getDate() {
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd/HH:mm:ss");
// return sdf.format(new Date());
// }
//
// private static String getStackTraceString(Throwable tr) {
// if (tr == null) {
// return "";
// }
//
// StringWriter sw = new StringWriter();
// PrintWriter pw = new PrintWriter(sw);
// tr.printStackTrace(pw);
// return sw.toString();
// }
// }
| import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.Random;
import org.jraf.irondad.Config;
import org.jraf.irondad.Constants;
import org.jraf.irondad.util.Log;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet; | private static final String SQL_CHECK_QUOTE_EXISTS = "SELECT " +
"count(_id)" +
" FROM " +
"quote" +
" WHERE " +
"channel=? and _text=?";
private static final String SQL_DELETE = "DELETE " +
" FROM " +
"quote" +
" WHERE " +
"_id=?";
//@formatter:on
public static final int ERR_SQL_PROBLEM = -1;
public static final int ERR_QUOTE_ALREADY_EXISTS = -2;
private Connection mConnection;
private ArrayList<Integer> mRandomOrder;
private int mRandomIdx;
public DbManager(String dbPath) {
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
Log.e(TAG, "DbManager Could not intialize jdbc driver", e);
}
boolean dbExists = new File(dbPath).exists(); | // Path: src/main/java/org/jraf/irondad/Config.java
// public class Config {
//
// public static final boolean LOGD = true;
//
// }
//
// Path: src/main/java/org/jraf/irondad/Constants.java
// public class Constants {
// public static final String TAG = "irondad/";
//
// public static final String PROJECT_FULL_NAME = "BoD irondad";
// public static final String PROJECT_URL = "https://github.com/BoD/irondad";
// public static final String VERSION_NAME = "v1.11.1"; // xxx When updating this, don't forget to update the version in pom.xml as well
// }
//
// Path: src/main/java/org/jraf/irondad/util/Log.java
// public class Log {
// public static void w(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " W " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void w(String tag, String msg) {
// System.out.print(getDate() + " W " + tag + " " + msg + "\n");
// }
//
// public static void e(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " E " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void e(String tag, String msg) {
// System.out.print(getDate() + " E " + tag + " " + msg + "\n");
// }
//
// public static void d(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " D " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void d(String tag, String msg) {
// System.out.print(getDate() + " D " + tag + " " + msg + "\n");
// }
//
// public static void i(String tag, String msg, Throwable t) {
// System.out.print(getDate() + " I " + tag + " " + msg + "\n" + getStackTraceString(t));
// }
//
// public static void i(String tag, String msg) {
// System.out.print(getDate() + " I " + tag + " " + msg + "\n");
// }
//
// private static String getDate() {
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd/HH:mm:ss");
// return sdf.format(new Date());
// }
//
// private static String getStackTraceString(Throwable tr) {
// if (tr == null) {
// return "";
// }
//
// StringWriter sw = new StringWriter();
// PrintWriter pw = new PrintWriter(sw);
// tr.printStackTrace(pw);
// return sw.toString();
// }
// }
// Path: src/main/java/org/jraf/irondad/handler/quote/DbManager.java
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.Random;
import org.jraf.irondad.Config;
import org.jraf.irondad.Constants;
import org.jraf.irondad.util.Log;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
private static final String SQL_CHECK_QUOTE_EXISTS = "SELECT " +
"count(_id)" +
" FROM " +
"quote" +
" WHERE " +
"channel=? and _text=?";
private static final String SQL_DELETE = "DELETE " +
" FROM " +
"quote" +
" WHERE " +
"_id=?";
//@formatter:on
public static final int ERR_SQL_PROBLEM = -1;
public static final int ERR_QUOTE_ALREADY_EXISTS = -2;
private Connection mConnection;
private ArrayList<Integer> mRandomOrder;
private int mRandomIdx;
public DbManager(String dbPath) {
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
Log.e(TAG, "DbManager Could not intialize jdbc driver", e);
}
boolean dbExists = new File(dbPath).exists(); | if (Config.LOGD) Log.d(TAG, "DbManager dbExists=" + dbExists); |
BoD/irondad | src/main/java/org/jraf/irondad/handler/CommandHandler.java | // Path: src/main/java/org/jraf/irondad/protocol/Message.java
// public class Message {
// /**
// * Origin of the message (can be {@code null}).
// */
// public final Origin origin;
// public final Command command;
// public final ArrayList<String> parameters;
//
// public Message(Origin origin, Command command, ArrayList<String> parameters) {
// this.origin = origin;
// this.command = command;
// this.parameters = parameters;
// }
//
// public static Message parse(String line) {
// ArrayList<String> split = split(line);
// Origin origin = null;
// if (split.get(0).startsWith(":")) {
// // Prefix is an optional origin
// String originStr = split.remove(0);
// // Remove colon
// originStr = originStr.substring(1);
// origin = new Origin(originStr);
// }
// String commandStr = split.remove(0);
// Command command = Command.from(commandStr);
// return new Message(origin, command, split);
// }
//
//
//
// private static ArrayList<String> split(String line) {
// ArrayList<String> split = new ArrayList<String>(10);
// int len = line.length();
// StringBuilder currentToken = new StringBuilder(10);
// boolean previousCharIsSpace = false;
// boolean lastParam = false;
// for (int i = 0; i < len; i++) {
// char c = line.charAt(i);
// if (c == ' ' && !lastParam) {
// // Space
// split.add(currentToken.toString());
// currentToken = new StringBuilder(10);
// previousCharIsSpace = true;
// } else if (c == ':' && i != 0 && previousCharIsSpace) {
// // Colon: if at start of token, the remainder is the last param (can have spaces)
// lastParam = true;
// // currentToken.append(c);
// } else {
// // Other characters
// currentToken.append(c);
// previousCharIsSpace = false;
// }
// }
// split.add(currentToken.toString());
// return split;
// }
//
// @Override
// public String toString() {
// return "Message [origin=" + origin + ", command=" + command + ", parameters=" + parameters + "]";
// }
// }
| import java.util.List;
import java.util.Locale;
import org.jraf.irondad.protocol.Message; | /*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2013 Benoit 'BoD' Lubek (BoD@JRAF.org)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see
* <http://www.gnu.org/licenses/>.
*/
package org.jraf.irondad.handler;
public abstract class CommandHandler extends BaseHandler {
protected abstract String getCommand();
@Override | // Path: src/main/java/org/jraf/irondad/protocol/Message.java
// public class Message {
// /**
// * Origin of the message (can be {@code null}).
// */
// public final Origin origin;
// public final Command command;
// public final ArrayList<String> parameters;
//
// public Message(Origin origin, Command command, ArrayList<String> parameters) {
// this.origin = origin;
// this.command = command;
// this.parameters = parameters;
// }
//
// public static Message parse(String line) {
// ArrayList<String> split = split(line);
// Origin origin = null;
// if (split.get(0).startsWith(":")) {
// // Prefix is an optional origin
// String originStr = split.remove(0);
// // Remove colon
// originStr = originStr.substring(1);
// origin = new Origin(originStr);
// }
// String commandStr = split.remove(0);
// Command command = Command.from(commandStr);
// return new Message(origin, command, split);
// }
//
//
//
// private static ArrayList<String> split(String line) {
// ArrayList<String> split = new ArrayList<String>(10);
// int len = line.length();
// StringBuilder currentToken = new StringBuilder(10);
// boolean previousCharIsSpace = false;
// boolean lastParam = false;
// for (int i = 0; i < len; i++) {
// char c = line.charAt(i);
// if (c == ' ' && !lastParam) {
// // Space
// split.add(currentToken.toString());
// currentToken = new StringBuilder(10);
// previousCharIsSpace = true;
// } else if (c == ':' && i != 0 && previousCharIsSpace) {
// // Colon: if at start of token, the remainder is the last param (can have spaces)
// lastParam = true;
// // currentToken.append(c);
// } else {
// // Other characters
// currentToken.append(c);
// previousCharIsSpace = false;
// }
// }
// split.add(currentToken.toString());
// return split;
// }
//
// @Override
// public String toString() {
// return "Message [origin=" + origin + ", command=" + command + ", parameters=" + parameters + "]";
// }
// }
// Path: src/main/java/org/jraf/irondad/handler/CommandHandler.java
import java.util.List;
import java.util.Locale;
import org.jraf.irondad.protocol.Message;
/*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2013 Benoit 'BoD' Lubek (BoD@JRAF.org)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see
* <http://www.gnu.org/licenses/>.
*/
package org.jraf.irondad.handler;
public abstract class CommandHandler extends BaseHandler {
protected abstract String getCommand();
@Override | public boolean isMessageHandled(String channel, String fromNickname, String text, List<String> textAsList, Message message, HandlerContext handlerContext) { |
BoD/irondad | src/main/java/org/jraf/irondad/handler/HandlerContext.java | // Path: src/main/java/org/jraf/irondad/protocol/Connection.java
// public class Connection {
// private static final String TAG = Constants.TAG + Connection.class.getSimpleName();
// private static final String CR_LF = "\r\n";
//
// private Client mClient;
// private final BufferedReader mBufferedReader;
// private final OutputStream mOutputStream;
//
// public Connection(Client client, Socket socket) throws IOException {
// mClient = client;
// mBufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
// mOutputStream = socket.getOutputStream();
// }
//
// public void send(String line) throws IOException {
// Log.d(TAG, "SND " + line);
// mOutputStream.write((line + CR_LF).getBytes("utf-8"));
// }
//
// public void send(Command command, String... params) throws IOException {
// String[] paramsCopy = params.clone();
// if (paramsCopy.length > 0) {
// // Add a colon to the last param if it contains spaces
// if (paramsCopy[paramsCopy.length - 1].contains(" ")) {
// paramsCopy[paramsCopy.length - 1] = ":" + paramsCopy[paramsCopy.length - 1];
// }
// send(command.name() + " " + StringUtils.join(paramsCopy, " "));
// } else {
// send(command.name());
// }
// }
//
// public void send(Command command, List<String> params) throws IOException {
// String[] paramArray = params.toArray(new String[params.size()]);
// send(command, paramArray);
// }
//
// public String receiveLine() throws IOException {
// String line = mBufferedReader.readLine();
// Log.i(TAG, "RCV " + line);
// return line;
// }
//
// public Message receive() throws IOException {
// String line = receiveLine();
// if (line == null) return null;
// Message res = Message.parse(line);
// // if (Config.LOGD) Log.d(TAG, "receive res=" + res);
// return res;
// }
//
// public Client getClient() {
// return mClient;
// }
// }
| import java.util.HashMap;
import org.jraf.irondad.protocol.Connection; | /*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2013 Benoit 'BoD' Lubek (BoD@JRAF.org)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see
* <http://www.gnu.org/licenses/>.
*/
package org.jraf.irondad.handler;
public class HandlerContext extends HashMap<String, Object> {
private final HandlerConfig mHandlerConfig;
private final String mChannelName; | // Path: src/main/java/org/jraf/irondad/protocol/Connection.java
// public class Connection {
// private static final String TAG = Constants.TAG + Connection.class.getSimpleName();
// private static final String CR_LF = "\r\n";
//
// private Client mClient;
// private final BufferedReader mBufferedReader;
// private final OutputStream mOutputStream;
//
// public Connection(Client client, Socket socket) throws IOException {
// mClient = client;
// mBufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
// mOutputStream = socket.getOutputStream();
// }
//
// public void send(String line) throws IOException {
// Log.d(TAG, "SND " + line);
// mOutputStream.write((line + CR_LF).getBytes("utf-8"));
// }
//
// public void send(Command command, String... params) throws IOException {
// String[] paramsCopy = params.clone();
// if (paramsCopy.length > 0) {
// // Add a colon to the last param if it contains spaces
// if (paramsCopy[paramsCopy.length - 1].contains(" ")) {
// paramsCopy[paramsCopy.length - 1] = ":" + paramsCopy[paramsCopy.length - 1];
// }
// send(command.name() + " " + StringUtils.join(paramsCopy, " "));
// } else {
// send(command.name());
// }
// }
//
// public void send(Command command, List<String> params) throws IOException {
// String[] paramArray = params.toArray(new String[params.size()]);
// send(command, paramArray);
// }
//
// public String receiveLine() throws IOException {
// String line = mBufferedReader.readLine();
// Log.i(TAG, "RCV " + line);
// return line;
// }
//
// public Message receive() throws IOException {
// String line = receiveLine();
// if (line == null) return null;
// Message res = Message.parse(line);
// // if (Config.LOGD) Log.d(TAG, "receive res=" + res);
// return res;
// }
//
// public Client getClient() {
// return mClient;
// }
// }
// Path: src/main/java/org/jraf/irondad/handler/HandlerContext.java
import java.util.HashMap;
import org.jraf.irondad.protocol.Connection;
/*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2013 Benoit 'BoD' Lubek (BoD@JRAF.org)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see
* <http://www.gnu.org/licenses/>.
*/
package org.jraf.irondad.handler;
public class HandlerContext extends HashMap<String, Object> {
private final HandlerConfig mHandlerConfig;
private final String mChannelName; | private Connection mConnection; |
BoD/irondad | src/main/java/org/jraf/irondad/protocol/ClientConfig.java | // Path: src/main/java/org/jraf/irondad/handler/Handler.java
// public interface Handler {
// /**
// * Initialize this Handler.<br/>
// * This will be called only once.
// *
// * @param clientConfig The client config.
// */
// void init(ClientConfig clientConfig) throws Exception;
//
// /**
// * Initialize this Handler for the given context.<br/>
// * This will be called once per context.
// *
// * @param clientConfig The client config.
// */
// void init(HandlerContext handlerContext) throws Exception;
//
// /**
// * @param channel If not {@code null}, the channel on which the message was sent. If {@code null}, this call is a private message.
// */
// boolean isMessageHandled(String channel, String fromNickname, String text, List<String> textAsList, Message message, HandlerContext handlerContext);
//
// /**
// * @param channel If not {@code null}, the channel on which the message was sent. If {@code null}, this call is a private message.
// */
// void handleMessage(Connection connection, String channel, String fromNickname, String text, List<String> textAsList, Message message,
// HandlerContext handlerContext) throws Exception;
// }
//
// Path: src/main/java/org/jraf/irondad/handler/HandlerConfig.java
// public class HandlerConfig extends JSONObject {
//
// }
| import java.util.Set;
import org.jraf.irondad.handler.Handler;
import org.jraf.irondad.handler.HandlerConfig;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | /*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2013 Benoit 'BoD' Lubek (BoD@JRAF.org)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see
* <http://www.gnu.org/licenses/>.
*/
package org.jraf.irondad.protocol;
public class ClientConfig {
public static class HandlerClassAndConfig { | // Path: src/main/java/org/jraf/irondad/handler/Handler.java
// public interface Handler {
// /**
// * Initialize this Handler.<br/>
// * This will be called only once.
// *
// * @param clientConfig The client config.
// */
// void init(ClientConfig clientConfig) throws Exception;
//
// /**
// * Initialize this Handler for the given context.<br/>
// * This will be called once per context.
// *
// * @param clientConfig The client config.
// */
// void init(HandlerContext handlerContext) throws Exception;
//
// /**
// * @param channel If not {@code null}, the channel on which the message was sent. If {@code null}, this call is a private message.
// */
// boolean isMessageHandled(String channel, String fromNickname, String text, List<String> textAsList, Message message, HandlerContext handlerContext);
//
// /**
// * @param channel If not {@code null}, the channel on which the message was sent. If {@code null}, this call is a private message.
// */
// void handleMessage(Connection connection, String channel, String fromNickname, String text, List<String> textAsList, Message message,
// HandlerContext handlerContext) throws Exception;
// }
//
// Path: src/main/java/org/jraf/irondad/handler/HandlerConfig.java
// public class HandlerConfig extends JSONObject {
//
// }
// Path: src/main/java/org/jraf/irondad/protocol/ClientConfig.java
import java.util.Set;
import org.jraf.irondad.handler.Handler;
import org.jraf.irondad.handler.HandlerConfig;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2013 Benoit 'BoD' Lubek (BoD@JRAF.org)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see
* <http://www.gnu.org/licenses/>.
*/
package org.jraf.irondad.protocol;
public class ClientConfig {
public static class HandlerClassAndConfig { | public Class<? extends Handler> handlerClass; |
BoD/irondad | src/main/java/org/jraf/irondad/protocol/ClientConfig.java | // Path: src/main/java/org/jraf/irondad/handler/Handler.java
// public interface Handler {
// /**
// * Initialize this Handler.<br/>
// * This will be called only once.
// *
// * @param clientConfig The client config.
// */
// void init(ClientConfig clientConfig) throws Exception;
//
// /**
// * Initialize this Handler for the given context.<br/>
// * This will be called once per context.
// *
// * @param clientConfig The client config.
// */
// void init(HandlerContext handlerContext) throws Exception;
//
// /**
// * @param channel If not {@code null}, the channel on which the message was sent. If {@code null}, this call is a private message.
// */
// boolean isMessageHandled(String channel, String fromNickname, String text, List<String> textAsList, Message message, HandlerContext handlerContext);
//
// /**
// * @param channel If not {@code null}, the channel on which the message was sent. If {@code null}, this call is a private message.
// */
// void handleMessage(Connection connection, String channel, String fromNickname, String text, List<String> textAsList, Message message,
// HandlerContext handlerContext) throws Exception;
// }
//
// Path: src/main/java/org/jraf/irondad/handler/HandlerConfig.java
// public class HandlerConfig extends JSONObject {
//
// }
| import java.util.Set;
import org.jraf.irondad.handler.Handler;
import org.jraf.irondad.handler.HandlerConfig;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | /*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2013 Benoit 'BoD' Lubek (BoD@JRAF.org)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see
* <http://www.gnu.org/licenses/>.
*/
package org.jraf.irondad.protocol;
public class ClientConfig {
public static class HandlerClassAndConfig {
public Class<? extends Handler> handlerClass; | // Path: src/main/java/org/jraf/irondad/handler/Handler.java
// public interface Handler {
// /**
// * Initialize this Handler.<br/>
// * This will be called only once.
// *
// * @param clientConfig The client config.
// */
// void init(ClientConfig clientConfig) throws Exception;
//
// /**
// * Initialize this Handler for the given context.<br/>
// * This will be called once per context.
// *
// * @param clientConfig The client config.
// */
// void init(HandlerContext handlerContext) throws Exception;
//
// /**
// * @param channel If not {@code null}, the channel on which the message was sent. If {@code null}, this call is a private message.
// */
// boolean isMessageHandled(String channel, String fromNickname, String text, List<String> textAsList, Message message, HandlerContext handlerContext);
//
// /**
// * @param channel If not {@code null}, the channel on which the message was sent. If {@code null}, this call is a private message.
// */
// void handleMessage(Connection connection, String channel, String fromNickname, String text, List<String> textAsList, Message message,
// HandlerContext handlerContext) throws Exception;
// }
//
// Path: src/main/java/org/jraf/irondad/handler/HandlerConfig.java
// public class HandlerConfig extends JSONObject {
//
// }
// Path: src/main/java/org/jraf/irondad/protocol/ClientConfig.java
import java.util.Set;
import org.jraf.irondad.handler.Handler;
import org.jraf.irondad.handler.HandlerConfig;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2013 Benoit 'BoD' Lubek (BoD@JRAF.org)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see
* <http://www.gnu.org/licenses/>.
*/
package org.jraf.irondad.protocol;
public class ClientConfig {
public static class HandlerClassAndConfig {
public Class<? extends Handler> handlerClass; | public HandlerConfig handlerConfig; |
udacity/ud405 | 1.3.03-Demo-DrawingLines/android/src/com/udacity/gamedev/drawinglines/android/AndroidLauncher.java | // Path: 1.3.03-Demo-DrawingLines/core/src/com/udacity/gamedev/drawinglines/DrawingLines.java
// public class DrawingLines extends ApplicationAdapter {
//
// ShapeRenderer shapeRenderer;
//
// @Override
// public void create() {
// // Remember we want to create our ShapeRenderer outside of our render callback
// shapeRenderer = new ShapeRenderer();
// }
//
// @Override
// public void dispose() {
// // Also remember to clean up
// shapeRenderer.dispose();
// super.dispose();
// }
//
// @Override
// public void render() {
// // As always, first we clear the screen
// Gdx.gl.glClearColor(0, 0, 0, 1);
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// // Then we start our shapeRenderer batch, this time with ShapeType.Line
// shapeRenderer.begin(ShapeType.Line);
// // A Simple white line
// shapeRenderer.setColor(Color.WHITE);
// shapeRenderer.line(0, 0, 100, 100);
// // We can set different colors using two methods. We can use constants like so.
// shapeRenderer.setColor(Color.MAGENTA);
// shapeRenderer.line(10, 0, 110, 100);
// // We can also set a color using RGBA values
// shapeRenderer.setColor(0, 1, 0, 1);
// shapeRenderer.line(20, 0, 120, 100);
// // We can also do fancy things like gradients
// shapeRenderer.line(30, 0, 130, 100, Color.BLUE, Color.RED);
// // The last interesting thing we can do is draw a bunch of connected line segments using polyline
// // First we set up the list of vertices, where the even positions are x coordinates, and the odd positions are the y coordinates
// float[] verticies = {100, 200, 300, 300, 200, 300, 300, 200};
// shapeRenderer.polyline(verticies);
// // Finally, as always, we end the batch
// shapeRenderer.end();
// }
// }
| import android.os.Bundle;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.udacity.gamedev.drawinglines.DrawingLines; | package com.udacity.gamedev.drawinglines.android;
public class AndroidLauncher extends AndroidApplication {
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); | // Path: 1.3.03-Demo-DrawingLines/core/src/com/udacity/gamedev/drawinglines/DrawingLines.java
// public class DrawingLines extends ApplicationAdapter {
//
// ShapeRenderer shapeRenderer;
//
// @Override
// public void create() {
// // Remember we want to create our ShapeRenderer outside of our render callback
// shapeRenderer = new ShapeRenderer();
// }
//
// @Override
// public void dispose() {
// // Also remember to clean up
// shapeRenderer.dispose();
// super.dispose();
// }
//
// @Override
// public void render() {
// // As always, first we clear the screen
// Gdx.gl.glClearColor(0, 0, 0, 1);
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// // Then we start our shapeRenderer batch, this time with ShapeType.Line
// shapeRenderer.begin(ShapeType.Line);
// // A Simple white line
// shapeRenderer.setColor(Color.WHITE);
// shapeRenderer.line(0, 0, 100, 100);
// // We can set different colors using two methods. We can use constants like so.
// shapeRenderer.setColor(Color.MAGENTA);
// shapeRenderer.line(10, 0, 110, 100);
// // We can also set a color using RGBA values
// shapeRenderer.setColor(0, 1, 0, 1);
// shapeRenderer.line(20, 0, 120, 100);
// // We can also do fancy things like gradients
// shapeRenderer.line(30, 0, 130, 100, Color.BLUE, Color.RED);
// // The last interesting thing we can do is draw a bunch of connected line segments using polyline
// // First we set up the list of vertices, where the even positions are x coordinates, and the odd positions are the y coordinates
// float[] verticies = {100, 200, 300, 300, 200, 300, 300, 200};
// shapeRenderer.polyline(verticies);
// // Finally, as always, we end the batch
// shapeRenderer.end();
// }
// }
// Path: 1.3.03-Demo-DrawingLines/android/src/com/udacity/gamedev/drawinglines/android/AndroidLauncher.java
import android.os.Bundle;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.udacity.gamedev.drawinglines.DrawingLines;
package com.udacity.gamedev.drawinglines.android;
public class AndroidLauncher extends AndroidApplication {
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); | initialize(new DrawingLines(), config); |
udacity/ud405 | IciclesComplete/core/src/com/udacity/gamedev/icicles/DifficultyScreen.java | // Path: 1.8.04-Exercise-AddDifficultySelectScreen/core/src/com/udacity/gamedev/icicles/Constants.java
// public enum Difficulty {
// EASY(EASY_SPAWNS_PER_SECOND, EASY_LABEL),
// MEDIUM(MEDIUM_SPAWNS_PER_SECOND, MEDIUM_LABEL),
// HARD(HARD_SPAWNS_PER_SECOND, HARD_LABEL);
//
// float spawnRate;
// String label;
//
// Difficulty(float spawnRate, String label) {
// this.spawnRate = spawnRate;
// this.label = label;
// }
// }
| import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.badlogic.gdx.graphics.g2d.GlyphLayout;
import com.udacity.gamedev.icicles.Constants.Difficulty; | viewport.update(width, height, true);
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void hide() {
batch.dispose();
font.dispose();
renderer.dispose();
}
@Override
public void dispose() {
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
Vector2 worldTouch = viewport.unproject(new Vector2(screenX, screenY));
if (worldTouch.dst(Constants.EASY_CENTER) < Constants.DIFFICULTY_BUBBLE_RADIUS) { | // Path: 1.8.04-Exercise-AddDifficultySelectScreen/core/src/com/udacity/gamedev/icicles/Constants.java
// public enum Difficulty {
// EASY(EASY_SPAWNS_PER_SECOND, EASY_LABEL),
// MEDIUM(MEDIUM_SPAWNS_PER_SECOND, MEDIUM_LABEL),
// HARD(HARD_SPAWNS_PER_SECOND, HARD_LABEL);
//
// float spawnRate;
// String label;
//
// Difficulty(float spawnRate, String label) {
// this.spawnRate = spawnRate;
// this.label = label;
// }
// }
// Path: IciclesComplete/core/src/com/udacity/gamedev/icicles/DifficultyScreen.java
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.badlogic.gdx.graphics.g2d.GlyphLayout;
import com.udacity.gamedev.icicles.Constants.Difficulty;
viewport.update(width, height, true);
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void hide() {
batch.dispose();
font.dispose();
renderer.dispose();
}
@Override
public void dispose() {
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
Vector2 worldTouch = viewport.unproject(new Vector2(screenX, screenY));
if (worldTouch.dst(Constants.EASY_CENTER) < Constants.DIFFICULTY_BUBBLE_RADIUS) { | game.showIciclesScreen(Difficulty.EASY); |
udacity/ud405 | IciclesComplete/core/src/com/udacity/gamedev/icicles/IciclesScreen.java | // Path: 1.8.04-Exercise-AddDifficultySelectScreen/core/src/com/udacity/gamedev/icicles/Constants.java
// public enum Difficulty {
// EASY(EASY_SPAWNS_PER_SECOND, EASY_LABEL),
// MEDIUM(MEDIUM_SPAWNS_PER_SECOND, MEDIUM_LABEL),
// HARD(HARD_SPAWNS_PER_SECOND, HARD_LABEL);
//
// float spawnRate;
// String label;
//
// Difficulty(float spawnRate, String label) {
// this.spawnRate = spawnRate;
// this.label = label;
// }
// }
| import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.viewport.ExtendViewport;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
import com.udacity.gamedev.icicles.Constants.Difficulty; | package com.udacity.gamedev.icicles;
public class IciclesScreen extends InputAdapter implements Screen {
public static final String TAG = IciclesScreen.class.getName();
public static final Color BACKGROUND_COLOR = Color.BLUE;
IciclesGame game; | // Path: 1.8.04-Exercise-AddDifficultySelectScreen/core/src/com/udacity/gamedev/icicles/Constants.java
// public enum Difficulty {
// EASY(EASY_SPAWNS_PER_SECOND, EASY_LABEL),
// MEDIUM(MEDIUM_SPAWNS_PER_SECOND, MEDIUM_LABEL),
// HARD(HARD_SPAWNS_PER_SECOND, HARD_LABEL);
//
// float spawnRate;
// String label;
//
// Difficulty(float spawnRate, String label) {
// this.spawnRate = spawnRate;
// this.label = label;
// }
// }
// Path: IciclesComplete/core/src/com/udacity/gamedev/icicles/IciclesScreen.java
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.viewport.ExtendViewport;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
import com.udacity.gamedev.icicles.Constants.Difficulty;
package com.udacity.gamedev.icicles;
public class IciclesScreen extends InputAdapter implements Screen {
public static final String TAG = IciclesScreen.class.getName();
public static final Color BACKGROUND_COLOR = Color.BLUE;
IciclesGame game; | Difficulty difficulty; |
udacity/ud405 | 1.3.07-Solution-RectangularFlower/desktop/src/com/udacity/gamedev/rectangularflower/desktop/DesktopLauncher.java | // Path: 1.3.07-Exercise-RectangularFlower/core/src/com/udacity/gamedev/rectangularflower/RectangularFlower.java
// public class RectangularFlower extends ApplicationAdapter {
//
// ShapeRenderer shapeRenderer;
//
// @Override
// public void create () {
// shapeRenderer = new ShapeRenderer();
// }
//
// @Override
// public void dispose() {
// super.dispose();
// shapeRenderer.dispose();
// }
//
// @Override
// public void render () {
// Gdx.gl.glClearColor(0, 0, 0, 1);
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// shapeRenderer.begin(ShapeType.Filled);
// shapeRenderer.setColor(Color.GREEN);
// shapeRenderer.rectLine(100, 0, 100, 300, 20);
//
// // TODO: Draw two leaves on the stem
//
// // TODO: Set the active color to yellow
//
// // TODO: Use a loop to draw 20 of these petals in a circle
//
// float petalAngle = 45.0f;
// shapeRenderer.rect(100, 300, 0, 0, 40, 40, 1, 1, petalAngle);
//
// shapeRenderer.end();
// }
// }
| import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.udacity.gamedev.rectangularflower.RectangularFlower; | package com.udacity.gamedev.rectangularflower.desktop;
public class DesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); | // Path: 1.3.07-Exercise-RectangularFlower/core/src/com/udacity/gamedev/rectangularflower/RectangularFlower.java
// public class RectangularFlower extends ApplicationAdapter {
//
// ShapeRenderer shapeRenderer;
//
// @Override
// public void create () {
// shapeRenderer = new ShapeRenderer();
// }
//
// @Override
// public void dispose() {
// super.dispose();
// shapeRenderer.dispose();
// }
//
// @Override
// public void render () {
// Gdx.gl.glClearColor(0, 0, 0, 1);
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// shapeRenderer.begin(ShapeType.Filled);
// shapeRenderer.setColor(Color.GREEN);
// shapeRenderer.rectLine(100, 0, 100, 300, 20);
//
// // TODO: Draw two leaves on the stem
//
// // TODO: Set the active color to yellow
//
// // TODO: Use a loop to draw 20 of these petals in a circle
//
// float petalAngle = 45.0f;
// shapeRenderer.rect(100, 300, 0, 0, 40, 40, 1, 1, petalAngle);
//
// shapeRenderer.end();
// }
// }
// Path: 1.3.07-Solution-RectangularFlower/desktop/src/com/udacity/gamedev/rectangularflower/desktop/DesktopLauncher.java
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.udacity.gamedev.rectangularflower.RectangularFlower;
package com.udacity.gamedev.rectangularflower.desktop;
public class DesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); | new LwjglApplication(new RectangularFlower(), config); |
udacity/ud405 | 1.5.02-Solution-ReciprocatingMotion/desktop/src/com/udacity/gamedev/reciprocatingmotion/desktop/DesktopLauncher.java | // Path: 1.5.02-Exercise-ReciprocatingMotion/core/src/com/udacity/gamedev/reciprocatingmotion/ReciprocatingMotion.java
// public class ReciprocatingMotion extends ApplicationAdapter {
//
// private static final float WORLD_SIZE = 480;
// private static final float CIRCLE_RADIUS = WORLD_SIZE / 20;
// private static final float MOVEMENT_DISTANCE = WORLD_SIZE / 4;
//
// // TODO: Define a constant that fixes how long a cycle of the animation should take in seconds
//
//
// ShapeRenderer renderer;
// ExtendViewport viewport;
//
// // TODO: Create a long to hold onto ApplicationAdapter creation time
//
//
// @Override
// public void create() {
// renderer = new ShapeRenderer();
// viewport = new ExtendViewport(WORLD_SIZE, WORLD_SIZE);
//
// // TODO: Save current value of TimeUtils.nanoTime()
//
// }
//
// @Override
// public void resize(int width, int height) {
// viewport.update(width, height, true);
// }
//
// @Override
// public void dispose() {
// renderer.dispose();
// }
//
// @Override
// public void render() {
// viewport.apply();
//
// Gdx.gl.glClearColor(0, 0, 0, 1);
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//
// renderer.setProjectionMatrix(viewport.getCamera().combined);
// renderer.begin(ShapeType.Filled);
//
// // Since we're using an extend viewport, the world might be bigger than we expect
// float worldCenterX = viewport.getWorldWidth() / 2;
// float worldCenterY = viewport.getWorldHeight() / 2;
//
// // TODO: Figure out how long it's been since the animation started using TimeUtils.nanoTime()
//
//
// // TODO: Use MathUtils.nanoToSec to figure out how many seconds the animation has been running
//
//
// // TODO: Figure out how many cycles have elapsed since the animation started running
//
//
// // TODO: Figure out where in the cycle we are
//
//
// // TODO: Use MathUtils.sin() to set the x position of the circle
//
//
// float x = worldCenterX;
// float y = worldCenterY;
// renderer.circle(x, y, CIRCLE_RADIUS);
// renderer.end();
//
// }
// }
| import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.udacity.gamedev.reciprocatingmotion.ReciprocatingMotion; | package com.udacity.gamedev.reciprocatingmotion.desktop;
public class DesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); | // Path: 1.5.02-Exercise-ReciprocatingMotion/core/src/com/udacity/gamedev/reciprocatingmotion/ReciprocatingMotion.java
// public class ReciprocatingMotion extends ApplicationAdapter {
//
// private static final float WORLD_SIZE = 480;
// private static final float CIRCLE_RADIUS = WORLD_SIZE / 20;
// private static final float MOVEMENT_DISTANCE = WORLD_SIZE / 4;
//
// // TODO: Define a constant that fixes how long a cycle of the animation should take in seconds
//
//
// ShapeRenderer renderer;
// ExtendViewport viewport;
//
// // TODO: Create a long to hold onto ApplicationAdapter creation time
//
//
// @Override
// public void create() {
// renderer = new ShapeRenderer();
// viewport = new ExtendViewport(WORLD_SIZE, WORLD_SIZE);
//
// // TODO: Save current value of TimeUtils.nanoTime()
//
// }
//
// @Override
// public void resize(int width, int height) {
// viewport.update(width, height, true);
// }
//
// @Override
// public void dispose() {
// renderer.dispose();
// }
//
// @Override
// public void render() {
// viewport.apply();
//
// Gdx.gl.glClearColor(0, 0, 0, 1);
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//
// renderer.setProjectionMatrix(viewport.getCamera().combined);
// renderer.begin(ShapeType.Filled);
//
// // Since we're using an extend viewport, the world might be bigger than we expect
// float worldCenterX = viewport.getWorldWidth() / 2;
// float worldCenterY = viewport.getWorldHeight() / 2;
//
// // TODO: Figure out how long it's been since the animation started using TimeUtils.nanoTime()
//
//
// // TODO: Use MathUtils.nanoToSec to figure out how many seconds the animation has been running
//
//
// // TODO: Figure out how many cycles have elapsed since the animation started running
//
//
// // TODO: Figure out where in the cycle we are
//
//
// // TODO: Use MathUtils.sin() to set the x position of the circle
//
//
// float x = worldCenterX;
// float y = worldCenterY;
// renderer.circle(x, y, CIRCLE_RADIUS);
// renderer.end();
//
// }
// }
// Path: 1.5.02-Solution-ReciprocatingMotion/desktop/src/com/udacity/gamedev/reciprocatingmotion/desktop/DesktopLauncher.java
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.udacity.gamedev.reciprocatingmotion.ReciprocatingMotion;
package com.udacity.gamedev.reciprocatingmotion.desktop;
public class DesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); | new LwjglApplication(new ReciprocatingMotion(), config); |
udacity/ud405 | 1.3.01-Demo-DrawingPoints/desktop/src/com/udacity/gamedev/pointdrawing/desktop/DesktopLauncher.java | // Path: 1.3.01-Demo-DrawingPoints/core/src/com/udacity/gamedev/pointdrawing/PointDrawing.java
// public class PointDrawing implements ApplicationListener {
//
// // Always tag your log messages!
// public static final String TAG = PointDrawing.class.getName();
// private ShapeRenderer shapeRenderer;
//
// /**
// * This is called when the application is ready for us to start up. Anything you'd do in a
// * constructor, do in create instead.
// */
// @Override
// public void create() {
// Gdx.app.log(TAG, "Application Listener Created");
// // Never allocate anything in render, since that gets called 60 times a second
// shapeRenderer = new ShapeRenderer();
// }
//
// /**
// * resize gets called right after create, and any time the screen size changes. This can happen
// * when a mobile device rotates, or if you drag around the size of the desktop window. We'll be
// * responding to resize in more interesting ways in the next level.
// */
// @Override
// public void resize(int width, int height) {
// Gdx.app.log(TAG, "Resized to width = " + width + " height = " + height);
// }
//
// /**
// * When Java finds that it's running out of memory, it performs a garbage collection to free up
// * memory held by objects that are no longer in use. Unfortunately, garbage collection is slow,
// * and nothing else can happen while the collection is in process. In a game, this can mean a
// * momentary freeze, which players hate with a burning passion. LibGDX does two things to avoid
// * this. First, there are a number of places where we need to manage our own memory. Since we
// * created a ShapeRenderer, we also need to dispose of it, as shown below.
// * <p>
// * The other way LibGDX avoids garbage collection hangs is by providing a ton of custom
// * collections that cleverly manage memory. We'll be using some of those soon.
// */
// @Override
// public void dispose() {
// Gdx.app.log(TAG, "Application Listener Disposed of");
// shapeRenderer.dispose();
// }
//
// /**
// * Render is where the action happens. By default, render will get called 60 times a second, and
// * it's the cue that it's time for our game to update itself and draw a new frame.
// */
// @Override
// public void render() {
// // Set the background color to opaque black
// Gdx.gl.glClearColor(0, 0, 0, 1);
// // Actually tell OpenGL to clear the screen
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// // First we begin a batch of points
// shapeRenderer.begin(ShapeType.Point);
// // Then we draw a point
// shapeRenderer.point(100, 100, 0);
// // And make sure we end the batch
// shapeRenderer.end();
// }
//
// /**
// * Called when the game loses focus, or when it's about to be destroyed. This is the time to
// * save any state you want to persist.
// */
// @Override
// public void pause() {
// Gdx.app.log(TAG, "Paused");
// }
//
// /**
// * Called when the game regains focus after being paused. This is mostly relevant on Android,
// * where the game can be paused by pressing the home button, but dispose is not called. When the
// * game is relaunched, resume will be called.
// */
// @Override
// public void resume() {
// Gdx.app.log(TAG, "Resumed");
// }
// }
| import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.udacity.gamedev.pointdrawing.PointDrawing; | package com.udacity.gamedev.pointdrawing.desktop;
public class DesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); | // Path: 1.3.01-Demo-DrawingPoints/core/src/com/udacity/gamedev/pointdrawing/PointDrawing.java
// public class PointDrawing implements ApplicationListener {
//
// // Always tag your log messages!
// public static final String TAG = PointDrawing.class.getName();
// private ShapeRenderer shapeRenderer;
//
// /**
// * This is called when the application is ready for us to start up. Anything you'd do in a
// * constructor, do in create instead.
// */
// @Override
// public void create() {
// Gdx.app.log(TAG, "Application Listener Created");
// // Never allocate anything in render, since that gets called 60 times a second
// shapeRenderer = new ShapeRenderer();
// }
//
// /**
// * resize gets called right after create, and any time the screen size changes. This can happen
// * when a mobile device rotates, or if you drag around the size of the desktop window. We'll be
// * responding to resize in more interesting ways in the next level.
// */
// @Override
// public void resize(int width, int height) {
// Gdx.app.log(TAG, "Resized to width = " + width + " height = " + height);
// }
//
// /**
// * When Java finds that it's running out of memory, it performs a garbage collection to free up
// * memory held by objects that are no longer in use. Unfortunately, garbage collection is slow,
// * and nothing else can happen while the collection is in process. In a game, this can mean a
// * momentary freeze, which players hate with a burning passion. LibGDX does two things to avoid
// * this. First, there are a number of places where we need to manage our own memory. Since we
// * created a ShapeRenderer, we also need to dispose of it, as shown below.
// * <p>
// * The other way LibGDX avoids garbage collection hangs is by providing a ton of custom
// * collections that cleverly manage memory. We'll be using some of those soon.
// */
// @Override
// public void dispose() {
// Gdx.app.log(TAG, "Application Listener Disposed of");
// shapeRenderer.dispose();
// }
//
// /**
// * Render is where the action happens. By default, render will get called 60 times a second, and
// * it's the cue that it's time for our game to update itself and draw a new frame.
// */
// @Override
// public void render() {
// // Set the background color to opaque black
// Gdx.gl.glClearColor(0, 0, 0, 1);
// // Actually tell OpenGL to clear the screen
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// // First we begin a batch of points
// shapeRenderer.begin(ShapeType.Point);
// // Then we draw a point
// shapeRenderer.point(100, 100, 0);
// // And make sure we end the batch
// shapeRenderer.end();
// }
//
// /**
// * Called when the game loses focus, or when it's about to be destroyed. This is the time to
// * save any state you want to persist.
// */
// @Override
// public void pause() {
// Gdx.app.log(TAG, "Paused");
// }
//
// /**
// * Called when the game regains focus after being paused. This is mostly relevant on Android,
// * where the game can be paused by pressing the home button, but dispose is not called. When the
// * game is relaunched, resume will be called.
// */
// @Override
// public void resume() {
// Gdx.app.log(TAG, "Resumed");
// }
// }
// Path: 1.3.01-Demo-DrawingPoints/desktop/src/com/udacity/gamedev/pointdrawing/desktop/DesktopLauncher.java
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.udacity.gamedev.pointdrawing.PointDrawing;
package com.udacity.gamedev.pointdrawing.desktop;
public class DesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); | new LwjglApplication(new PointDrawing(), config); |
udacity/ud405 | 1.3.09-Solution-DrawTheDragonCurve/html/src/com/udacity/gamedev/dragoncurve/client/HtmlLauncher.java | // Path: 1.3.09-Solution-DrawTheDragonCurve/core/src/com/udacity/gamedev/dragoncurve/DragonCurve.java
// public class DragonCurve extends ApplicationAdapter {
//
// private float[] dragonCurve;
// // Any more than 10 and we'll need to break up the polyline into multiple lines
// private static final int RECURSIONS = 10;
//
// private ShapeRenderer shapeRenderer;
//
// @Override
// public void create () {
// dragonCurve = DragonCurveGenerator.generateDragonCurve(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), RECURSIONS);
// shapeRenderer = new ShapeRenderer();
// }
//
// @Override
// public void render () {
// Gdx.gl.glClearColor(0, 0, 0, 1);
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// shapeRenderer.begin(ShapeType.Line);
// shapeRenderer.polyline(dragonCurve);
// shapeRenderer.end();
// }
// }
| import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.backends.gwt.GwtApplication;
import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration;
import com.udacity.gamedev.dragoncurve.DragonCurve; | package com.udacity.gamedev.dragoncurve.client;
public class HtmlLauncher extends GwtApplication {
@Override
public GwtApplicationConfiguration getConfig () {
return new GwtApplicationConfiguration(480, 320);
}
@Override
public ApplicationListener getApplicationListener () { | // Path: 1.3.09-Solution-DrawTheDragonCurve/core/src/com/udacity/gamedev/dragoncurve/DragonCurve.java
// public class DragonCurve extends ApplicationAdapter {
//
// private float[] dragonCurve;
// // Any more than 10 and we'll need to break up the polyline into multiple lines
// private static final int RECURSIONS = 10;
//
// private ShapeRenderer shapeRenderer;
//
// @Override
// public void create () {
// dragonCurve = DragonCurveGenerator.generateDragonCurve(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), RECURSIONS);
// shapeRenderer = new ShapeRenderer();
// }
//
// @Override
// public void render () {
// Gdx.gl.glClearColor(0, 0, 0, 1);
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// shapeRenderer.begin(ShapeType.Line);
// shapeRenderer.polyline(dragonCurve);
// shapeRenderer.end();
// }
// }
// Path: 1.3.09-Solution-DrawTheDragonCurve/html/src/com/udacity/gamedev/dragoncurve/client/HtmlLauncher.java
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.backends.gwt.GwtApplication;
import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration;
import com.udacity.gamedev.dragoncurve.DragonCurve;
package com.udacity.gamedev.dragoncurve.client;
public class HtmlLauncher extends GwtApplication {
@Override
public GwtApplicationConfiguration getConfig () {
return new GwtApplicationConfiguration(480, 320);
}
@Override
public ApplicationListener getApplicationListener () { | return new DragonCurve(); |
udacity/ud405 | 1.8.03-Solution-AddDifficultyLevels/core/src/com/udacity/gamedev/icicles/Icicles.java | // Path: 1.8.04-Exercise-AddDifficultySelectScreen/core/src/com/udacity/gamedev/icicles/Constants.java
// public enum Difficulty {
// EASY(EASY_SPAWNS_PER_SECOND, EASY_LABEL),
// MEDIUM(MEDIUM_SPAWNS_PER_SECOND, MEDIUM_LABEL),
// HARD(HARD_SPAWNS_PER_SECOND, HARD_LABEL);
//
// float spawnRate;
// String label;
//
// Difficulty(float spawnRate, String label) {
// this.spawnRate = spawnRate;
// this.label = label;
// }
// }
| import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.DelayedRemovalArray;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.udacity.gamedev.icicles.Constants.Difficulty; | package com.udacity.gamedev.icicles;
public class Icicles {
public static final String TAG = Icicles.class.getName();
// TODO: Add a Difficulty | // Path: 1.8.04-Exercise-AddDifficultySelectScreen/core/src/com/udacity/gamedev/icicles/Constants.java
// public enum Difficulty {
// EASY(EASY_SPAWNS_PER_SECOND, EASY_LABEL),
// MEDIUM(MEDIUM_SPAWNS_PER_SECOND, MEDIUM_LABEL),
// HARD(HARD_SPAWNS_PER_SECOND, HARD_LABEL);
//
// float spawnRate;
// String label;
//
// Difficulty(float spawnRate, String label) {
// this.spawnRate = spawnRate;
// this.label = label;
// }
// }
// Path: 1.8.03-Solution-AddDifficultyLevels/core/src/com/udacity/gamedev/icicles/Icicles.java
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.DelayedRemovalArray;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.udacity.gamedev.icicles.Constants.Difficulty;
package com.udacity.gamedev.icicles;
public class Icicles {
public static final String TAG = Icicles.class.getName();
// TODO: Add a Difficulty | Difficulty difficulty; |
udacity/ud405 | 1.3.02-Solution-DrawAStarfield/ios/src/com/udacity/gamedev/starfield/IOSLauncher.java | // Path: 1.3.02-Exercise-DrawAStarfield/core/src/com/udacity/gamedev/starfield/Starfield.java
// public class Starfield extends ApplicationAdapter {
//
// private static final float STAR_DENSITY = 0.01f;
// ShapeRenderer shapeRenderer;
// Array<Vector2> stars;
//
// @Override
// public void create() {
// // TODO: Initialize a shapeRenderer
//
// // TODO: Call initStars
//
// }
//
// public void initStars(float density) {
// // TODO: Figure out how many stars to draw. You'll need the screen dimensions, which you can get using Gdx.graphics.getWidth() and Gdx.graphics.getHeight().
//
// // TODO: Create a new array of Vector2's to hold the star positions
//
// // TODO: Use java.util.Random to fill the array of star positions
//
// }
//
// @Override
// public void resize(int width, int height) {
// initStars(STAR_DENSITY);
// shapeRenderer = new ShapeRenderer();
// }
//
// @Override
// public void render() {
// // TODO: Make the night sky black
// Gdx.gl.glClearColor(1, 0, 0, 1);
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//
// // TODO: Begin a shapeRenderer batch using ShapeType.Point
//
// // TODO: Loop through the star positions and use shapeRenderer to draw points
//
// // TODO: End the shapeRenderer batch
//
// }
//
// @Override
// public void dispose() {
// // TODO: Dispose of our ShapeRenderer
//
// super.dispose();
// }
// }
| import org.robovm.apple.foundation.NSAutoreleasePool;
import org.robovm.apple.uikit.UIApplication;
import com.badlogic.gdx.backends.iosrobovm.IOSApplication;
import com.badlogic.gdx.backends.iosrobovm.IOSApplicationConfiguration;
import com.udacity.gamedev.starfield.Starfield; | package com.udacity.gamedev.starfield;
public class IOSLauncher extends IOSApplication.Delegate {
@Override
protected IOSApplication createApplication() {
IOSApplicationConfiguration config = new IOSApplicationConfiguration(); | // Path: 1.3.02-Exercise-DrawAStarfield/core/src/com/udacity/gamedev/starfield/Starfield.java
// public class Starfield extends ApplicationAdapter {
//
// private static final float STAR_DENSITY = 0.01f;
// ShapeRenderer shapeRenderer;
// Array<Vector2> stars;
//
// @Override
// public void create() {
// // TODO: Initialize a shapeRenderer
//
// // TODO: Call initStars
//
// }
//
// public void initStars(float density) {
// // TODO: Figure out how many stars to draw. You'll need the screen dimensions, which you can get using Gdx.graphics.getWidth() and Gdx.graphics.getHeight().
//
// // TODO: Create a new array of Vector2's to hold the star positions
//
// // TODO: Use java.util.Random to fill the array of star positions
//
// }
//
// @Override
// public void resize(int width, int height) {
// initStars(STAR_DENSITY);
// shapeRenderer = new ShapeRenderer();
// }
//
// @Override
// public void render() {
// // TODO: Make the night sky black
// Gdx.gl.glClearColor(1, 0, 0, 1);
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//
// // TODO: Begin a shapeRenderer batch using ShapeType.Point
//
// // TODO: Loop through the star positions and use shapeRenderer to draw points
//
// // TODO: End the shapeRenderer batch
//
// }
//
// @Override
// public void dispose() {
// // TODO: Dispose of our ShapeRenderer
//
// super.dispose();
// }
// }
// Path: 1.3.02-Solution-DrawAStarfield/ios/src/com/udacity/gamedev/starfield/IOSLauncher.java
import org.robovm.apple.foundation.NSAutoreleasePool;
import org.robovm.apple.uikit.UIApplication;
import com.badlogic.gdx.backends.iosrobovm.IOSApplication;
import com.badlogic.gdx.backends.iosrobovm.IOSApplicationConfiguration;
import com.udacity.gamedev.starfield.Starfield;
package com.udacity.gamedev.starfield;
public class IOSLauncher extends IOSApplication.Delegate {
@Override
protected IOSApplication createApplication() {
IOSApplicationConfiguration config = new IOSApplicationConfiguration(); | return new IOSApplication(new Starfield(), config); |
udacity/ud405 | 1.4.03-Demo-Cameras/desktop/src/com/udacity/gamedev/orthographicprojection/desktop/DesktopLauncher.java | // Path: 1.4.03-Demo-Cameras/core/src/com/udacity/gamedev/orthographicprojection/OrthographicProjection.java
// public class OrthographicProjection extends ApplicationAdapter {
//
// ShapeRenderer renderer;
// DemoCamera demoCamera;
//
// @Override
// public void create() {
// renderer = new ShapeRenderer();
// demoCamera = new DemoCamera();
// // Tell LibGDX that demoCamera knows what to do with keypresses
// Gdx.input.setInputProcessor(demoCamera);
// }
//
// @Override
// public void resize(int width, int height) {
// demoCamera.resize(width, height);
// }
//
// @Override
// public void render() {
// Gdx.gl.glClearColor(0, 0, 0, 1);
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// demoCamera.update();
// demoCamera.setCamera(renderer);
// renderTestScene(renderer);
// demoCamera.render(renderer);
// }
//
// /**
// * This method renders a few shapes for us to try our camera on. Note that we're using a Bezier
// * curve, which is a way to draw smooth curves. For more information on Bezier curves, check
// * out: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
// *
// * Also note that a line is a line is a line. No matter how much we zoom in, a line is always
// * just one pixel wide.
// */
// private void renderTestScene(ShapeRenderer renderer) {
// renderer.begin(ShapeType.Filled);
// renderer.setColor(Color.GREEN);
// renderer.circle(100, 100, 90);
// renderer.setColor(Color.RED);
// renderer.rect(200, 10, 200, 200);
// renderer.setColor(Color.YELLOW);
// renderer.triangle(10, 200, 200, 200, 100, 400);
// renderer.end();
// renderer.begin(ShapeType.Line);
//
// renderer.setColor(Color.CYAN);
//
// // Here's another shape ShapeRenderer
// renderer.curve(
// 210, 210,
// 400, 210,
// 210, 400,
// 400, 300,
// 20);
// renderer.end();
// }
// }
| import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.udacity.gamedev.orthographicprojection.OrthographicProjection; | package com.udacity.gamedev.orthographicprojection.desktop;
public class DesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); | // Path: 1.4.03-Demo-Cameras/core/src/com/udacity/gamedev/orthographicprojection/OrthographicProjection.java
// public class OrthographicProjection extends ApplicationAdapter {
//
// ShapeRenderer renderer;
// DemoCamera demoCamera;
//
// @Override
// public void create() {
// renderer = new ShapeRenderer();
// demoCamera = new DemoCamera();
// // Tell LibGDX that demoCamera knows what to do with keypresses
// Gdx.input.setInputProcessor(demoCamera);
// }
//
// @Override
// public void resize(int width, int height) {
// demoCamera.resize(width, height);
// }
//
// @Override
// public void render() {
// Gdx.gl.glClearColor(0, 0, 0, 1);
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// demoCamera.update();
// demoCamera.setCamera(renderer);
// renderTestScene(renderer);
// demoCamera.render(renderer);
// }
//
// /**
// * This method renders a few shapes for us to try our camera on. Note that we're using a Bezier
// * curve, which is a way to draw smooth curves. For more information on Bezier curves, check
// * out: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
// *
// * Also note that a line is a line is a line. No matter how much we zoom in, a line is always
// * just one pixel wide.
// */
// private void renderTestScene(ShapeRenderer renderer) {
// renderer.begin(ShapeType.Filled);
// renderer.setColor(Color.GREEN);
// renderer.circle(100, 100, 90);
// renderer.setColor(Color.RED);
// renderer.rect(200, 10, 200, 200);
// renderer.setColor(Color.YELLOW);
// renderer.triangle(10, 200, 200, 200, 100, 400);
// renderer.end();
// renderer.begin(ShapeType.Line);
//
// renderer.setColor(Color.CYAN);
//
// // Here's another shape ShapeRenderer
// renderer.curve(
// 210, 210,
// 400, 210,
// 210, 400,
// 400, 300,
// 20);
// renderer.end();
// }
// }
// Path: 1.4.03-Demo-Cameras/desktop/src/com/udacity/gamedev/orthographicprojection/desktop/DesktopLauncher.java
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.udacity.gamedev.orthographicprojection.OrthographicProjection;
package com.udacity.gamedev.orthographicprojection.desktop;
public class DesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); | new LwjglApplication(new OrthographicProjection(), config); |
udacity/ud405 | 1.4.09-Demo-Text/android/src/com/udacity/gamedev/textdemo/android/AndroidLauncher.java | // Path: 1.4.09-Demo-Text/core/src/com/udacity/gamedev/textdemo/TextDemo.java
// public class TextDemo extends ApplicationAdapter {
//
// SpriteBatch batch;
// BitmapFont font;
//
// @Override
// public void create() {
// batch = new SpriteBatch();
// // Create the default font
// font = new BitmapFont();
// // Scale it up
// font.getData().setScale(3);
// // Set the filter
// font.getRegion().getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
// }
//
// /**
// * Remember to dispose of SpriteBatches and fonts!
// */
// @Override
// public void dispose() {
// batch.dispose();
// font.dispose();
// }
//
// @Override
// public void render() {
// Gdx.gl.glClearColor(0, 0, 0, 1);
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// // We begin batches just like with a ShapeRenderer, though there's no mode
// batch.begin();
// font.draw(batch, "Text", 100, 100);
// // Remember to end the batch
// batch.end();
// }
// }
| import android.os.Bundle;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.udacity.gamedev.textdemo.TextDemo; | package com.udacity.gamedev.textdemo.android;
public class AndroidLauncher extends AndroidApplication {
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); | // Path: 1.4.09-Demo-Text/core/src/com/udacity/gamedev/textdemo/TextDemo.java
// public class TextDemo extends ApplicationAdapter {
//
// SpriteBatch batch;
// BitmapFont font;
//
// @Override
// public void create() {
// batch = new SpriteBatch();
// // Create the default font
// font = new BitmapFont();
// // Scale it up
// font.getData().setScale(3);
// // Set the filter
// font.getRegion().getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear);
// }
//
// /**
// * Remember to dispose of SpriteBatches and fonts!
// */
// @Override
// public void dispose() {
// batch.dispose();
// font.dispose();
// }
//
// @Override
// public void render() {
// Gdx.gl.glClearColor(0, 0, 0, 1);
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// // We begin batches just like with a ShapeRenderer, though there's no mode
// batch.begin();
// font.draw(batch, "Text", 100, 100);
// // Remember to end the batch
// batch.end();
// }
// }
// Path: 1.4.09-Demo-Text/android/src/com/udacity/gamedev/textdemo/android/AndroidLauncher.java
import android.os.Bundle;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.udacity.gamedev.textdemo.TextDemo;
package com.udacity.gamedev.textdemo.android;
public class AndroidLauncher extends AndroidApplication {
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); | initialize(new TextDemo(), config); |
udacity/ud405 | 1.5.02-Solution-ReciprocatingMotion/android/src/com/udacity/gamedev/reciprocatingmotion/android/AndroidLauncher.java | // Path: 1.5.02-Exercise-ReciprocatingMotion/core/src/com/udacity/gamedev/reciprocatingmotion/ReciprocatingMotion.java
// public class ReciprocatingMotion extends ApplicationAdapter {
//
// private static final float WORLD_SIZE = 480;
// private static final float CIRCLE_RADIUS = WORLD_SIZE / 20;
// private static final float MOVEMENT_DISTANCE = WORLD_SIZE / 4;
//
// // TODO: Define a constant that fixes how long a cycle of the animation should take in seconds
//
//
// ShapeRenderer renderer;
// ExtendViewport viewport;
//
// // TODO: Create a long to hold onto ApplicationAdapter creation time
//
//
// @Override
// public void create() {
// renderer = new ShapeRenderer();
// viewport = new ExtendViewport(WORLD_SIZE, WORLD_SIZE);
//
// // TODO: Save current value of TimeUtils.nanoTime()
//
// }
//
// @Override
// public void resize(int width, int height) {
// viewport.update(width, height, true);
// }
//
// @Override
// public void dispose() {
// renderer.dispose();
// }
//
// @Override
// public void render() {
// viewport.apply();
//
// Gdx.gl.glClearColor(0, 0, 0, 1);
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//
// renderer.setProjectionMatrix(viewport.getCamera().combined);
// renderer.begin(ShapeType.Filled);
//
// // Since we're using an extend viewport, the world might be bigger than we expect
// float worldCenterX = viewport.getWorldWidth() / 2;
// float worldCenterY = viewport.getWorldHeight() / 2;
//
// // TODO: Figure out how long it's been since the animation started using TimeUtils.nanoTime()
//
//
// // TODO: Use MathUtils.nanoToSec to figure out how many seconds the animation has been running
//
//
// // TODO: Figure out how many cycles have elapsed since the animation started running
//
//
// // TODO: Figure out where in the cycle we are
//
//
// // TODO: Use MathUtils.sin() to set the x position of the circle
//
//
// float x = worldCenterX;
// float y = worldCenterY;
// renderer.circle(x, y, CIRCLE_RADIUS);
// renderer.end();
//
// }
// }
| import android.os.Bundle;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.udacity.gamedev.reciprocatingmotion.ReciprocatingMotion; | package com.udacity.gamedev.reciprocatingmotion.android;
public class AndroidLauncher extends AndroidApplication {
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); | // Path: 1.5.02-Exercise-ReciprocatingMotion/core/src/com/udacity/gamedev/reciprocatingmotion/ReciprocatingMotion.java
// public class ReciprocatingMotion extends ApplicationAdapter {
//
// private static final float WORLD_SIZE = 480;
// private static final float CIRCLE_RADIUS = WORLD_SIZE / 20;
// private static final float MOVEMENT_DISTANCE = WORLD_SIZE / 4;
//
// // TODO: Define a constant that fixes how long a cycle of the animation should take in seconds
//
//
// ShapeRenderer renderer;
// ExtendViewport viewport;
//
// // TODO: Create a long to hold onto ApplicationAdapter creation time
//
//
// @Override
// public void create() {
// renderer = new ShapeRenderer();
// viewport = new ExtendViewport(WORLD_SIZE, WORLD_SIZE);
//
// // TODO: Save current value of TimeUtils.nanoTime()
//
// }
//
// @Override
// public void resize(int width, int height) {
// viewport.update(width, height, true);
// }
//
// @Override
// public void dispose() {
// renderer.dispose();
// }
//
// @Override
// public void render() {
// viewport.apply();
//
// Gdx.gl.glClearColor(0, 0, 0, 1);
// Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
//
// renderer.setProjectionMatrix(viewport.getCamera().combined);
// renderer.begin(ShapeType.Filled);
//
// // Since we're using an extend viewport, the world might be bigger than we expect
// float worldCenterX = viewport.getWorldWidth() / 2;
// float worldCenterY = viewport.getWorldHeight() / 2;
//
// // TODO: Figure out how long it's been since the animation started using TimeUtils.nanoTime()
//
//
// // TODO: Use MathUtils.nanoToSec to figure out how many seconds the animation has been running
//
//
// // TODO: Figure out how many cycles have elapsed since the animation started running
//
//
// // TODO: Figure out where in the cycle we are
//
//
// // TODO: Use MathUtils.sin() to set the x position of the circle
//
//
// float x = worldCenterX;
// float y = worldCenterY;
// renderer.circle(x, y, CIRCLE_RADIUS);
// renderer.end();
//
// }
// }
// Path: 1.5.02-Solution-ReciprocatingMotion/android/src/com/udacity/gamedev/reciprocatingmotion/android/AndroidLauncher.java
import android.os.Bundle;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.udacity.gamedev.reciprocatingmotion.ReciprocatingMotion;
package com.udacity.gamedev.reciprocatingmotion.android;
public class AndroidLauncher extends AndroidApplication {
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); | initialize(new ReciprocatingMotion(), config); |
tommyettinger/RegExodus | src/main/java/regexodus/emu/java/util/regex/Pattern.java | // Path: src/main/java/regexodus/REFlags.java
// public interface REFlags {
// /**
// * All the following options turned off, EXCEPT UNICODE. Unicode handling can be turned off with "-u" at the end
// * of a flag string, or by simply specifying only the flags you want in a bitmask, like
// * {@code (REFlags.IGNORE_CASE | REFlags.MULTILINE | REFlags.DOTALL)}.
// * <br>
// * This behavior changed between the 0.1.1 and 0.1.2 release.
// */
// int DEFAULT = 16;
//
// /**
// * Pattern "a" matches both "a" and "A".
// * Corresponds to "i" in Perl notation.
// */
// int IGNORE_CASE = 1 << 0;
//
// /**
// * Affects the behaviour of "^" and "$" tags. When switched off:
// * <ul>
// * <li> the "^" matches the beginning of the whole text;</li>
// * <li> the "$" matches the end of the whole text, or just before the '\n' or "\r\n" at the end of text.</li>
// * </ul>
// * When switched on:
// * <ul>
// * <li> the "^" additionally matches the line beginnings (that is just after the '\n');</li>
// * <li> the "$" additionally matches the line ends (that is just before "\r\n" or '\n');</li>
// * </ul>
// * Corresponds to "m" in Perl notation.
// */
// int MULTILINE = 1 << 1;
//
// /**
// * Affects the behaviour of dot(".") tag. When switched off:
// * <ul>
// * <li> the dot matches any character but EOLs('\r','\n');</li>
// * </ul>
// * When switched on:
// * <ul>
// * <li> the dot matches any character, including EOLs.</li>
// * </ul>
// * This flag is sometimes referenced in regex tutorials as SINGLELINE, which confusingly seems opposite to MULTILINE, but in fact is orthogonal.
// * Corresponds to "s" in Perl notation.
// */
// int DOTALL = 1 << 2;
//
// /**
// * Affects how the space characters are interpreted in the expression. When switched off:
// * <ul>
// * <li> the spaces are interpreted literally;</li>
// * </ul>
// * When switched on:
// * <ul>
// * <li> the spaces are ignored, allowing an expression to be slightly more readable.</li>
// * </ul>
// * Corresponds to "x" in Perl notation.
// */
// int IGNORE_SPACES = 1 << 3;
//
// /**
// * Affects whether the predefined classes("\d","\s","\w",etc) in the expression are interpreted as belonging to Unicode. When switched off:
// * <ul>
// * <li> the predefined classes are interpreted as ASCII;</li>
// * </ul>
// * When switched on:
// * <ul>
// * <li> the predefined classes are interpreted as Unicode categories;</li>
// * </ul>
// * Defaults to switched on, unlike the others. When specifying a flags with an int, however, UNICODE doesn't get
// * added automatically, so if you add a flag and want UNICODE on as well, you should specify it, too.
// * <br>
// * Corresponds to "u" in Perl notation.
// */
// int UNICODE = 1 << 4;
//
// /**
// * Turns on the compatibility with XML Schema regular expressions.
// * <br>
// * Corresponds to "X" in Perl notation.
// */
// int XML_SCHEMA = 1 << 5;
//
//
// }
| import regexodus.REFlags;
import java.io.Serializable;
import java.util.ArrayList; | * <br>
* This method produces a <code>String</code> that can be used to
* create a <code>Pattern</code> that would match the string
* <code>s</code> as if it were a literal pattern. Metacharacters
* or escape sequences in the input sequence will be given no special
* meaning.
*
* @param s The string to be literalized
* @return A literal string replacement
*/
public static String quote(String s) {
int slashEIndex = s.indexOf("\\E");
if (slashEIndex == -1)
return "\\Q" + s + "\\E";
StringBuilder sb = new StringBuilder(s.length() * 2);
sb.append("\\Q");
int current = 0;
while ((slashEIndex = s.indexOf("\\E", current)) != -1) {
sb.append(s.substring(current, slashEIndex));
current = slashEIndex + 2;
sb.append("\\E\\\\E\\Q");
}
sb.append(s.substring(current, s.length()));
sb.append("\\E");
return sb.toString();
}
private Pattern(String p, int flags)
{ | // Path: src/main/java/regexodus/REFlags.java
// public interface REFlags {
// /**
// * All the following options turned off, EXCEPT UNICODE. Unicode handling can be turned off with "-u" at the end
// * of a flag string, or by simply specifying only the flags you want in a bitmask, like
// * {@code (REFlags.IGNORE_CASE | REFlags.MULTILINE | REFlags.DOTALL)}.
// * <br>
// * This behavior changed between the 0.1.1 and 0.1.2 release.
// */
// int DEFAULT = 16;
//
// /**
// * Pattern "a" matches both "a" and "A".
// * Corresponds to "i" in Perl notation.
// */
// int IGNORE_CASE = 1 << 0;
//
// /**
// * Affects the behaviour of "^" and "$" tags. When switched off:
// * <ul>
// * <li> the "^" matches the beginning of the whole text;</li>
// * <li> the "$" matches the end of the whole text, or just before the '\n' or "\r\n" at the end of text.</li>
// * </ul>
// * When switched on:
// * <ul>
// * <li> the "^" additionally matches the line beginnings (that is just after the '\n');</li>
// * <li> the "$" additionally matches the line ends (that is just before "\r\n" or '\n');</li>
// * </ul>
// * Corresponds to "m" in Perl notation.
// */
// int MULTILINE = 1 << 1;
//
// /**
// * Affects the behaviour of dot(".") tag. When switched off:
// * <ul>
// * <li> the dot matches any character but EOLs('\r','\n');</li>
// * </ul>
// * When switched on:
// * <ul>
// * <li> the dot matches any character, including EOLs.</li>
// * </ul>
// * This flag is sometimes referenced in regex tutorials as SINGLELINE, which confusingly seems opposite to MULTILINE, but in fact is orthogonal.
// * Corresponds to "s" in Perl notation.
// */
// int DOTALL = 1 << 2;
//
// /**
// * Affects how the space characters are interpreted in the expression. When switched off:
// * <ul>
// * <li> the spaces are interpreted literally;</li>
// * </ul>
// * When switched on:
// * <ul>
// * <li> the spaces are ignored, allowing an expression to be slightly more readable.</li>
// * </ul>
// * Corresponds to "x" in Perl notation.
// */
// int IGNORE_SPACES = 1 << 3;
//
// /**
// * Affects whether the predefined classes("\d","\s","\w",etc) in the expression are interpreted as belonging to Unicode. When switched off:
// * <ul>
// * <li> the predefined classes are interpreted as ASCII;</li>
// * </ul>
// * When switched on:
// * <ul>
// * <li> the predefined classes are interpreted as Unicode categories;</li>
// * </ul>
// * Defaults to switched on, unlike the others. When specifying a flags with an int, however, UNICODE doesn't get
// * added automatically, so if you add a flag and want UNICODE on as well, you should specify it, too.
// * <br>
// * Corresponds to "u" in Perl notation.
// */
// int UNICODE = 1 << 4;
//
// /**
// * Turns on the compatibility with XML Schema regular expressions.
// * <br>
// * Corresponds to "X" in Perl notation.
// */
// int XML_SCHEMA = 1 << 5;
//
//
// }
// Path: src/main/java/regexodus/emu/java/util/regex/Pattern.java
import regexodus.REFlags;
import java.io.Serializable;
import java.util.ArrayList;
* <br>
* This method produces a <code>String</code> that can be used to
* create a <code>Pattern</code> that would match the string
* <code>s</code> as if it were a literal pattern. Metacharacters
* or escape sequences in the input sequence will be given no special
* meaning.
*
* @param s The string to be literalized
* @return A literal string replacement
*/
public static String quote(String s) {
int slashEIndex = s.indexOf("\\E");
if (slashEIndex == -1)
return "\\Q" + s + "\\E";
StringBuilder sb = new StringBuilder(s.length() * 2);
sb.append("\\Q");
int current = 0;
while ((slashEIndex = s.indexOf("\\E", current)) != -1) {
sb.append(s.substring(current, slashEIndex));
current = slashEIndex + 2;
sb.append("\\E\\\\E\\Q");
}
sb.append(s.substring(current, s.length()));
sb.append("\\E");
return sb.toString();
}
private Pattern(String p, int flags)
{ | int fm = (flags & CASE_INSENSITIVE) != 0 ? REFlags.IGNORE_CASE : 0; |
ChristinGorman/baxter | src/main/java/no/gorman/database/BigBrother.java | // Path: src/main/java/no/gorman/database/DBFunctions.java
// public static Object get(Field f, Object instance) {
// try {
// return f.get(instance);
// }catch (IllegalAccessException e) {
// throw new RuntimeException(e);
// }
// }
//
// Path: src/main/java/no/gorman/database/DBFunctions.java
// public static List<Field> getMappedFields(Class<?> clazz) {
// List<Field> columnFields = asList(clazz.getDeclaredFields()).stream()
// .filter(f -> f.isAnnotationPresent(Column.class))
// .collect(toList());
// columnFields.forEach(f->f.setAccessible(true));
//
// if (clazz.getSuperclass() != null) {
// columnFields.addAll(getMappedFields(clazz.getSuperclass()));
// }
// return columnFields;
// }
//
// Path: src/main/java/no/gorman/database/DBFunctions.java
// public static <T> Field getPrimaryKeyField(T obj) {
// return getMappedFields(obj.getClass()).stream().filter(f-> getColumn(f).getType() == PrimaryKey).findFirst().orElseThrow(() -> new IllegalArgumentException(obj.getClass().getName() + " has no primary key defined"));
// }
| import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static no.gorman.database.DBFunctions.get;
import static no.gorman.database.DBFunctions.getMappedFields;
import static no.gorman.database.DBFunctions.getPrimaryKeyField; | package no.gorman.database;
public class BigBrother {
public static interface Spy { void suspectAltered(Object suspect); }
private static final ConcurrentMap<RowIdentifier, WeakHashMap<Spy, Boolean>> spies = new ConcurrentHashMap<>();
private static List<WeakReference<Spy>> spyRefs = Collections.synchronizedList(new ArrayList<>());
//Keep track of all weak references created, listen for when they are garbage collected,
// so the main spy-map doesn't fill up with keys that have no living spies left.
private static final ReferenceQueue<Spy> terminatedSpies = new ReferenceQueue<>();
static {
new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
try {
terminatedSpies.remove(); | // Path: src/main/java/no/gorman/database/DBFunctions.java
// public static Object get(Field f, Object instance) {
// try {
// return f.get(instance);
// }catch (IllegalAccessException e) {
// throw new RuntimeException(e);
// }
// }
//
// Path: src/main/java/no/gorman/database/DBFunctions.java
// public static List<Field> getMappedFields(Class<?> clazz) {
// List<Field> columnFields = asList(clazz.getDeclaredFields()).stream()
// .filter(f -> f.isAnnotationPresent(Column.class))
// .collect(toList());
// columnFields.forEach(f->f.setAccessible(true));
//
// if (clazz.getSuperclass() != null) {
// columnFields.addAll(getMappedFields(clazz.getSuperclass()));
// }
// return columnFields;
// }
//
// Path: src/main/java/no/gorman/database/DBFunctions.java
// public static <T> Field getPrimaryKeyField(T obj) {
// return getMappedFields(obj.getClass()).stream().filter(f-> getColumn(f).getType() == PrimaryKey).findFirst().orElseThrow(() -> new IllegalArgumentException(obj.getClass().getName() + " has no primary key defined"));
// }
// Path: src/main/java/no/gorman/database/BigBrother.java
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static no.gorman.database.DBFunctions.get;
import static no.gorman.database.DBFunctions.getMappedFields;
import static no.gorman.database.DBFunctions.getPrimaryKeyField;
package no.gorman.database;
public class BigBrother {
public static interface Spy { void suspectAltered(Object suspect); }
private static final ConcurrentMap<RowIdentifier, WeakHashMap<Spy, Boolean>> spies = new ConcurrentHashMap<>();
private static List<WeakReference<Spy>> spyRefs = Collections.synchronizedList(new ArrayList<>());
//Keep track of all weak references created, listen for when they are garbage collected,
// so the main spy-map doesn't fill up with keys that have no living spies left.
private static final ReferenceQueue<Spy> terminatedSpies = new ReferenceQueue<>();
static {
new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
try {
terminatedSpies.remove(); | spyRefs.removeIf(spy -> spy.get() == null); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.