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
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/osgi/FrameworkShutdownHandler.java
// Path: src/main/java/com/adeptj/runtime/common/ServletContextHolder.java // public enum ServletContextHolder { // // INSTANCE; // // private ServletContext context; // // public void setServletContext(ServletContext context) { // NOSONAR // if (this.context == null) { // this.context = context; // } // } // // public ServletContext getServletContext() { // return this.context; // } // // public <T> T getAttributeOfType(String name, Class<T> type) { // final Object value = this.context.getAttribute(name); // return type.isInstance(value) ? type.cast(value) : null; // } // // public static ServletContextHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/common/Times.java // public final class Times { // // // No instances, just utility methods. // private Times() { // } // // /** // * Returns elapsed time in milliseconds from the provided time in nanoseconds. // * // * @param startTime time in nanoseconds // * @return elapsed time in milliseconds // */ // public static long elapsedMillis(final long startTime) { // return NANOSECONDS.toMillis(System.nanoTime() - startTime); // } // // /** // * Returns elapsed time in seconds from the provided time in milliseconds. // * // * @param startTime time in milliseconds // * @return elapsed time in seconds // */ // public static long elapsedSeconds(final long startTime) { // return MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime); // } // }
import com.adeptj.runtime.common.ServletContextHolder; import com.adeptj.runtime.common.Times; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.osgi; /** * ContextListener that handles the OSGi Framework shutdown. * * @author Rakesh.Kumar, AdeptJ */ @WebListener("Stops the OSGi Framework when ServletContext is destroyed") public class FrameworkShutdownHandler implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent event) { long startTime = System.nanoTime(); Logger logger = LoggerFactory.getLogger(this.getClass()); logger.info("Stopping OSGi Framework as ServletContext is being destroyed!!"); ServiceTrackers.getInstance().closeEventDispatcherTracker(); // see - https://github.com/AdeptJ/adeptj-runtime/issues/4 // Close the DispatcherServletTracker here rather than in BridgeServlet#destroy method. // As with version 3.0.18 of Felix Http base the way with HttpSessionListener(s) handled // is changed which results in a NPE. ServiceTrackers.getInstance().closeDispatcherServletTracker(); FrameworkManager.getInstance().stopFramework();
// Path: src/main/java/com/adeptj/runtime/common/ServletContextHolder.java // public enum ServletContextHolder { // // INSTANCE; // // private ServletContext context; // // public void setServletContext(ServletContext context) { // NOSONAR // if (this.context == null) { // this.context = context; // } // } // // public ServletContext getServletContext() { // return this.context; // } // // public <T> T getAttributeOfType(String name, Class<T> type) { // final Object value = this.context.getAttribute(name); // return type.isInstance(value) ? type.cast(value) : null; // } // // public static ServletContextHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/common/Times.java // public final class Times { // // // No instances, just utility methods. // private Times() { // } // // /** // * Returns elapsed time in milliseconds from the provided time in nanoseconds. // * // * @param startTime time in nanoseconds // * @return elapsed time in milliseconds // */ // public static long elapsedMillis(final long startTime) { // return NANOSECONDS.toMillis(System.nanoTime() - startTime); // } // // /** // * Returns elapsed time in seconds from the provided time in milliseconds. // * // * @param startTime time in milliseconds // * @return elapsed time in seconds // */ // public static long elapsedSeconds(final long startTime) { // return MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime); // } // } // Path: src/main/java/com/adeptj/runtime/osgi/FrameworkShutdownHandler.java import com.adeptj.runtime.common.ServletContextHolder; import com.adeptj.runtime.common.Times; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.osgi; /** * ContextListener that handles the OSGi Framework shutdown. * * @author Rakesh.Kumar, AdeptJ */ @WebListener("Stops the OSGi Framework when ServletContext is destroyed") public class FrameworkShutdownHandler implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent event) { long startTime = System.nanoTime(); Logger logger = LoggerFactory.getLogger(this.getClass()); logger.info("Stopping OSGi Framework as ServletContext is being destroyed!!"); ServiceTrackers.getInstance().closeEventDispatcherTracker(); // see - https://github.com/AdeptJ/adeptj-runtime/issues/4 // Close the DispatcherServletTracker here rather than in BridgeServlet#destroy method. // As with version 3.0.18 of Felix Http base the way with HttpSessionListener(s) handled // is changed which results in a NPE. ServiceTrackers.getInstance().closeDispatcherServletTracker(); FrameworkManager.getInstance().stopFramework();
ServletContextHolder.getInstance().setServletContext(null);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/osgi/FrameworkShutdownHandler.java
// Path: src/main/java/com/adeptj/runtime/common/ServletContextHolder.java // public enum ServletContextHolder { // // INSTANCE; // // private ServletContext context; // // public void setServletContext(ServletContext context) { // NOSONAR // if (this.context == null) { // this.context = context; // } // } // // public ServletContext getServletContext() { // return this.context; // } // // public <T> T getAttributeOfType(String name, Class<T> type) { // final Object value = this.context.getAttribute(name); // return type.isInstance(value) ? type.cast(value) : null; // } // // public static ServletContextHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/common/Times.java // public final class Times { // // // No instances, just utility methods. // private Times() { // } // // /** // * Returns elapsed time in milliseconds from the provided time in nanoseconds. // * // * @param startTime time in nanoseconds // * @return elapsed time in milliseconds // */ // public static long elapsedMillis(final long startTime) { // return NANOSECONDS.toMillis(System.nanoTime() - startTime); // } // // /** // * Returns elapsed time in seconds from the provided time in milliseconds. // * // * @param startTime time in milliseconds // * @return elapsed time in seconds // */ // public static long elapsedSeconds(final long startTime) { // return MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime); // } // }
import com.adeptj.runtime.common.ServletContextHolder; import com.adeptj.runtime.common.Times; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.osgi; /** * ContextListener that handles the OSGi Framework shutdown. * * @author Rakesh.Kumar, AdeptJ */ @WebListener("Stops the OSGi Framework when ServletContext is destroyed") public class FrameworkShutdownHandler implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent event) { long startTime = System.nanoTime(); Logger logger = LoggerFactory.getLogger(this.getClass()); logger.info("Stopping OSGi Framework as ServletContext is being destroyed!!"); ServiceTrackers.getInstance().closeEventDispatcherTracker(); // see - https://github.com/AdeptJ/adeptj-runtime/issues/4 // Close the DispatcherServletTracker here rather than in BridgeServlet#destroy method. // As with version 3.0.18 of Felix Http base the way with HttpSessionListener(s) handled // is changed which results in a NPE. ServiceTrackers.getInstance().closeDispatcherServletTracker(); FrameworkManager.getInstance().stopFramework(); ServletContextHolder.getInstance().setServletContext(null);
// Path: src/main/java/com/adeptj/runtime/common/ServletContextHolder.java // public enum ServletContextHolder { // // INSTANCE; // // private ServletContext context; // // public void setServletContext(ServletContext context) { // NOSONAR // if (this.context == null) { // this.context = context; // } // } // // public ServletContext getServletContext() { // return this.context; // } // // public <T> T getAttributeOfType(String name, Class<T> type) { // final Object value = this.context.getAttribute(name); // return type.isInstance(value) ? type.cast(value) : null; // } // // public static ServletContextHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/common/Times.java // public final class Times { // // // No instances, just utility methods. // private Times() { // } // // /** // * Returns elapsed time in milliseconds from the provided time in nanoseconds. // * // * @param startTime time in nanoseconds // * @return elapsed time in milliseconds // */ // public static long elapsedMillis(final long startTime) { // return NANOSECONDS.toMillis(System.nanoTime() - startTime); // } // // /** // * Returns elapsed time in seconds from the provided time in milliseconds. // * // * @param startTime time in milliseconds // * @return elapsed time in seconds // */ // public static long elapsedSeconds(final long startTime) { // return MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime); // } // } // Path: src/main/java/com/adeptj/runtime/osgi/FrameworkShutdownHandler.java import com.adeptj.runtime.common.ServletContextHolder; import com.adeptj.runtime.common.Times; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.osgi; /** * ContextListener that handles the OSGi Framework shutdown. * * @author Rakesh.Kumar, AdeptJ */ @WebListener("Stops the OSGi Framework when ServletContext is destroyed") public class FrameworkShutdownHandler implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent event) { long startTime = System.nanoTime(); Logger logger = LoggerFactory.getLogger(this.getClass()); logger.info("Stopping OSGi Framework as ServletContext is being destroyed!!"); ServiceTrackers.getInstance().closeEventDispatcherTracker(); // see - https://github.com/AdeptJ/adeptj-runtime/issues/4 // Close the DispatcherServletTracker here rather than in BridgeServlet#destroy method. // As with version 3.0.18 of Felix Http base the way with HttpSessionListener(s) handled // is changed which results in a NPE. ServiceTrackers.getInstance().closeDispatcherServletTracker(); FrameworkManager.getInstance().stopFramework(); ServletContextHolder.getInstance().setServletContext(null);
logger.info("OSGi Framework stopped in [{}] ms!!", Times.elapsedMillis(startTime));
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/osgi/FrameworkLifecycleListener.java
// Path: src/main/java/com/adeptj/runtime/common/BundleContextHolder.java // public enum BundleContextHolder { // // INSTANCE; // // private BundleContext bundleContext; // // public BundleContext getBundleContext() { // return this.bundleContext; // } // // public void setBundleContext(BundleContext bundleContext) { // NOSONAR // this.bundleContext = bundleContext; // } // // public static BundleContextHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/common/ServletContextHolder.java // public enum ServletContextHolder { // // INSTANCE; // // private ServletContext context; // // public void setServletContext(ServletContext context) { // NOSONAR // if (this.context == null) { // this.context = context; // } // } // // public ServletContext getServletContext() { // return this.context; // } // // public <T> T getAttributeOfType(String name, Class<T> type) { // final Object value = this.context.getAttribute(name); // return type.isInstance(value) ? type.cast(value) : null; // } // // public static ServletContextHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String ATTRIBUTE_BUNDLE_CONTEXT = "org.osgi.framework.BundleContext";
import static org.osgi.framework.FrameworkEvent.ERROR; import static org.osgi.framework.FrameworkEvent.STARTED; import com.adeptj.runtime.common.BundleContextHolder; import com.adeptj.runtime.common.ServletContextHolder; import org.apache.commons.lang3.StringUtils; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkEvent; import org.osgi.framework.FrameworkListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.adeptj.runtime.common.Constants.ATTRIBUTE_BUNDLE_CONTEXT;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.osgi; /** * OSGi FrameworkListener which takes care of OSGi framework restart from Felix WebConsole. * * @author Rakesh.Kumar, AdeptJ */ public class FrameworkLifecycleListener implements FrameworkListener { private static final Logger LOGGER = LoggerFactory.getLogger(FrameworkLifecycleListener.class); private static final String SYS_PROP_LOG_FRAMEWORK_ERROR = "adeptj.rt.log.framework.error"; /** * Handles OSGi Framework restart, does following on System Bundle STARTED event. * <p> * 1. Removes the BundleContext from ServletContext attributes. <br> * 2. Gets the new BundleContext from System Bundle and sets that to ServletContext. <br> * 3. Closes the DispatcherServletTracker and open again with new BundleContext. <br> * 4. As the BundleContext is removed and added from ServletContext the corresponding BridgeServletContextAttributeListener * is fired with events which in turn closes the EventDispatcherTracker and opens again with new BundleContext. */ @Override public void frameworkEvent(FrameworkEvent event) { switch (event.getType()) { case STARTED: if (ServiceTrackers.getInstance().isDispatcherServletTrackerOpened()) { LOGGER.info("Handling OSGi Framework Restart!!"); BundleContext bundleContext = event.getBundle().getBundleContext();
// Path: src/main/java/com/adeptj/runtime/common/BundleContextHolder.java // public enum BundleContextHolder { // // INSTANCE; // // private BundleContext bundleContext; // // public BundleContext getBundleContext() { // return this.bundleContext; // } // // public void setBundleContext(BundleContext bundleContext) { // NOSONAR // this.bundleContext = bundleContext; // } // // public static BundleContextHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/common/ServletContextHolder.java // public enum ServletContextHolder { // // INSTANCE; // // private ServletContext context; // // public void setServletContext(ServletContext context) { // NOSONAR // if (this.context == null) { // this.context = context; // } // } // // public ServletContext getServletContext() { // return this.context; // } // // public <T> T getAttributeOfType(String name, Class<T> type) { // final Object value = this.context.getAttribute(name); // return type.isInstance(value) ? type.cast(value) : null; // } // // public static ServletContextHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String ATTRIBUTE_BUNDLE_CONTEXT = "org.osgi.framework.BundleContext"; // Path: src/main/java/com/adeptj/runtime/osgi/FrameworkLifecycleListener.java import static org.osgi.framework.FrameworkEvent.ERROR; import static org.osgi.framework.FrameworkEvent.STARTED; import com.adeptj.runtime.common.BundleContextHolder; import com.adeptj.runtime.common.ServletContextHolder; import org.apache.commons.lang3.StringUtils; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkEvent; import org.osgi.framework.FrameworkListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.adeptj.runtime.common.Constants.ATTRIBUTE_BUNDLE_CONTEXT; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.osgi; /** * OSGi FrameworkListener which takes care of OSGi framework restart from Felix WebConsole. * * @author Rakesh.Kumar, AdeptJ */ public class FrameworkLifecycleListener implements FrameworkListener { private static final Logger LOGGER = LoggerFactory.getLogger(FrameworkLifecycleListener.class); private static final String SYS_PROP_LOG_FRAMEWORK_ERROR = "adeptj.rt.log.framework.error"; /** * Handles OSGi Framework restart, does following on System Bundle STARTED event. * <p> * 1. Removes the BundleContext from ServletContext attributes. <br> * 2. Gets the new BundleContext from System Bundle and sets that to ServletContext. <br> * 3. Closes the DispatcherServletTracker and open again with new BundleContext. <br> * 4. As the BundleContext is removed and added from ServletContext the corresponding BridgeServletContextAttributeListener * is fired with events which in turn closes the EventDispatcherTracker and opens again with new BundleContext. */ @Override public void frameworkEvent(FrameworkEvent event) { switch (event.getType()) { case STARTED: if (ServiceTrackers.getInstance().isDispatcherServletTrackerOpened()) { LOGGER.info("Handling OSGi Framework Restart!!"); BundleContext bundleContext = event.getBundle().getBundleContext();
BundleContextHolder.getInstance().setBundleContext(bundleContext);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/osgi/FrameworkLifecycleListener.java
// Path: src/main/java/com/adeptj/runtime/common/BundleContextHolder.java // public enum BundleContextHolder { // // INSTANCE; // // private BundleContext bundleContext; // // public BundleContext getBundleContext() { // return this.bundleContext; // } // // public void setBundleContext(BundleContext bundleContext) { // NOSONAR // this.bundleContext = bundleContext; // } // // public static BundleContextHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/common/ServletContextHolder.java // public enum ServletContextHolder { // // INSTANCE; // // private ServletContext context; // // public void setServletContext(ServletContext context) { // NOSONAR // if (this.context == null) { // this.context = context; // } // } // // public ServletContext getServletContext() { // return this.context; // } // // public <T> T getAttributeOfType(String name, Class<T> type) { // final Object value = this.context.getAttribute(name); // return type.isInstance(value) ? type.cast(value) : null; // } // // public static ServletContextHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String ATTRIBUTE_BUNDLE_CONTEXT = "org.osgi.framework.BundleContext";
import static org.osgi.framework.FrameworkEvent.ERROR; import static org.osgi.framework.FrameworkEvent.STARTED; import com.adeptj.runtime.common.BundleContextHolder; import com.adeptj.runtime.common.ServletContextHolder; import org.apache.commons.lang3.StringUtils; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkEvent; import org.osgi.framework.FrameworkListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.adeptj.runtime.common.Constants.ATTRIBUTE_BUNDLE_CONTEXT;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.osgi; /** * OSGi FrameworkListener which takes care of OSGi framework restart from Felix WebConsole. * * @author Rakesh.Kumar, AdeptJ */ public class FrameworkLifecycleListener implements FrameworkListener { private static final Logger LOGGER = LoggerFactory.getLogger(FrameworkLifecycleListener.class); private static final String SYS_PROP_LOG_FRAMEWORK_ERROR = "adeptj.rt.log.framework.error"; /** * Handles OSGi Framework restart, does following on System Bundle STARTED event. * <p> * 1. Removes the BundleContext from ServletContext attributes. <br> * 2. Gets the new BundleContext from System Bundle and sets that to ServletContext. <br> * 3. Closes the DispatcherServletTracker and open again with new BundleContext. <br> * 4. As the BundleContext is removed and added from ServletContext the corresponding BridgeServletContextAttributeListener * is fired with events which in turn closes the EventDispatcherTracker and opens again with new BundleContext. */ @Override public void frameworkEvent(FrameworkEvent event) { switch (event.getType()) { case STARTED: if (ServiceTrackers.getInstance().isDispatcherServletTrackerOpened()) { LOGGER.info("Handling OSGi Framework Restart!!"); BundleContext bundleContext = event.getBundle().getBundleContext(); BundleContextHolder.getInstance().setBundleContext(bundleContext); // Set the new BundleContext as a ServletContext attribute, remove the stale BundleContext.
// Path: src/main/java/com/adeptj/runtime/common/BundleContextHolder.java // public enum BundleContextHolder { // // INSTANCE; // // private BundleContext bundleContext; // // public BundleContext getBundleContext() { // return this.bundleContext; // } // // public void setBundleContext(BundleContext bundleContext) { // NOSONAR // this.bundleContext = bundleContext; // } // // public static BundleContextHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/common/ServletContextHolder.java // public enum ServletContextHolder { // // INSTANCE; // // private ServletContext context; // // public void setServletContext(ServletContext context) { // NOSONAR // if (this.context == null) { // this.context = context; // } // } // // public ServletContext getServletContext() { // return this.context; // } // // public <T> T getAttributeOfType(String name, Class<T> type) { // final Object value = this.context.getAttribute(name); // return type.isInstance(value) ? type.cast(value) : null; // } // // public static ServletContextHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String ATTRIBUTE_BUNDLE_CONTEXT = "org.osgi.framework.BundleContext"; // Path: src/main/java/com/adeptj/runtime/osgi/FrameworkLifecycleListener.java import static org.osgi.framework.FrameworkEvent.ERROR; import static org.osgi.framework.FrameworkEvent.STARTED; import com.adeptj.runtime.common.BundleContextHolder; import com.adeptj.runtime.common.ServletContextHolder; import org.apache.commons.lang3.StringUtils; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkEvent; import org.osgi.framework.FrameworkListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.adeptj.runtime.common.Constants.ATTRIBUTE_BUNDLE_CONTEXT; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.osgi; /** * OSGi FrameworkListener which takes care of OSGi framework restart from Felix WebConsole. * * @author Rakesh.Kumar, AdeptJ */ public class FrameworkLifecycleListener implements FrameworkListener { private static final Logger LOGGER = LoggerFactory.getLogger(FrameworkLifecycleListener.class); private static final String SYS_PROP_LOG_FRAMEWORK_ERROR = "adeptj.rt.log.framework.error"; /** * Handles OSGi Framework restart, does following on System Bundle STARTED event. * <p> * 1. Removes the BundleContext from ServletContext attributes. <br> * 2. Gets the new BundleContext from System Bundle and sets that to ServletContext. <br> * 3. Closes the DispatcherServletTracker and open again with new BundleContext. <br> * 4. As the BundleContext is removed and added from ServletContext the corresponding BridgeServletContextAttributeListener * is fired with events which in turn closes the EventDispatcherTracker and opens again with new BundleContext. */ @Override public void frameworkEvent(FrameworkEvent event) { switch (event.getType()) { case STARTED: if (ServiceTrackers.getInstance().isDispatcherServletTrackerOpened()) { LOGGER.info("Handling OSGi Framework Restart!!"); BundleContext bundleContext = event.getBundle().getBundleContext(); BundleContextHolder.getInstance().setBundleContext(bundleContext); // Set the new BundleContext as a ServletContext attribute, remove the stale BundleContext.
ServletContextHolder.getInstance()
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/osgi/FrameworkLifecycleListener.java
// Path: src/main/java/com/adeptj/runtime/common/BundleContextHolder.java // public enum BundleContextHolder { // // INSTANCE; // // private BundleContext bundleContext; // // public BundleContext getBundleContext() { // return this.bundleContext; // } // // public void setBundleContext(BundleContext bundleContext) { // NOSONAR // this.bundleContext = bundleContext; // } // // public static BundleContextHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/common/ServletContextHolder.java // public enum ServletContextHolder { // // INSTANCE; // // private ServletContext context; // // public void setServletContext(ServletContext context) { // NOSONAR // if (this.context == null) { // this.context = context; // } // } // // public ServletContext getServletContext() { // return this.context; // } // // public <T> T getAttributeOfType(String name, Class<T> type) { // final Object value = this.context.getAttribute(name); // return type.isInstance(value) ? type.cast(value) : null; // } // // public static ServletContextHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String ATTRIBUTE_BUNDLE_CONTEXT = "org.osgi.framework.BundleContext";
import static org.osgi.framework.FrameworkEvent.ERROR; import static org.osgi.framework.FrameworkEvent.STARTED; import com.adeptj.runtime.common.BundleContextHolder; import com.adeptj.runtime.common.ServletContextHolder; import org.apache.commons.lang3.StringUtils; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkEvent; import org.osgi.framework.FrameworkListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.adeptj.runtime.common.Constants.ATTRIBUTE_BUNDLE_CONTEXT;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.osgi; /** * OSGi FrameworkListener which takes care of OSGi framework restart from Felix WebConsole. * * @author Rakesh.Kumar, AdeptJ */ public class FrameworkLifecycleListener implements FrameworkListener { private static final Logger LOGGER = LoggerFactory.getLogger(FrameworkLifecycleListener.class); private static final String SYS_PROP_LOG_FRAMEWORK_ERROR = "adeptj.rt.log.framework.error"; /** * Handles OSGi Framework restart, does following on System Bundle STARTED event. * <p> * 1. Removes the BundleContext from ServletContext attributes. <br> * 2. Gets the new BundleContext from System Bundle and sets that to ServletContext. <br> * 3. Closes the DispatcherServletTracker and open again with new BundleContext. <br> * 4. As the BundleContext is removed and added from ServletContext the corresponding BridgeServletContextAttributeListener * is fired with events which in turn closes the EventDispatcherTracker and opens again with new BundleContext. */ @Override public void frameworkEvent(FrameworkEvent event) { switch (event.getType()) { case STARTED: if (ServiceTrackers.getInstance().isDispatcherServletTrackerOpened()) { LOGGER.info("Handling OSGi Framework Restart!!"); BundleContext bundleContext = event.getBundle().getBundleContext(); BundleContextHolder.getInstance().setBundleContext(bundleContext); // Set the new BundleContext as a ServletContext attribute, remove the stale BundleContext. ServletContextHolder.getInstance()
// Path: src/main/java/com/adeptj/runtime/common/BundleContextHolder.java // public enum BundleContextHolder { // // INSTANCE; // // private BundleContext bundleContext; // // public BundleContext getBundleContext() { // return this.bundleContext; // } // // public void setBundleContext(BundleContext bundleContext) { // NOSONAR // this.bundleContext = bundleContext; // } // // public static BundleContextHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/common/ServletContextHolder.java // public enum ServletContextHolder { // // INSTANCE; // // private ServletContext context; // // public void setServletContext(ServletContext context) { // NOSONAR // if (this.context == null) { // this.context = context; // } // } // // public ServletContext getServletContext() { // return this.context; // } // // public <T> T getAttributeOfType(String name, Class<T> type) { // final Object value = this.context.getAttribute(name); // return type.isInstance(value) ? type.cast(value) : null; // } // // public static ServletContextHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String ATTRIBUTE_BUNDLE_CONTEXT = "org.osgi.framework.BundleContext"; // Path: src/main/java/com/adeptj/runtime/osgi/FrameworkLifecycleListener.java import static org.osgi.framework.FrameworkEvent.ERROR; import static org.osgi.framework.FrameworkEvent.STARTED; import com.adeptj.runtime.common.BundleContextHolder; import com.adeptj.runtime.common.ServletContextHolder; import org.apache.commons.lang3.StringUtils; import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkEvent; import org.osgi.framework.FrameworkListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.adeptj.runtime.common.Constants.ATTRIBUTE_BUNDLE_CONTEXT; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.osgi; /** * OSGi FrameworkListener which takes care of OSGi framework restart from Felix WebConsole. * * @author Rakesh.Kumar, AdeptJ */ public class FrameworkLifecycleListener implements FrameworkListener { private static final Logger LOGGER = LoggerFactory.getLogger(FrameworkLifecycleListener.class); private static final String SYS_PROP_LOG_FRAMEWORK_ERROR = "adeptj.rt.log.framework.error"; /** * Handles OSGi Framework restart, does following on System Bundle STARTED event. * <p> * 1. Removes the BundleContext from ServletContext attributes. <br> * 2. Gets the new BundleContext from System Bundle and sets that to ServletContext. <br> * 3. Closes the DispatcherServletTracker and open again with new BundleContext. <br> * 4. As the BundleContext is removed and added from ServletContext the corresponding BridgeServletContextAttributeListener * is fired with events which in turn closes the EventDispatcherTracker and opens again with new BundleContext. */ @Override public void frameworkEvent(FrameworkEvent event) { switch (event.getType()) { case STARTED: if (ServiceTrackers.getInstance().isDispatcherServletTrackerOpened()) { LOGGER.info("Handling OSGi Framework Restart!!"); BundleContext bundleContext = event.getBundle().getBundleContext(); BundleContextHolder.getInstance().setBundleContext(bundleContext); // Set the new BundleContext as a ServletContext attribute, remove the stale BundleContext. ServletContextHolder.getInstance()
.getServletContext().setAttribute(ATTRIBUTE_BUNDLE_CONTEXT, bundleContext);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/server/CredentialMatcher.java
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String H2_MAP_ADMIN_CREDENTIALS = "adminCredentials"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String MV_CREDENTIALS_STORE = "credentials.dat";
import java.util.Arrays; import java.util.Base64; import static com.adeptj.runtime.common.Constants.H2_MAP_ADMIN_CREDENTIALS; import static com.adeptj.runtime.common.Constants.MV_CREDENTIALS_STORE; import static java.nio.charset.StandardCharsets.UTF_8; import io.undertow.security.idm.Credential; import io.undertow.security.idm.PasswordCredential; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.h2.mvstore.MVStore; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.server; /** * CredentialMatcher - utility creates an SHA-256 digest of the supplied password and matches with the one stored * in MVStore. * * @author Rakesh.Kumar, AdeptJ */ final class CredentialMatcher { private static final String SHA_256 = "SHA-256"; private CredentialMatcher() { } static boolean match(String username, Credential credential) { char[] inputPwd = ((PasswordCredential) credential).getPassword(); if (StringUtils.isEmpty(username) || ArrayUtils.isEmpty(inputPwd)) { return false; } byte[] inputPwdBytes = null; byte[] digest = null; byte[] storedPwdBytes = null;
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String H2_MAP_ADMIN_CREDENTIALS = "adminCredentials"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String MV_CREDENTIALS_STORE = "credentials.dat"; // Path: src/main/java/com/adeptj/runtime/server/CredentialMatcher.java import java.util.Arrays; import java.util.Base64; import static com.adeptj.runtime.common.Constants.H2_MAP_ADMIN_CREDENTIALS; import static com.adeptj.runtime.common.Constants.MV_CREDENTIALS_STORE; import static java.nio.charset.StandardCharsets.UTF_8; import io.undertow.security.idm.Credential; import io.undertow.security.idm.PasswordCredential; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.h2.mvstore.MVStore; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.server; /** * CredentialMatcher - utility creates an SHA-256 digest of the supplied password and matches with the one stored * in MVStore. * * @author Rakesh.Kumar, AdeptJ */ final class CredentialMatcher { private static final String SHA_256 = "SHA-256"; private CredentialMatcher() { } static boolean match(String username, Credential credential) { char[] inputPwd = ((PasswordCredential) credential).getPassword(); if (StringUtils.isEmpty(username) || ArrayUtils.isEmpty(inputPwd)) { return false; } byte[] inputPwdBytes = null; byte[] digest = null; byte[] storedPwdBytes = null;
try (MVStore store = MVStore.open(MV_CREDENTIALS_STORE)) {
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/server/CredentialMatcher.java
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String H2_MAP_ADMIN_CREDENTIALS = "adminCredentials"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String MV_CREDENTIALS_STORE = "credentials.dat";
import java.util.Arrays; import java.util.Base64; import static com.adeptj.runtime.common.Constants.H2_MAP_ADMIN_CREDENTIALS; import static com.adeptj.runtime.common.Constants.MV_CREDENTIALS_STORE; import static java.nio.charset.StandardCharsets.UTF_8; import io.undertow.security.idm.Credential; import io.undertow.security.idm.PasswordCredential; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.h2.mvstore.MVStore; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.server; /** * CredentialMatcher - utility creates an SHA-256 digest of the supplied password and matches with the one stored * in MVStore. * * @author Rakesh.Kumar, AdeptJ */ final class CredentialMatcher { private static final String SHA_256 = "SHA-256"; private CredentialMatcher() { } static boolean match(String username, Credential credential) { char[] inputPwd = ((PasswordCredential) credential).getPassword(); if (StringUtils.isEmpty(username) || ArrayUtils.isEmpty(inputPwd)) { return false; } byte[] inputPwdBytes = null; byte[] digest = null; byte[] storedPwdBytes = null; try (MVStore store = MVStore.open(MV_CREDENTIALS_STORE)) {
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String H2_MAP_ADMIN_CREDENTIALS = "adminCredentials"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String MV_CREDENTIALS_STORE = "credentials.dat"; // Path: src/main/java/com/adeptj/runtime/server/CredentialMatcher.java import java.util.Arrays; import java.util.Base64; import static com.adeptj.runtime.common.Constants.H2_MAP_ADMIN_CREDENTIALS; import static com.adeptj.runtime.common.Constants.MV_CREDENTIALS_STORE; import static java.nio.charset.StandardCharsets.UTF_8; import io.undertow.security.idm.Credential; import io.undertow.security.idm.PasswordCredential; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.h2.mvstore.MVStore; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.server; /** * CredentialMatcher - utility creates an SHA-256 digest of the supplied password and matches with the one stored * in MVStore. * * @author Rakesh.Kumar, AdeptJ */ final class CredentialMatcher { private static final String SHA_256 = "SHA-256"; private CredentialMatcher() { } static boolean match(String username, Credential credential) { char[] inputPwd = ((PasswordCredential) credential).getPassword(); if (StringUtils.isEmpty(username) || ArrayUtils.isEmpty(inputPwd)) { return false; } byte[] inputPwdBytes = null; byte[] digest = null; byte[] storedPwdBytes = null; try (MVStore store = MVStore.open(MV_CREDENTIALS_STORE)) {
String storedPwd = (String) store.openMap(H2_MAP_ADMIN_CREDENTIALS).get(username);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/server/ServerOptions.java
// Path: src/main/java/com/adeptj/runtime/common/Times.java // public final class Times { // // // No instances, just utility methods. // private Times() { // } // // /** // * Returns elapsed time in milliseconds from the provided time in nanoseconds. // * // * @param startTime time in nanoseconds // * @return elapsed time in milliseconds // */ // public static long elapsedMillis(final long startTime) { // return NANOSECONDS.toMillis(System.nanoTime() - startTime); // } // // /** // * Returns elapsed time in seconds from the provided time in milliseconds. // * // * @param startTime time in milliseconds // * @return elapsed time in seconds // */ // public static long elapsedSeconds(final long startTime) { // return MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime); // } // }
import io.undertow.Undertow.Builder; import com.adeptj.runtime.common.Times; import com.typesafe.config.Config;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.server; /** * UNDERTOW Server Options. * * @author Rakesh.Kumar, AdeptJ */ final class ServerOptions extends BaseOptions { private static final String SERVER_OPTIONS = "server-options"; private static final String OPTIONS_TYPE_OTHERS = "options-type-others"; private static final String OPTIONS_TYPE_LONG = "options-type-long"; /** * Configures the server options dynamically. * * @param builder Undertow.Builder * @param undertowConfig Undertow Typesafe Config */ @Override void setOptions(Builder builder, Config undertowConfig) { long startTime = System.nanoTime(); Config serverOptionsCfg = undertowConfig.getConfig(SERVER_OPTIONS); serverOptionsCfg.getObject(OPTIONS_TYPE_OTHERS) .unwrapped() .forEach((key, val) -> builder.setServerOption(this.getOption(key), val)); serverOptionsCfg.getObject(OPTIONS_TYPE_LONG) .unwrapped() .forEach((key, val) -> builder.setServerOption(this.getOption(key), Long.valueOf((Integer) val)));
// Path: src/main/java/com/adeptj/runtime/common/Times.java // public final class Times { // // // No instances, just utility methods. // private Times() { // } // // /** // * Returns elapsed time in milliseconds from the provided time in nanoseconds. // * // * @param startTime time in nanoseconds // * @return elapsed time in milliseconds // */ // public static long elapsedMillis(final long startTime) { // return NANOSECONDS.toMillis(System.nanoTime() - startTime); // } // // /** // * Returns elapsed time in seconds from the provided time in milliseconds. // * // * @param startTime time in milliseconds // * @return elapsed time in seconds // */ // public static long elapsedSeconds(final long startTime) { // return MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime); // } // } // Path: src/main/java/com/adeptj/runtime/server/ServerOptions.java import io.undertow.Undertow.Builder; import com.adeptj.runtime.common.Times; import com.typesafe.config.Config; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.server; /** * UNDERTOW Server Options. * * @author Rakesh.Kumar, AdeptJ */ final class ServerOptions extends BaseOptions { private static final String SERVER_OPTIONS = "server-options"; private static final String OPTIONS_TYPE_OTHERS = "options-type-others"; private static final String OPTIONS_TYPE_LONG = "options-type-long"; /** * Configures the server options dynamically. * * @param builder Undertow.Builder * @param undertowConfig Undertow Typesafe Config */ @Override void setOptions(Builder builder, Config undertowConfig) { long startTime = System.nanoTime(); Config serverOptionsCfg = undertowConfig.getConfig(SERVER_OPTIONS); serverOptionsCfg.getObject(OPTIONS_TYPE_OTHERS) .unwrapped() .forEach((key, val) -> builder.setServerOption(this.getOption(key), val)); serverOptionsCfg.getObject(OPTIONS_TYPE_LONG) .unwrapped() .forEach((key, val) -> builder.setServerOption(this.getOption(key), Long.valueOf((Integer) val)));
this.logger.info("Undertow ServerOptions configured in [{}] ms!!", Times.elapsedMillis(startTime));
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/common/KeyStores.java
// Path: src/main/java/com/adeptj/runtime/exception/RuntimeInitializationException.java // public class RuntimeInitializationException extends RuntimeException { // // private static final long serialVersionUID = 6443421220206654015L; // // public RuntimeInitializationException(Throwable cause) { // super(cause); // } // }
import com.adeptj.runtime.exception.RuntimeInitializationException; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.security.GeneralSecurityException; import java.security.KeyStore;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utilities for Java KeyStore. * * @author Rakesh.Kumar, AdeptJ */ final class KeyStores { private KeyStores() { } static KeyStore getKeyStore(boolean p12FileExternal, String type, String p12Loc, char[] p12Pwd) { try (InputStream is = p12FileExternal ? Files.newInputStream(Paths.get(p12Loc)) : KeyStores.class.getResourceAsStream(p12Loc)) { KeyStore keyStore = KeyStore.getInstance(type); keyStore.load(is, p12Pwd); return keyStore; } catch (IOException | GeneralSecurityException ex) {
// Path: src/main/java/com/adeptj/runtime/exception/RuntimeInitializationException.java // public class RuntimeInitializationException extends RuntimeException { // // private static final long serialVersionUID = 6443421220206654015L; // // public RuntimeInitializationException(Throwable cause) { // super(cause); // } // } // Path: src/main/java/com/adeptj/runtime/common/KeyStores.java import com.adeptj.runtime.exception.RuntimeInitializationException; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.security.GeneralSecurityException; import java.security.KeyStore; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utilities for Java KeyStore. * * @author Rakesh.Kumar, AdeptJ */ final class KeyStores { private KeyStores() { } static KeyStore getKeyStore(boolean p12FileExternal, String type, String p12Loc, char[] p12Pwd) { try (InputStream is = p12FileExternal ? Files.newInputStream(Paths.get(p12Loc)) : KeyStores.class.getResourceAsStream(p12Loc)) { KeyStore keyStore = KeyStore.getInstance(type); keyStore.load(is, p12Pwd); return keyStore; } catch (IOException | GeneralSecurityException ex) {
throw new RuntimeInitializationException(ex);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/osgi/DispatcherServletWrapper.java
// Path: src/main/java/com/adeptj/runtime/common/Times.java // public final class Times { // // // No instances, just utility methods. // private Times() { // } // // /** // * Returns elapsed time in milliseconds from the provided time in nanoseconds. // * // * @param startTime time in nanoseconds // * @return elapsed time in milliseconds // */ // public static long elapsedMillis(final long startTime) { // return NANOSECONDS.toMillis(System.nanoTime() - startTime); // } // // /** // * Returns elapsed time in seconds from the provided time in milliseconds. // * // * @param startTime time in milliseconds // * @return elapsed time in seconds // */ // public static long elapsedSeconds(final long startTime) { // return MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime); // } // }
import com.adeptj.runtime.common.Times; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet; import java.io.IOException;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.osgi; /** * {@link HttpServlet} wrapper for Felix {@link org.apache.felix.http.base.internal.dispatch.DispatcherServlet}. * * @author Rakesh.Kumar, AdeptJ */ public class DispatcherServletWrapper extends HttpServlet { private static final long serialVersionUID = 282686082848634854L; private static final Logger LOGGER = LoggerFactory.getLogger(DispatcherServletWrapper.class); /** * The Felix {@link org.apache.felix.http.base.internal.dispatch.DispatcherServlet} */ private final HttpServlet dispatcherServlet; DispatcherServletWrapper(HttpServlet dispatcherServlet) { this.dispatcherServlet = dispatcherServlet; } @Override public void init(ServletConfig config) throws ServletException { long startTime = System.nanoTime(); super.init(config); this.dispatcherServlet.init(config);
// Path: src/main/java/com/adeptj/runtime/common/Times.java // public final class Times { // // // No instances, just utility methods. // private Times() { // } // // /** // * Returns elapsed time in milliseconds from the provided time in nanoseconds. // * // * @param startTime time in nanoseconds // * @return elapsed time in milliseconds // */ // public static long elapsedMillis(final long startTime) { // return NANOSECONDS.toMillis(System.nanoTime() - startTime); // } // // /** // * Returns elapsed time in seconds from the provided time in milliseconds. // * // * @param startTime time in milliseconds // * @return elapsed time in seconds // */ // public static long elapsedSeconds(final long startTime) { // return MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime); // } // } // Path: src/main/java/com/adeptj/runtime/osgi/DispatcherServletWrapper.java import com.adeptj.runtime.common.Times; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServlet; import java.io.IOException; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.osgi; /** * {@link HttpServlet} wrapper for Felix {@link org.apache.felix.http.base.internal.dispatch.DispatcherServlet}. * * @author Rakesh.Kumar, AdeptJ */ public class DispatcherServletWrapper extends HttpServlet { private static final long serialVersionUID = 282686082848634854L; private static final Logger LOGGER = LoggerFactory.getLogger(DispatcherServletWrapper.class); /** * The Felix {@link org.apache.felix.http.base.internal.dispatch.DispatcherServlet} */ private final HttpServlet dispatcherServlet; DispatcherServletWrapper(HttpServlet dispatcherServlet) { this.dispatcherServlet = dispatcherServlet; } @Override public void init(ServletConfig config) throws ServletException { long startTime = System.nanoTime(); super.init(config); this.dispatcherServlet.init(config);
LOGGER.info("Felix DispatcherServlet initialized in [{}] ms!!", Times.elapsedMillis(startTime));
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/osgi/BridgeServiceTracker.java
// Path: src/main/java/com/adeptj/runtime/common/OSGiUtil.java // public final class OSGiUtil { // // private static final String FILTER_AND = "(&("; // // private static final String EQ = "="; // // private static final String ASTERISK = "*"; // // private static final String PARENTHESIS_OPEN = "("; // // private static final String PARENTHESIS_CLOSE = ")"; // // // No instantiation. Utility methods only. // private OSGiUtil() { // } // // public static boolean isNotFragment(Bundle bundle) { // return bundle.getHeaders().get(FRAGMENT_HOST) == null; // } // // public static boolean isSystemBundleFragment(Bundle bundle) { // return StringUtils.contains(bundle.getHeaders().get(FRAGMENT_HOST), EXTENSION_DIRECTIVE); // } // // public static boolean isNotBundle(Manifest manifest) { // return manifest != null && StringUtils.isEmpty(manifest.getMainAttributes().getValue(BUNDLE_SYMBOLICNAME)); // } // // public static Filter filter(BundleContext context, String objectClassFQN) { // try { // return context.createFilter(PARENTHESIS_OPEN + // OBJECTCLASS + // EQ + // objectClassFQN + // PARENTHESIS_CLOSE); // } catch (InvalidSyntaxException ex) { // // Filter expression is malformed, not RFC-1960 based Filter. // throw new IllegalArgumentException(ex); // } // } // // public static Filter filter(BundleContext context, Class<?> objectClass, String filterExpr) { // try { // return context.createFilter(FILTER_AND + // OBJECTCLASS + // EQ + // objectClass.getName() + // PARENTHESIS_CLOSE + // filterExpr + // PARENTHESIS_CLOSE); // } catch (InvalidSyntaxException ex) { // // Filter expression is malformed, not RFC-1960 based Filter. // throw new IllegalArgumentException(ex); // } // } // // public static Filter anyServiceFilter(BundleContext context, String filterExpr) { // try { // return context.createFilter(FILTER_AND + // OBJECTCLASS + // EQ + // ASTERISK + // PARENTHESIS_CLOSE + // filterExpr + // PARENTHESIS_CLOSE); // } catch (InvalidSyntaxException ex) { // // Filter expression is malformed, not RFC-1960 based Filter. // throw new IllegalArgumentException(ex); // } // } // // public static void unregisterService(ServiceRegistration<?> registration) { // Optional.ofNullable(registration).ifPresent(ServiceRegistration::unregister); // } // // public static String getServiceDesc(ServiceReference<?> reference) { // return getString(reference, SERVICE_DESCRIPTION); // } // // public static String getString(ServiceReference<?> reference, String key) { // return (String) reference.getProperty(key); // } // // public static boolean getBoolean(ServiceReference<?> reference, String key) { // return (boolean) reference.getProperty(key); // } // // public static Set<String> arrayToSet(ServiceReference<?> reference, String key) { // // Not doing any type check as the property has to be an array type suggested by method name itself. // return Stream.of((String[]) reference.getProperty(key)) // .filter(StringUtils::isNotBlank) // .map(String::trim) // .collect(Collectors.toSet()); // } // }
import com.adeptj.runtime.common.OSGiUtil; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.util.tracker.ServiceTracker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.atomic.AtomicBoolean;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.osgi; /** * Boilerplate for {@link DispatcherServletTracker} and {@link EventDispatcherTracker} * * @author Rakesh.Kumar, AdeptJ */ public abstract class BridgeServiceTracker<T> extends ServiceTracker<T, T> { private static final Logger LOGGER = LoggerFactory.getLogger(BridgeServiceTracker.class); private static final String DISPATCHER_SERVICE_FILTER = "(http.felix.dispatcher=*)"; /** * This is to prevent {@link IllegalStateException} : Invalid {@link BundleContext} when service is removed and * then added again on framework restart using the stale {@link BundleContext}. * <p> * This is registered again using the fresh {@link BundleContext} obtained via {@link FrameworkLifecycleListener} */ private final AtomicBoolean serviceRemoved; BridgeServiceTracker(BundleContext context, Class<T> objectClass) {
// Path: src/main/java/com/adeptj/runtime/common/OSGiUtil.java // public final class OSGiUtil { // // private static final String FILTER_AND = "(&("; // // private static final String EQ = "="; // // private static final String ASTERISK = "*"; // // private static final String PARENTHESIS_OPEN = "("; // // private static final String PARENTHESIS_CLOSE = ")"; // // // No instantiation. Utility methods only. // private OSGiUtil() { // } // // public static boolean isNotFragment(Bundle bundle) { // return bundle.getHeaders().get(FRAGMENT_HOST) == null; // } // // public static boolean isSystemBundleFragment(Bundle bundle) { // return StringUtils.contains(bundle.getHeaders().get(FRAGMENT_HOST), EXTENSION_DIRECTIVE); // } // // public static boolean isNotBundle(Manifest manifest) { // return manifest != null && StringUtils.isEmpty(manifest.getMainAttributes().getValue(BUNDLE_SYMBOLICNAME)); // } // // public static Filter filter(BundleContext context, String objectClassFQN) { // try { // return context.createFilter(PARENTHESIS_OPEN + // OBJECTCLASS + // EQ + // objectClassFQN + // PARENTHESIS_CLOSE); // } catch (InvalidSyntaxException ex) { // // Filter expression is malformed, not RFC-1960 based Filter. // throw new IllegalArgumentException(ex); // } // } // // public static Filter filter(BundleContext context, Class<?> objectClass, String filterExpr) { // try { // return context.createFilter(FILTER_AND + // OBJECTCLASS + // EQ + // objectClass.getName() + // PARENTHESIS_CLOSE + // filterExpr + // PARENTHESIS_CLOSE); // } catch (InvalidSyntaxException ex) { // // Filter expression is malformed, not RFC-1960 based Filter. // throw new IllegalArgumentException(ex); // } // } // // public static Filter anyServiceFilter(BundleContext context, String filterExpr) { // try { // return context.createFilter(FILTER_AND + // OBJECTCLASS + // EQ + // ASTERISK + // PARENTHESIS_CLOSE + // filterExpr + // PARENTHESIS_CLOSE); // } catch (InvalidSyntaxException ex) { // // Filter expression is malformed, not RFC-1960 based Filter. // throw new IllegalArgumentException(ex); // } // } // // public static void unregisterService(ServiceRegistration<?> registration) { // Optional.ofNullable(registration).ifPresent(ServiceRegistration::unregister); // } // // public static String getServiceDesc(ServiceReference<?> reference) { // return getString(reference, SERVICE_DESCRIPTION); // } // // public static String getString(ServiceReference<?> reference, String key) { // return (String) reference.getProperty(key); // } // // public static boolean getBoolean(ServiceReference<?> reference, String key) { // return (boolean) reference.getProperty(key); // } // // public static Set<String> arrayToSet(ServiceReference<?> reference, String key) { // // Not doing any type check as the property has to be an array type suggested by method name itself. // return Stream.of((String[]) reference.getProperty(key)) // .filter(StringUtils::isNotBlank) // .map(String::trim) // .collect(Collectors.toSet()); // } // } // Path: src/main/java/com/adeptj/runtime/osgi/BridgeServiceTracker.java import com.adeptj.runtime.common.OSGiUtil; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.util.tracker.ServiceTracker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.atomic.AtomicBoolean; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.osgi; /** * Boilerplate for {@link DispatcherServletTracker} and {@link EventDispatcherTracker} * * @author Rakesh.Kumar, AdeptJ */ public abstract class BridgeServiceTracker<T> extends ServiceTracker<T, T> { private static final Logger LOGGER = LoggerFactory.getLogger(BridgeServiceTracker.class); private static final String DISPATCHER_SERVICE_FILTER = "(http.felix.dispatcher=*)"; /** * This is to prevent {@link IllegalStateException} : Invalid {@link BundleContext} when service is removed and * then added again on framework restart using the stale {@link BundleContext}. * <p> * This is registered again using the fresh {@link BundleContext} obtained via {@link FrameworkLifecycleListener} */ private final AtomicBoolean serviceRemoved; BridgeServiceTracker(BundleContext context, Class<T> objectClass) {
super(context, OSGiUtil.filter(context, objectClass, DISPATCHER_SERVICE_FILTER), null);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/logging/LogbackInitializer.java
// Path: src/main/java/com/adeptj/runtime/common/LogbackManagerHolder.java // public enum LogbackManagerHolder { // // INSTANCE; // // private LogbackManager logbackManager; // // public void setLogbackManager(LogbackManager logbackManager) { // if (this.logbackManager == null) { // this.logbackManager = logbackManager; // } // } // // public LogbackManager getLogbackManager() { // return this.logbackManager; // } // // public static LogbackManagerHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/common/Times.java // public final class Times { // // // No instances, just utility methods. // private Times() { // } // // /** // * Returns elapsed time in milliseconds from the provided time in nanoseconds. // * // * @param startTime time in nanoseconds // * @return elapsed time in milliseconds // */ // public static long elapsedMillis(final long startTime) { // return NANOSECONDS.toMillis(System.nanoTime() - startTime); // } // // /** // * Returns elapsed time in seconds from the provided time in milliseconds. // * // * @param startTime time in milliseconds // * @return elapsed time in seconds // */ // public static long elapsedSeconds(final long startTime) { // return MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime); // } // } // // Path: src/main/java/com/adeptj/runtime/config/Configs.java // public enum Configs { // // INSTANCE; // // /** // * This will include system properties as well. // */ // private final Config root; // // Configs() { // this.root = this.loadConf(); // } // // public Config root() { // return this.root; // } // // public Config main() { // return this.root.getConfig(MAIN_CONF_SECTION); // } // // public Config undertow() { // return this.main().getConfig(UNDERTOW_CONF_SECTION); // } // // public Config felix() { // return this.main().getConfig(FELIX_CONF_SECTION); // } // // public Config common() { // return this.main().getConfig(COMMON_CONF_SECTION); // } // // public Config logging() { // return this.main().getConfig(LOGGING_CONF_SECTION); // } // // public Config trimou() { // return this.main().getConfig(TRIMOU_CONF_SECTION); // } // // public Config resteasy() { // return this.main().getConfig(RESTEASY_CONF_SECTION); // } // // private Config loadConf() { // Config config; // File configFile = Environment.getServerConfPath().toFile(); // if (configFile.exists()) { // // if overwrite.server.conf.file system property is provided, then load the configs from classpath. // if (Boolean.getBoolean(SYS_PROP_OVERWRITE_SERVER_CONF)) { // config = ConfigFactory.load(SERVER_CONF_FILE); // } else { // config = ConfigFactory.parseFile(configFile) // .withFallback(ConfigFactory.systemProperties()) // .resolve(); // } // } else { // config = ConfigFactory.load(SERVER_CONF_FILE); // } // return config; // } // // public static Configs of() { // return INSTANCE; // } // // }
import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.spi.Configurator; import ch.qos.logback.core.spi.ContextAwareBase; import ch.qos.logback.core.util.StatusPrinter; import com.adeptj.runtime.common.LogbackManagerHolder; import com.adeptj.runtime.common.Times; import com.adeptj.runtime.config.Configs; import com.typesafe.config.Config; import org.slf4j.bridge.SLF4JBridgeHandler;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.logging; /** * This Class initializes the Logback logging framework. * <p> * Usually Logback is initialized via logback.xml file on CLASSPATH. * But using that approach Logback takes longer to initialize(5+ seconds) which is reduced drastically * to ~ 200 milliseconds using programmatic approach. * <p> * This is huge improvement on total startup time. * * @author Rakesh.Kumar, AdeptJ */ public final class LogbackInitializer extends ContextAwareBase implements Configurator { private static final String LOGBACK_INIT_MSG = "Logback initialized in [{}] ms!!"; /** * See class description for details. * * @param loggerContext the {@link LoggerContext} */ @Override public void configure(LoggerContext loggerContext) { long startTime = System.nanoTime();
// Path: src/main/java/com/adeptj/runtime/common/LogbackManagerHolder.java // public enum LogbackManagerHolder { // // INSTANCE; // // private LogbackManager logbackManager; // // public void setLogbackManager(LogbackManager logbackManager) { // if (this.logbackManager == null) { // this.logbackManager = logbackManager; // } // } // // public LogbackManager getLogbackManager() { // return this.logbackManager; // } // // public static LogbackManagerHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/common/Times.java // public final class Times { // // // No instances, just utility methods. // private Times() { // } // // /** // * Returns elapsed time in milliseconds from the provided time in nanoseconds. // * // * @param startTime time in nanoseconds // * @return elapsed time in milliseconds // */ // public static long elapsedMillis(final long startTime) { // return NANOSECONDS.toMillis(System.nanoTime() - startTime); // } // // /** // * Returns elapsed time in seconds from the provided time in milliseconds. // * // * @param startTime time in milliseconds // * @return elapsed time in seconds // */ // public static long elapsedSeconds(final long startTime) { // return MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime); // } // } // // Path: src/main/java/com/adeptj/runtime/config/Configs.java // public enum Configs { // // INSTANCE; // // /** // * This will include system properties as well. // */ // private final Config root; // // Configs() { // this.root = this.loadConf(); // } // // public Config root() { // return this.root; // } // // public Config main() { // return this.root.getConfig(MAIN_CONF_SECTION); // } // // public Config undertow() { // return this.main().getConfig(UNDERTOW_CONF_SECTION); // } // // public Config felix() { // return this.main().getConfig(FELIX_CONF_SECTION); // } // // public Config common() { // return this.main().getConfig(COMMON_CONF_SECTION); // } // // public Config logging() { // return this.main().getConfig(LOGGING_CONF_SECTION); // } // // public Config trimou() { // return this.main().getConfig(TRIMOU_CONF_SECTION); // } // // public Config resteasy() { // return this.main().getConfig(RESTEASY_CONF_SECTION); // } // // private Config loadConf() { // Config config; // File configFile = Environment.getServerConfPath().toFile(); // if (configFile.exists()) { // // if overwrite.server.conf.file system property is provided, then load the configs from classpath. // if (Boolean.getBoolean(SYS_PROP_OVERWRITE_SERVER_CONF)) { // config = ConfigFactory.load(SERVER_CONF_FILE); // } else { // config = ConfigFactory.parseFile(configFile) // .withFallback(ConfigFactory.systemProperties()) // .resolve(); // } // } else { // config = ConfigFactory.load(SERVER_CONF_FILE); // } // return config; // } // // public static Configs of() { // return INSTANCE; // } // // } // Path: src/main/java/com/adeptj/runtime/logging/LogbackInitializer.java import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.spi.Configurator; import ch.qos.logback.core.spi.ContextAwareBase; import ch.qos.logback.core.util.StatusPrinter; import com.adeptj.runtime.common.LogbackManagerHolder; import com.adeptj.runtime.common.Times; import com.adeptj.runtime.config.Configs; import com.typesafe.config.Config; import org.slf4j.bridge.SLF4JBridgeHandler; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.logging; /** * This Class initializes the Logback logging framework. * <p> * Usually Logback is initialized via logback.xml file on CLASSPATH. * But using that approach Logback takes longer to initialize(5+ seconds) which is reduced drastically * to ~ 200 milliseconds using programmatic approach. * <p> * This is huge improvement on total startup time. * * @author Rakesh.Kumar, AdeptJ */ public final class LogbackInitializer extends ContextAwareBase implements Configurator { private static final String LOGBACK_INIT_MSG = "Logback initialized in [{}] ms!!"; /** * See class description for details. * * @param loggerContext the {@link LoggerContext} */ @Override public void configure(LoggerContext loggerContext) { long startTime = System.nanoTime();
Config loggingCfg = Configs.of().logging();
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/logging/LogbackInitializer.java
// Path: src/main/java/com/adeptj/runtime/common/LogbackManagerHolder.java // public enum LogbackManagerHolder { // // INSTANCE; // // private LogbackManager logbackManager; // // public void setLogbackManager(LogbackManager logbackManager) { // if (this.logbackManager == null) { // this.logbackManager = logbackManager; // } // } // // public LogbackManager getLogbackManager() { // return this.logbackManager; // } // // public static LogbackManagerHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/common/Times.java // public final class Times { // // // No instances, just utility methods. // private Times() { // } // // /** // * Returns elapsed time in milliseconds from the provided time in nanoseconds. // * // * @param startTime time in nanoseconds // * @return elapsed time in milliseconds // */ // public static long elapsedMillis(final long startTime) { // return NANOSECONDS.toMillis(System.nanoTime() - startTime); // } // // /** // * Returns elapsed time in seconds from the provided time in milliseconds. // * // * @param startTime time in milliseconds // * @return elapsed time in seconds // */ // public static long elapsedSeconds(final long startTime) { // return MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime); // } // } // // Path: src/main/java/com/adeptj/runtime/config/Configs.java // public enum Configs { // // INSTANCE; // // /** // * This will include system properties as well. // */ // private final Config root; // // Configs() { // this.root = this.loadConf(); // } // // public Config root() { // return this.root; // } // // public Config main() { // return this.root.getConfig(MAIN_CONF_SECTION); // } // // public Config undertow() { // return this.main().getConfig(UNDERTOW_CONF_SECTION); // } // // public Config felix() { // return this.main().getConfig(FELIX_CONF_SECTION); // } // // public Config common() { // return this.main().getConfig(COMMON_CONF_SECTION); // } // // public Config logging() { // return this.main().getConfig(LOGGING_CONF_SECTION); // } // // public Config trimou() { // return this.main().getConfig(TRIMOU_CONF_SECTION); // } // // public Config resteasy() { // return this.main().getConfig(RESTEASY_CONF_SECTION); // } // // private Config loadConf() { // Config config; // File configFile = Environment.getServerConfPath().toFile(); // if (configFile.exists()) { // // if overwrite.server.conf.file system property is provided, then load the configs from classpath. // if (Boolean.getBoolean(SYS_PROP_OVERWRITE_SERVER_CONF)) { // config = ConfigFactory.load(SERVER_CONF_FILE); // } else { // config = ConfigFactory.parseFile(configFile) // .withFallback(ConfigFactory.systemProperties()) // .resolve(); // } // } else { // config = ConfigFactory.load(SERVER_CONF_FILE); // } // return config; // } // // public static Configs of() { // return INSTANCE; // } // // }
import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.spi.Configurator; import ch.qos.logback.core.spi.ContextAwareBase; import ch.qos.logback.core.util.StatusPrinter; import com.adeptj.runtime.common.LogbackManagerHolder; import com.adeptj.runtime.common.Times; import com.adeptj.runtime.config.Configs; import com.typesafe.config.Config; import org.slf4j.bridge.SLF4JBridgeHandler;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.logging; /** * This Class initializes the Logback logging framework. * <p> * Usually Logback is initialized via logback.xml file on CLASSPATH. * But using that approach Logback takes longer to initialize(5+ seconds) which is reduced drastically * to ~ 200 milliseconds using programmatic approach. * <p> * This is huge improvement on total startup time. * * @author Rakesh.Kumar, AdeptJ */ public final class LogbackInitializer extends ContextAwareBase implements Configurator { private static final String LOGBACK_INIT_MSG = "Logback initialized in [{}] ms!!"; /** * See class description for details. * * @param loggerContext the {@link LoggerContext} */ @Override public void configure(LoggerContext loggerContext) { long startTime = System.nanoTime(); Config loggingCfg = Configs.of().logging(); LogbackManager logbackManager = new LogbackManager(loggerContext);
// Path: src/main/java/com/adeptj/runtime/common/LogbackManagerHolder.java // public enum LogbackManagerHolder { // // INSTANCE; // // private LogbackManager logbackManager; // // public void setLogbackManager(LogbackManager logbackManager) { // if (this.logbackManager == null) { // this.logbackManager = logbackManager; // } // } // // public LogbackManager getLogbackManager() { // return this.logbackManager; // } // // public static LogbackManagerHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/common/Times.java // public final class Times { // // // No instances, just utility methods. // private Times() { // } // // /** // * Returns elapsed time in milliseconds from the provided time in nanoseconds. // * // * @param startTime time in nanoseconds // * @return elapsed time in milliseconds // */ // public static long elapsedMillis(final long startTime) { // return NANOSECONDS.toMillis(System.nanoTime() - startTime); // } // // /** // * Returns elapsed time in seconds from the provided time in milliseconds. // * // * @param startTime time in milliseconds // * @return elapsed time in seconds // */ // public static long elapsedSeconds(final long startTime) { // return MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime); // } // } // // Path: src/main/java/com/adeptj/runtime/config/Configs.java // public enum Configs { // // INSTANCE; // // /** // * This will include system properties as well. // */ // private final Config root; // // Configs() { // this.root = this.loadConf(); // } // // public Config root() { // return this.root; // } // // public Config main() { // return this.root.getConfig(MAIN_CONF_SECTION); // } // // public Config undertow() { // return this.main().getConfig(UNDERTOW_CONF_SECTION); // } // // public Config felix() { // return this.main().getConfig(FELIX_CONF_SECTION); // } // // public Config common() { // return this.main().getConfig(COMMON_CONF_SECTION); // } // // public Config logging() { // return this.main().getConfig(LOGGING_CONF_SECTION); // } // // public Config trimou() { // return this.main().getConfig(TRIMOU_CONF_SECTION); // } // // public Config resteasy() { // return this.main().getConfig(RESTEASY_CONF_SECTION); // } // // private Config loadConf() { // Config config; // File configFile = Environment.getServerConfPath().toFile(); // if (configFile.exists()) { // // if overwrite.server.conf.file system property is provided, then load the configs from classpath. // if (Boolean.getBoolean(SYS_PROP_OVERWRITE_SERVER_CONF)) { // config = ConfigFactory.load(SERVER_CONF_FILE); // } else { // config = ConfigFactory.parseFile(configFile) // .withFallback(ConfigFactory.systemProperties()) // .resolve(); // } // } else { // config = ConfigFactory.load(SERVER_CONF_FILE); // } // return config; // } // // public static Configs of() { // return INSTANCE; // } // // } // Path: src/main/java/com/adeptj/runtime/logging/LogbackInitializer.java import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.spi.Configurator; import ch.qos.logback.core.spi.ContextAwareBase; import ch.qos.logback.core.util.StatusPrinter; import com.adeptj.runtime.common.LogbackManagerHolder; import com.adeptj.runtime.common.Times; import com.adeptj.runtime.config.Configs; import com.typesafe.config.Config; import org.slf4j.bridge.SLF4JBridgeHandler; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.logging; /** * This Class initializes the Logback logging framework. * <p> * Usually Logback is initialized via logback.xml file on CLASSPATH. * But using that approach Logback takes longer to initialize(5+ seconds) which is reduced drastically * to ~ 200 milliseconds using programmatic approach. * <p> * This is huge improvement on total startup time. * * @author Rakesh.Kumar, AdeptJ */ public final class LogbackInitializer extends ContextAwareBase implements Configurator { private static final String LOGBACK_INIT_MSG = "Logback initialized in [{}] ms!!"; /** * See class description for details. * * @param loggerContext the {@link LoggerContext} */ @Override public void configure(LoggerContext loggerContext) { long startTime = System.nanoTime(); Config loggingCfg = Configs.of().logging(); LogbackManager logbackManager = new LogbackManager(loggerContext);
LogbackManagerHolder.getInstance().setLogbackManager(logbackManager);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/htmlrender/TemplateEngine.java
// Path: src/main/java/com/adeptj/runtime/common/Times.java // public final class Times { // // // No instances, just utility methods. // private Times() { // } // // /** // * Returns elapsed time in milliseconds from the provided time in nanoseconds. // * // * @param startTime time in nanoseconds // * @return elapsed time in milliseconds // */ // public static long elapsedMillis(final long startTime) { // return NANOSECONDS.toMillis(System.nanoTime() - startTime); // } // // /** // * Returns elapsed time in seconds from the provided time in milliseconds. // * // * @param startTime time in milliseconds // * @return elapsed time in seconds // */ // public static long elapsedSeconds(final long startTime) { // return MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime); // } // } // // Path: src/main/java/com/adeptj/runtime/config/Configs.java // public enum Configs { // // INSTANCE; // // /** // * This will include system properties as well. // */ // private final Config root; // // Configs() { // this.root = this.loadConf(); // } // // public Config root() { // return this.root; // } // // public Config main() { // return this.root.getConfig(MAIN_CONF_SECTION); // } // // public Config undertow() { // return this.main().getConfig(UNDERTOW_CONF_SECTION); // } // // public Config felix() { // return this.main().getConfig(FELIX_CONF_SECTION); // } // // public Config common() { // return this.main().getConfig(COMMON_CONF_SECTION); // } // // public Config logging() { // return this.main().getConfig(LOGGING_CONF_SECTION); // } // // public Config trimou() { // return this.main().getConfig(TRIMOU_CONF_SECTION); // } // // public Config resteasy() { // return this.main().getConfig(RESTEASY_CONF_SECTION); // } // // private Config loadConf() { // Config config; // File configFile = Environment.getServerConfPath().toFile(); // if (configFile.exists()) { // // if overwrite.server.conf.file system property is provided, then load the configs from classpath. // if (Boolean.getBoolean(SYS_PROP_OVERWRITE_SERVER_CONF)) { // config = ConfigFactory.load(SERVER_CONF_FILE); // } else { // config = ConfigFactory.parseFile(configFile) // .withFallback(ConfigFactory.systemProperties()) // .resolve(); // } // } else { // config = ConfigFactory.load(SERVER_CONF_FILE); // } // return config; // } // // public static Configs of() { // return INSTANCE; // } // // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String CONTENT_TYPE_HTML_UTF8 = "text/html;charset=UTF-8"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String UTF8 = "UTF-8";
import static com.adeptj.runtime.common.Constants.CONTENT_TYPE_HTML_UTF8; import static com.adeptj.runtime.common.Constants.UTF8; import static org.trimou.engine.config.EngineConfigurationKey.DEFAULT_FILE_ENCODING; import static org.trimou.engine.config.EngineConfigurationKey.END_DELIMITER; import static org.trimou.engine.config.EngineConfigurationKey.START_DELIMITER; import static org.trimou.engine.config.EngineConfigurationKey.TEMPLATE_CACHE_ENABLED; import static org.trimou.engine.config.EngineConfigurationKey.TEMPLATE_CACHE_EXPIRATION_TIMEOUT; import static org.trimou.handlebars.i18n.ResourceBundleHelper.Format.MESSAGE; import com.adeptj.runtime.common.Times; import com.adeptj.runtime.config.Configs; import com.typesafe.config.Config; import org.slf4j.LoggerFactory; import org.trimou.Mustache; import org.trimou.engine.MustacheEngine; import org.trimou.engine.MustacheEngineBuilder; import org.trimou.engine.locator.ClassPathTemplateLocator; import org.trimou.handlebars.i18n.ResourceBundleHelper;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.htmlrender; /** * Trimou based TemplateEngine for rendering the HTML templates. * * @author Rakesh.Kumar, AdeptJ. */ public enum TemplateEngine { INSTANCE; private static final String TEMPLATE_ENGINE_INIT_MSG = "TemplateEngine initialized in [{}] ms!!"; private static final String RB_HELPER_NAME = "msg"; private static final String KEY_RB_BASE_NAME = "resource-bundle-basename"; private static final String KEY_START_DELIMITER = "start-delimiter"; private static final String KEY_END_DELIMITER = "end-delimiter"; private static final String KEY_CACHE_ENABLED = "cache-enabled"; private static final String KEY_CACHE_EXPIRATION = "cache-expiration"; private static final String KEY_TEMPLATE_LOCATOR_PRIORITY = "template-locator-priority"; private static final String KEY_PREFIX = "prefix"; private static final String KEY_SUFFIX = "suffix"; private final MustacheEngine mustacheEngine; TemplateEngine() { long startTime = System.nanoTime();
// Path: src/main/java/com/adeptj/runtime/common/Times.java // public final class Times { // // // No instances, just utility methods. // private Times() { // } // // /** // * Returns elapsed time in milliseconds from the provided time in nanoseconds. // * // * @param startTime time in nanoseconds // * @return elapsed time in milliseconds // */ // public static long elapsedMillis(final long startTime) { // return NANOSECONDS.toMillis(System.nanoTime() - startTime); // } // // /** // * Returns elapsed time in seconds from the provided time in milliseconds. // * // * @param startTime time in milliseconds // * @return elapsed time in seconds // */ // public static long elapsedSeconds(final long startTime) { // return MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime); // } // } // // Path: src/main/java/com/adeptj/runtime/config/Configs.java // public enum Configs { // // INSTANCE; // // /** // * This will include system properties as well. // */ // private final Config root; // // Configs() { // this.root = this.loadConf(); // } // // public Config root() { // return this.root; // } // // public Config main() { // return this.root.getConfig(MAIN_CONF_SECTION); // } // // public Config undertow() { // return this.main().getConfig(UNDERTOW_CONF_SECTION); // } // // public Config felix() { // return this.main().getConfig(FELIX_CONF_SECTION); // } // // public Config common() { // return this.main().getConfig(COMMON_CONF_SECTION); // } // // public Config logging() { // return this.main().getConfig(LOGGING_CONF_SECTION); // } // // public Config trimou() { // return this.main().getConfig(TRIMOU_CONF_SECTION); // } // // public Config resteasy() { // return this.main().getConfig(RESTEASY_CONF_SECTION); // } // // private Config loadConf() { // Config config; // File configFile = Environment.getServerConfPath().toFile(); // if (configFile.exists()) { // // if overwrite.server.conf.file system property is provided, then load the configs from classpath. // if (Boolean.getBoolean(SYS_PROP_OVERWRITE_SERVER_CONF)) { // config = ConfigFactory.load(SERVER_CONF_FILE); // } else { // config = ConfigFactory.parseFile(configFile) // .withFallback(ConfigFactory.systemProperties()) // .resolve(); // } // } else { // config = ConfigFactory.load(SERVER_CONF_FILE); // } // return config; // } // // public static Configs of() { // return INSTANCE; // } // // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String CONTENT_TYPE_HTML_UTF8 = "text/html;charset=UTF-8"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String UTF8 = "UTF-8"; // Path: src/main/java/com/adeptj/runtime/htmlrender/TemplateEngine.java import static com.adeptj.runtime.common.Constants.CONTENT_TYPE_HTML_UTF8; import static com.adeptj.runtime.common.Constants.UTF8; import static org.trimou.engine.config.EngineConfigurationKey.DEFAULT_FILE_ENCODING; import static org.trimou.engine.config.EngineConfigurationKey.END_DELIMITER; import static org.trimou.engine.config.EngineConfigurationKey.START_DELIMITER; import static org.trimou.engine.config.EngineConfigurationKey.TEMPLATE_CACHE_ENABLED; import static org.trimou.engine.config.EngineConfigurationKey.TEMPLATE_CACHE_EXPIRATION_TIMEOUT; import static org.trimou.handlebars.i18n.ResourceBundleHelper.Format.MESSAGE; import com.adeptj.runtime.common.Times; import com.adeptj.runtime.config.Configs; import com.typesafe.config.Config; import org.slf4j.LoggerFactory; import org.trimou.Mustache; import org.trimou.engine.MustacheEngine; import org.trimou.engine.MustacheEngineBuilder; import org.trimou.engine.locator.ClassPathTemplateLocator; import org.trimou.handlebars.i18n.ResourceBundleHelper; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.htmlrender; /** * Trimou based TemplateEngine for rendering the HTML templates. * * @author Rakesh.Kumar, AdeptJ. */ public enum TemplateEngine { INSTANCE; private static final String TEMPLATE_ENGINE_INIT_MSG = "TemplateEngine initialized in [{}] ms!!"; private static final String RB_HELPER_NAME = "msg"; private static final String KEY_RB_BASE_NAME = "resource-bundle-basename"; private static final String KEY_START_DELIMITER = "start-delimiter"; private static final String KEY_END_DELIMITER = "end-delimiter"; private static final String KEY_CACHE_ENABLED = "cache-enabled"; private static final String KEY_CACHE_EXPIRATION = "cache-expiration"; private static final String KEY_TEMPLATE_LOCATOR_PRIORITY = "template-locator-priority"; private static final String KEY_PREFIX = "prefix"; private static final String KEY_SUFFIX = "suffix"; private final MustacheEngine mustacheEngine; TemplateEngine() { long startTime = System.nanoTime();
Config config = Configs.of().trimou();
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/htmlrender/TemplateEngine.java
// Path: src/main/java/com/adeptj/runtime/common/Times.java // public final class Times { // // // No instances, just utility methods. // private Times() { // } // // /** // * Returns elapsed time in milliseconds from the provided time in nanoseconds. // * // * @param startTime time in nanoseconds // * @return elapsed time in milliseconds // */ // public static long elapsedMillis(final long startTime) { // return NANOSECONDS.toMillis(System.nanoTime() - startTime); // } // // /** // * Returns elapsed time in seconds from the provided time in milliseconds. // * // * @param startTime time in milliseconds // * @return elapsed time in seconds // */ // public static long elapsedSeconds(final long startTime) { // return MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime); // } // } // // Path: src/main/java/com/adeptj/runtime/config/Configs.java // public enum Configs { // // INSTANCE; // // /** // * This will include system properties as well. // */ // private final Config root; // // Configs() { // this.root = this.loadConf(); // } // // public Config root() { // return this.root; // } // // public Config main() { // return this.root.getConfig(MAIN_CONF_SECTION); // } // // public Config undertow() { // return this.main().getConfig(UNDERTOW_CONF_SECTION); // } // // public Config felix() { // return this.main().getConfig(FELIX_CONF_SECTION); // } // // public Config common() { // return this.main().getConfig(COMMON_CONF_SECTION); // } // // public Config logging() { // return this.main().getConfig(LOGGING_CONF_SECTION); // } // // public Config trimou() { // return this.main().getConfig(TRIMOU_CONF_SECTION); // } // // public Config resteasy() { // return this.main().getConfig(RESTEASY_CONF_SECTION); // } // // private Config loadConf() { // Config config; // File configFile = Environment.getServerConfPath().toFile(); // if (configFile.exists()) { // // if overwrite.server.conf.file system property is provided, then load the configs from classpath. // if (Boolean.getBoolean(SYS_PROP_OVERWRITE_SERVER_CONF)) { // config = ConfigFactory.load(SERVER_CONF_FILE); // } else { // config = ConfigFactory.parseFile(configFile) // .withFallback(ConfigFactory.systemProperties()) // .resolve(); // } // } else { // config = ConfigFactory.load(SERVER_CONF_FILE); // } // return config; // } // // public static Configs of() { // return INSTANCE; // } // // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String CONTENT_TYPE_HTML_UTF8 = "text/html;charset=UTF-8"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String UTF8 = "UTF-8";
import static com.adeptj.runtime.common.Constants.CONTENT_TYPE_HTML_UTF8; import static com.adeptj.runtime.common.Constants.UTF8; import static org.trimou.engine.config.EngineConfigurationKey.DEFAULT_FILE_ENCODING; import static org.trimou.engine.config.EngineConfigurationKey.END_DELIMITER; import static org.trimou.engine.config.EngineConfigurationKey.START_DELIMITER; import static org.trimou.engine.config.EngineConfigurationKey.TEMPLATE_CACHE_ENABLED; import static org.trimou.engine.config.EngineConfigurationKey.TEMPLATE_CACHE_EXPIRATION_TIMEOUT; import static org.trimou.handlebars.i18n.ResourceBundleHelper.Format.MESSAGE; import com.adeptj.runtime.common.Times; import com.adeptj.runtime.config.Configs; import com.typesafe.config.Config; import org.slf4j.LoggerFactory; import org.trimou.Mustache; import org.trimou.engine.MustacheEngine; import org.trimou.engine.MustacheEngineBuilder; import org.trimou.engine.locator.ClassPathTemplateLocator; import org.trimou.handlebars.i18n.ResourceBundleHelper;
private static final String KEY_CACHE_ENABLED = "cache-enabled"; private static final String KEY_CACHE_EXPIRATION = "cache-expiration"; private static final String KEY_TEMPLATE_LOCATOR_PRIORITY = "template-locator-priority"; private static final String KEY_PREFIX = "prefix"; private static final String KEY_SUFFIX = "suffix"; private final MustacheEngine mustacheEngine; TemplateEngine() { long startTime = System.nanoTime(); Config config = Configs.of().trimou(); this.mustacheEngine = MustacheEngineBuilder.newBuilder() .registerHelper(RB_HELPER_NAME, new ResourceBundleHelper(config.getString(KEY_RB_BASE_NAME), MESSAGE)) .addTemplateLocator(ClassPathTemplateLocator.builder() .setPriority(config.getInt(KEY_TEMPLATE_LOCATOR_PRIORITY)) .setRootPath(config.getString(KEY_PREFIX)) .setSuffix(config.getString(KEY_SUFFIX)) .setScanClasspath(false) .build()) .setProperty(START_DELIMITER, config.getString(KEY_START_DELIMITER)) .setProperty(END_DELIMITER, config.getString(KEY_END_DELIMITER)) .setProperty(DEFAULT_FILE_ENCODING, UTF8) .setProperty(TEMPLATE_CACHE_ENABLED, config.getBoolean(KEY_CACHE_ENABLED)) .setProperty(TEMPLATE_CACHE_EXPIRATION_TIMEOUT, config.getInt(KEY_CACHE_EXPIRATION)) .build();
// Path: src/main/java/com/adeptj/runtime/common/Times.java // public final class Times { // // // No instances, just utility methods. // private Times() { // } // // /** // * Returns elapsed time in milliseconds from the provided time in nanoseconds. // * // * @param startTime time in nanoseconds // * @return elapsed time in milliseconds // */ // public static long elapsedMillis(final long startTime) { // return NANOSECONDS.toMillis(System.nanoTime() - startTime); // } // // /** // * Returns elapsed time in seconds from the provided time in milliseconds. // * // * @param startTime time in milliseconds // * @return elapsed time in seconds // */ // public static long elapsedSeconds(final long startTime) { // return MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime); // } // } // // Path: src/main/java/com/adeptj/runtime/config/Configs.java // public enum Configs { // // INSTANCE; // // /** // * This will include system properties as well. // */ // private final Config root; // // Configs() { // this.root = this.loadConf(); // } // // public Config root() { // return this.root; // } // // public Config main() { // return this.root.getConfig(MAIN_CONF_SECTION); // } // // public Config undertow() { // return this.main().getConfig(UNDERTOW_CONF_SECTION); // } // // public Config felix() { // return this.main().getConfig(FELIX_CONF_SECTION); // } // // public Config common() { // return this.main().getConfig(COMMON_CONF_SECTION); // } // // public Config logging() { // return this.main().getConfig(LOGGING_CONF_SECTION); // } // // public Config trimou() { // return this.main().getConfig(TRIMOU_CONF_SECTION); // } // // public Config resteasy() { // return this.main().getConfig(RESTEASY_CONF_SECTION); // } // // private Config loadConf() { // Config config; // File configFile = Environment.getServerConfPath().toFile(); // if (configFile.exists()) { // // if overwrite.server.conf.file system property is provided, then load the configs from classpath. // if (Boolean.getBoolean(SYS_PROP_OVERWRITE_SERVER_CONF)) { // config = ConfigFactory.load(SERVER_CONF_FILE); // } else { // config = ConfigFactory.parseFile(configFile) // .withFallback(ConfigFactory.systemProperties()) // .resolve(); // } // } else { // config = ConfigFactory.load(SERVER_CONF_FILE); // } // return config; // } // // public static Configs of() { // return INSTANCE; // } // // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String CONTENT_TYPE_HTML_UTF8 = "text/html;charset=UTF-8"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String UTF8 = "UTF-8"; // Path: src/main/java/com/adeptj/runtime/htmlrender/TemplateEngine.java import static com.adeptj.runtime.common.Constants.CONTENT_TYPE_HTML_UTF8; import static com.adeptj.runtime.common.Constants.UTF8; import static org.trimou.engine.config.EngineConfigurationKey.DEFAULT_FILE_ENCODING; import static org.trimou.engine.config.EngineConfigurationKey.END_DELIMITER; import static org.trimou.engine.config.EngineConfigurationKey.START_DELIMITER; import static org.trimou.engine.config.EngineConfigurationKey.TEMPLATE_CACHE_ENABLED; import static org.trimou.engine.config.EngineConfigurationKey.TEMPLATE_CACHE_EXPIRATION_TIMEOUT; import static org.trimou.handlebars.i18n.ResourceBundleHelper.Format.MESSAGE; import com.adeptj.runtime.common.Times; import com.adeptj.runtime.config.Configs; import com.typesafe.config.Config; import org.slf4j.LoggerFactory; import org.trimou.Mustache; import org.trimou.engine.MustacheEngine; import org.trimou.engine.MustacheEngineBuilder; import org.trimou.engine.locator.ClassPathTemplateLocator; import org.trimou.handlebars.i18n.ResourceBundleHelper; private static final String KEY_CACHE_ENABLED = "cache-enabled"; private static final String KEY_CACHE_EXPIRATION = "cache-expiration"; private static final String KEY_TEMPLATE_LOCATOR_PRIORITY = "template-locator-priority"; private static final String KEY_PREFIX = "prefix"; private static final String KEY_SUFFIX = "suffix"; private final MustacheEngine mustacheEngine; TemplateEngine() { long startTime = System.nanoTime(); Config config = Configs.of().trimou(); this.mustacheEngine = MustacheEngineBuilder.newBuilder() .registerHelper(RB_HELPER_NAME, new ResourceBundleHelper(config.getString(KEY_RB_BASE_NAME), MESSAGE)) .addTemplateLocator(ClassPathTemplateLocator.builder() .setPriority(config.getInt(KEY_TEMPLATE_LOCATOR_PRIORITY)) .setRootPath(config.getString(KEY_PREFIX)) .setSuffix(config.getString(KEY_SUFFIX)) .setScanClasspath(false) .build()) .setProperty(START_DELIMITER, config.getString(KEY_START_DELIMITER)) .setProperty(END_DELIMITER, config.getString(KEY_END_DELIMITER)) .setProperty(DEFAULT_FILE_ENCODING, UTF8) .setProperty(TEMPLATE_CACHE_ENABLED, config.getBoolean(KEY_CACHE_ENABLED)) .setProperty(TEMPLATE_CACHE_EXPIRATION_TIMEOUT, config.getInt(KEY_CACHE_EXPIRATION)) .build();
LoggerFactory.getLogger(this.getClass()).info(TEMPLATE_ENGINE_INIT_MSG, Times.elapsedMillis(startTime));
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/htmlrender/TemplateEngine.java
// Path: src/main/java/com/adeptj/runtime/common/Times.java // public final class Times { // // // No instances, just utility methods. // private Times() { // } // // /** // * Returns elapsed time in milliseconds from the provided time in nanoseconds. // * // * @param startTime time in nanoseconds // * @return elapsed time in milliseconds // */ // public static long elapsedMillis(final long startTime) { // return NANOSECONDS.toMillis(System.nanoTime() - startTime); // } // // /** // * Returns elapsed time in seconds from the provided time in milliseconds. // * // * @param startTime time in milliseconds // * @return elapsed time in seconds // */ // public static long elapsedSeconds(final long startTime) { // return MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime); // } // } // // Path: src/main/java/com/adeptj/runtime/config/Configs.java // public enum Configs { // // INSTANCE; // // /** // * This will include system properties as well. // */ // private final Config root; // // Configs() { // this.root = this.loadConf(); // } // // public Config root() { // return this.root; // } // // public Config main() { // return this.root.getConfig(MAIN_CONF_SECTION); // } // // public Config undertow() { // return this.main().getConfig(UNDERTOW_CONF_SECTION); // } // // public Config felix() { // return this.main().getConfig(FELIX_CONF_SECTION); // } // // public Config common() { // return this.main().getConfig(COMMON_CONF_SECTION); // } // // public Config logging() { // return this.main().getConfig(LOGGING_CONF_SECTION); // } // // public Config trimou() { // return this.main().getConfig(TRIMOU_CONF_SECTION); // } // // public Config resteasy() { // return this.main().getConfig(RESTEASY_CONF_SECTION); // } // // private Config loadConf() { // Config config; // File configFile = Environment.getServerConfPath().toFile(); // if (configFile.exists()) { // // if overwrite.server.conf.file system property is provided, then load the configs from classpath. // if (Boolean.getBoolean(SYS_PROP_OVERWRITE_SERVER_CONF)) { // config = ConfigFactory.load(SERVER_CONF_FILE); // } else { // config = ConfigFactory.parseFile(configFile) // .withFallback(ConfigFactory.systemProperties()) // .resolve(); // } // } else { // config = ConfigFactory.load(SERVER_CONF_FILE); // } // return config; // } // // public static Configs of() { // return INSTANCE; // } // // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String CONTENT_TYPE_HTML_UTF8 = "text/html;charset=UTF-8"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String UTF8 = "UTF-8";
import static com.adeptj.runtime.common.Constants.CONTENT_TYPE_HTML_UTF8; import static com.adeptj.runtime.common.Constants.UTF8; import static org.trimou.engine.config.EngineConfigurationKey.DEFAULT_FILE_ENCODING; import static org.trimou.engine.config.EngineConfigurationKey.END_DELIMITER; import static org.trimou.engine.config.EngineConfigurationKey.START_DELIMITER; import static org.trimou.engine.config.EngineConfigurationKey.TEMPLATE_CACHE_ENABLED; import static org.trimou.engine.config.EngineConfigurationKey.TEMPLATE_CACHE_EXPIRATION_TIMEOUT; import static org.trimou.handlebars.i18n.ResourceBundleHelper.Format.MESSAGE; import com.adeptj.runtime.common.Times; import com.adeptj.runtime.config.Configs; import com.typesafe.config.Config; import org.slf4j.LoggerFactory; import org.trimou.Mustache; import org.trimou.engine.MustacheEngine; import org.trimou.engine.MustacheEngineBuilder; import org.trimou.engine.locator.ClassPathTemplateLocator; import org.trimou.handlebars.i18n.ResourceBundleHelper;
TemplateEngine() { long startTime = System.nanoTime(); Config config = Configs.of().trimou(); this.mustacheEngine = MustacheEngineBuilder.newBuilder() .registerHelper(RB_HELPER_NAME, new ResourceBundleHelper(config.getString(KEY_RB_BASE_NAME), MESSAGE)) .addTemplateLocator(ClassPathTemplateLocator.builder() .setPriority(config.getInt(KEY_TEMPLATE_LOCATOR_PRIORITY)) .setRootPath(config.getString(KEY_PREFIX)) .setSuffix(config.getString(KEY_SUFFIX)) .setScanClasspath(false) .build()) .setProperty(START_DELIMITER, config.getString(KEY_START_DELIMITER)) .setProperty(END_DELIMITER, config.getString(KEY_END_DELIMITER)) .setProperty(DEFAULT_FILE_ENCODING, UTF8) .setProperty(TEMPLATE_CACHE_ENABLED, config.getBoolean(KEY_CACHE_ENABLED)) .setProperty(TEMPLATE_CACHE_EXPIRATION_TIMEOUT, config.getInt(KEY_CACHE_EXPIRATION)) .build(); LoggerFactory.getLogger(this.getClass()).info(TEMPLATE_ENGINE_INIT_MSG, Times.elapsedMillis(startTime)); } /** * Renders the template contained by the {@link TemplateEngineContext#getTemplate()} * * @param context the TemplateEngine context * @throws TemplateProcessingException if there was some issue while rendering the template. */ public void render(TemplateEngineContext context) { try { // Making sure the Content-Type will always be text/html;charset=UTF-8.
// Path: src/main/java/com/adeptj/runtime/common/Times.java // public final class Times { // // // No instances, just utility methods. // private Times() { // } // // /** // * Returns elapsed time in milliseconds from the provided time in nanoseconds. // * // * @param startTime time in nanoseconds // * @return elapsed time in milliseconds // */ // public static long elapsedMillis(final long startTime) { // return NANOSECONDS.toMillis(System.nanoTime() - startTime); // } // // /** // * Returns elapsed time in seconds from the provided time in milliseconds. // * // * @param startTime time in milliseconds // * @return elapsed time in seconds // */ // public static long elapsedSeconds(final long startTime) { // return MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime); // } // } // // Path: src/main/java/com/adeptj/runtime/config/Configs.java // public enum Configs { // // INSTANCE; // // /** // * This will include system properties as well. // */ // private final Config root; // // Configs() { // this.root = this.loadConf(); // } // // public Config root() { // return this.root; // } // // public Config main() { // return this.root.getConfig(MAIN_CONF_SECTION); // } // // public Config undertow() { // return this.main().getConfig(UNDERTOW_CONF_SECTION); // } // // public Config felix() { // return this.main().getConfig(FELIX_CONF_SECTION); // } // // public Config common() { // return this.main().getConfig(COMMON_CONF_SECTION); // } // // public Config logging() { // return this.main().getConfig(LOGGING_CONF_SECTION); // } // // public Config trimou() { // return this.main().getConfig(TRIMOU_CONF_SECTION); // } // // public Config resteasy() { // return this.main().getConfig(RESTEASY_CONF_SECTION); // } // // private Config loadConf() { // Config config; // File configFile = Environment.getServerConfPath().toFile(); // if (configFile.exists()) { // // if overwrite.server.conf.file system property is provided, then load the configs from classpath. // if (Boolean.getBoolean(SYS_PROP_OVERWRITE_SERVER_CONF)) { // config = ConfigFactory.load(SERVER_CONF_FILE); // } else { // config = ConfigFactory.parseFile(configFile) // .withFallback(ConfigFactory.systemProperties()) // .resolve(); // } // } else { // config = ConfigFactory.load(SERVER_CONF_FILE); // } // return config; // } // // public static Configs of() { // return INSTANCE; // } // // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String CONTENT_TYPE_HTML_UTF8 = "text/html;charset=UTF-8"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String UTF8 = "UTF-8"; // Path: src/main/java/com/adeptj/runtime/htmlrender/TemplateEngine.java import static com.adeptj.runtime.common.Constants.CONTENT_TYPE_HTML_UTF8; import static com.adeptj.runtime.common.Constants.UTF8; import static org.trimou.engine.config.EngineConfigurationKey.DEFAULT_FILE_ENCODING; import static org.trimou.engine.config.EngineConfigurationKey.END_DELIMITER; import static org.trimou.engine.config.EngineConfigurationKey.START_DELIMITER; import static org.trimou.engine.config.EngineConfigurationKey.TEMPLATE_CACHE_ENABLED; import static org.trimou.engine.config.EngineConfigurationKey.TEMPLATE_CACHE_EXPIRATION_TIMEOUT; import static org.trimou.handlebars.i18n.ResourceBundleHelper.Format.MESSAGE; import com.adeptj.runtime.common.Times; import com.adeptj.runtime.config.Configs; import com.typesafe.config.Config; import org.slf4j.LoggerFactory; import org.trimou.Mustache; import org.trimou.engine.MustacheEngine; import org.trimou.engine.MustacheEngineBuilder; import org.trimou.engine.locator.ClassPathTemplateLocator; import org.trimou.handlebars.i18n.ResourceBundleHelper; TemplateEngine() { long startTime = System.nanoTime(); Config config = Configs.of().trimou(); this.mustacheEngine = MustacheEngineBuilder.newBuilder() .registerHelper(RB_HELPER_NAME, new ResourceBundleHelper(config.getString(KEY_RB_BASE_NAME), MESSAGE)) .addTemplateLocator(ClassPathTemplateLocator.builder() .setPriority(config.getInt(KEY_TEMPLATE_LOCATOR_PRIORITY)) .setRootPath(config.getString(KEY_PREFIX)) .setSuffix(config.getString(KEY_SUFFIX)) .setScanClasspath(false) .build()) .setProperty(START_DELIMITER, config.getString(KEY_START_DELIMITER)) .setProperty(END_DELIMITER, config.getString(KEY_END_DELIMITER)) .setProperty(DEFAULT_FILE_ENCODING, UTF8) .setProperty(TEMPLATE_CACHE_ENABLED, config.getBoolean(KEY_CACHE_ENABLED)) .setProperty(TEMPLATE_CACHE_EXPIRATION_TIMEOUT, config.getInt(KEY_CACHE_EXPIRATION)) .build(); LoggerFactory.getLogger(this.getClass()).info(TEMPLATE_ENGINE_INIT_MSG, Times.elapsedMillis(startTime)); } /** * Renders the template contained by the {@link TemplateEngineContext#getTemplate()} * * @param context the TemplateEngine context * @throws TemplateProcessingException if there was some issue while rendering the template. */ public void render(TemplateEngineContext context) { try { // Making sure the Content-Type will always be text/html;charset=UTF-8.
context.getResponse().setContentType(CONTENT_TYPE_HTML_UTF8);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/osgi/DispatcherServletTracker.java
// Path: src/main/java/com/adeptj/runtime/common/BridgeServletConfigHolder.java // public enum BridgeServletConfigHolder { // // INSTANCE; // // private ServletConfig bridgeServletConfig; // // public void setBridgeServletConfig(ServletConfig bridgeServletConfig) { // NOSONAR // if (this.bridgeServletConfig == null) { // this.bridgeServletConfig = bridgeServletConfig; // } // } // // public ServletConfig getBridgeServletConfig() { // return bridgeServletConfig; // } // // public static BridgeServletConfigHolder getInstance() { // return INSTANCE; // } // }
import com.adeptj.runtime.common.BridgeServletConfigHolder; import org.apache.felix.http.base.internal.dispatch.DispatcherServlet; import org.osgi.framework.BundleContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletConfig; import javax.servlet.http.HttpServlet;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.osgi; /** * OSGi ServiceTracker for Felix {@link org.apache.felix.http.base.internal.dispatch.DispatcherServlet}. * * @author Rakesh.Kumar, AdeptJ */ public class DispatcherServletTracker extends BridgeServiceTracker<HttpServlet> { private static final Logger LOGGER = LoggerFactory.getLogger(DispatcherServletTracker.class); private static final String EXCEPTION_MSG = "Exception adding Felix DispatcherServlet OSGi Service!!"; private DispatcherServletWrapper dispatcherServletWrapper; /** * Create the {@link org.osgi.util.tracker.ServiceTracker} for {@link HttpServlet} * * @param context the {@link BundleContext} */ DispatcherServletTracker(BundleContext context) { super(context, HttpServlet.class); } /** * Initializes the Felix {@link org.apache.felix.http.base.internal.dispatch.DispatcherServlet} * * @param dispatcherServlet the Felix {@link org.apache.felix.http.base.internal.dispatch.DispatcherServlet} */ @Override protected HttpServlet addingService(HttpServlet dispatcherServlet) { this.dispatcherServletWrapper = new DispatcherServletWrapper(dispatcherServlet); try {
// Path: src/main/java/com/adeptj/runtime/common/BridgeServletConfigHolder.java // public enum BridgeServletConfigHolder { // // INSTANCE; // // private ServletConfig bridgeServletConfig; // // public void setBridgeServletConfig(ServletConfig bridgeServletConfig) { // NOSONAR // if (this.bridgeServletConfig == null) { // this.bridgeServletConfig = bridgeServletConfig; // } // } // // public ServletConfig getBridgeServletConfig() { // return bridgeServletConfig; // } // // public static BridgeServletConfigHolder getInstance() { // return INSTANCE; // } // } // Path: src/main/java/com/adeptj/runtime/osgi/DispatcherServletTracker.java import com.adeptj.runtime.common.BridgeServletConfigHolder; import org.apache.felix.http.base.internal.dispatch.DispatcherServlet; import org.osgi.framework.BundleContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletConfig; import javax.servlet.http.HttpServlet; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.osgi; /** * OSGi ServiceTracker for Felix {@link org.apache.felix.http.base.internal.dispatch.DispatcherServlet}. * * @author Rakesh.Kumar, AdeptJ */ public class DispatcherServletTracker extends BridgeServiceTracker<HttpServlet> { private static final Logger LOGGER = LoggerFactory.getLogger(DispatcherServletTracker.class); private static final String EXCEPTION_MSG = "Exception adding Felix DispatcherServlet OSGi Service!!"; private DispatcherServletWrapper dispatcherServletWrapper; /** * Create the {@link org.osgi.util.tracker.ServiceTracker} for {@link HttpServlet} * * @param context the {@link BundleContext} */ DispatcherServletTracker(BundleContext context) { super(context, HttpServlet.class); } /** * Initializes the Felix {@link org.apache.felix.http.base.internal.dispatch.DispatcherServlet} * * @param dispatcherServlet the Felix {@link org.apache.felix.http.base.internal.dispatch.DispatcherServlet} */ @Override protected HttpServlet addingService(HttpServlet dispatcherServlet) { this.dispatcherServletWrapper = new DispatcherServletWrapper(dispatcherServlet); try {
ServletConfig bridgeServletConfig = BridgeServletConfigHolder.getInstance().getBridgeServletConfig();
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/server/SocketOptions.java
// Path: src/main/java/com/adeptj/runtime/common/Times.java // public final class Times { // // // No instances, just utility methods. // private Times() { // } // // /** // * Returns elapsed time in milliseconds from the provided time in nanoseconds. // * // * @param startTime time in nanoseconds // * @return elapsed time in milliseconds // */ // public static long elapsedMillis(final long startTime) { // return NANOSECONDS.toMillis(System.nanoTime() - startTime); // } // // /** // * Returns elapsed time in seconds from the provided time in milliseconds. // * // * @param startTime time in milliseconds // * @return elapsed time in seconds // */ // public static long elapsedSeconds(final long startTime) { // return MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime); // } // }
import io.undertow.Undertow.Builder; import com.adeptj.runtime.common.Times; import com.typesafe.config.Config;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.server; /** * Undertow Socket Options. * * @author Rakesh.Kumar, AdeptJ */ final class SocketOptions extends BaseOptions { private static final String SOCKET_OPTIONS = "socket-options"; /** * Configures the socket options dynamically. * * @param builder Undertow.Builder * @param undertowConfig Undertow Typesafe Config */ @Override void setOptions(Builder builder, Config undertowConfig) { long startTime = System.nanoTime(); undertowConfig.getObject(SOCKET_OPTIONS) .unwrapped() .forEach((key, val) -> builder.setSocketOption(this.getOption(key), val));
// Path: src/main/java/com/adeptj/runtime/common/Times.java // public final class Times { // // // No instances, just utility methods. // private Times() { // } // // /** // * Returns elapsed time in milliseconds from the provided time in nanoseconds. // * // * @param startTime time in nanoseconds // * @return elapsed time in milliseconds // */ // public static long elapsedMillis(final long startTime) { // return NANOSECONDS.toMillis(System.nanoTime() - startTime); // } // // /** // * Returns elapsed time in seconds from the provided time in milliseconds. // * // * @param startTime time in milliseconds // * @return elapsed time in seconds // */ // public static long elapsedSeconds(final long startTime) { // return MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime); // } // } // Path: src/main/java/com/adeptj/runtime/server/SocketOptions.java import io.undertow.Undertow.Builder; import com.adeptj.runtime.common.Times; import com.typesafe.config.Config; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.server; /** * Undertow Socket Options. * * @author Rakesh.Kumar, AdeptJ */ final class SocketOptions extends BaseOptions { private static final String SOCKET_OPTIONS = "socket-options"; /** * Configures the socket options dynamically. * * @param builder Undertow.Builder * @param undertowConfig Undertow Typesafe Config */ @Override void setOptions(Builder builder, Config undertowConfig) { long startTime = System.nanoTime(); undertowConfig.getObject(SOCKET_OPTIONS) .unwrapped() .forEach((key, val) -> builder.setSocketOption(this.getOption(key), val));
this.logger.info("Undertow SocketOptions configured in [{}] ms!!", Times.elapsedMillis(startTime));
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/osgi/BridgeServletContextAttributeListener.java
// Path: src/main/java/com/adeptj/runtime/common/BundleContextHolder.java // public enum BundleContextHolder { // // INSTANCE; // // private BundleContext bundleContext; // // public BundleContext getBundleContext() { // return this.bundleContext; // } // // public void setBundleContext(BundleContext bundleContext) { // NOSONAR // this.bundleContext = bundleContext; // } // // public static BundleContextHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String ATTRIBUTE_BUNDLE_CONTEXT = "org.osgi.framework.BundleContext";
import com.adeptj.runtime.common.BundleContextHolder; import org.apache.commons.lang3.StringUtils; import org.osgi.framework.BundleContext; import javax.servlet.ServletContextAttributeEvent; import javax.servlet.ServletContextAttributeListener; import static com.adeptj.runtime.common.Constants.ATTRIBUTE_BUNDLE_CONTEXT;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.osgi; /** * A {@link ServletContextAttributeListener} which initializes the {@link EventDispatcherTracker} * when {@link BundleContext} is being set as a {@link javax.servlet.ServletContext} attribute and again closes * and opens when {@link BundleContext} is replaced as a {@link javax.servlet.ServletContext} attribute. * * @author Rakesh.Kumar, AdeptJ */ public class BridgeServletContextAttributeListener implements ServletContextAttributeListener { @Override public void attributeAdded(ServletContextAttributeEvent event) {
// Path: src/main/java/com/adeptj/runtime/common/BundleContextHolder.java // public enum BundleContextHolder { // // INSTANCE; // // private BundleContext bundleContext; // // public BundleContext getBundleContext() { // return this.bundleContext; // } // // public void setBundleContext(BundleContext bundleContext) { // NOSONAR // this.bundleContext = bundleContext; // } // // public static BundleContextHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String ATTRIBUTE_BUNDLE_CONTEXT = "org.osgi.framework.BundleContext"; // Path: src/main/java/com/adeptj/runtime/osgi/BridgeServletContextAttributeListener.java import com.adeptj.runtime.common.BundleContextHolder; import org.apache.commons.lang3.StringUtils; import org.osgi.framework.BundleContext; import javax.servlet.ServletContextAttributeEvent; import javax.servlet.ServletContextAttributeListener; import static com.adeptj.runtime.common.Constants.ATTRIBUTE_BUNDLE_CONTEXT; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.osgi; /** * A {@link ServletContextAttributeListener} which initializes the {@link EventDispatcherTracker} * when {@link BundleContext} is being set as a {@link javax.servlet.ServletContext} attribute and again closes * and opens when {@link BundleContext} is replaced as a {@link javax.servlet.ServletContext} attribute. * * @author Rakesh.Kumar, AdeptJ */ public class BridgeServletContextAttributeListener implements ServletContextAttributeListener { @Override public void attributeAdded(ServletContextAttributeEvent event) {
if (StringUtils.equals(event.getName(), ATTRIBUTE_BUNDLE_CONTEXT)) {
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/osgi/BridgeServletContextAttributeListener.java
// Path: src/main/java/com/adeptj/runtime/common/BundleContextHolder.java // public enum BundleContextHolder { // // INSTANCE; // // private BundleContext bundleContext; // // public BundleContext getBundleContext() { // return this.bundleContext; // } // // public void setBundleContext(BundleContext bundleContext) { // NOSONAR // this.bundleContext = bundleContext; // } // // public static BundleContextHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String ATTRIBUTE_BUNDLE_CONTEXT = "org.osgi.framework.BundleContext";
import com.adeptj.runtime.common.BundleContextHolder; import org.apache.commons.lang3.StringUtils; import org.osgi.framework.BundleContext; import javax.servlet.ServletContextAttributeEvent; import javax.servlet.ServletContextAttributeListener; import static com.adeptj.runtime.common.Constants.ATTRIBUTE_BUNDLE_CONTEXT;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.osgi; /** * A {@link ServletContextAttributeListener} which initializes the {@link EventDispatcherTracker} * when {@link BundleContext} is being set as a {@link javax.servlet.ServletContext} attribute and again closes * and opens when {@link BundleContext} is replaced as a {@link javax.servlet.ServletContext} attribute. * * @author Rakesh.Kumar, AdeptJ */ public class BridgeServletContextAttributeListener implements ServletContextAttributeListener { @Override public void attributeAdded(ServletContextAttributeEvent event) { if (StringUtils.equals(event.getName(), ATTRIBUTE_BUNDLE_CONTEXT)) { ServiceTrackers.getInstance().openEventDispatcherTracker((BundleContext) event.getValue()); } } @Override public void attributeReplaced(ServletContextAttributeEvent event) { if (StringUtils.equals(event.getName(), ATTRIBUTE_BUNDLE_CONTEXT)) { ServiceTrackers.getInstance().closeEventDispatcherTracker(); /* * Now open the EventDispatcherTracker with fresh BundleContext which is already hold by * BundleContextHolder after being set in FrameworkLifecycleListener. * * Rationale: If we use the BundleContext contained in the passed event which is a stale * BundleContext in case of a framework restart event and results in an IllegalStateException. */ ServiceTrackers.getInstance()
// Path: src/main/java/com/adeptj/runtime/common/BundleContextHolder.java // public enum BundleContextHolder { // // INSTANCE; // // private BundleContext bundleContext; // // public BundleContext getBundleContext() { // return this.bundleContext; // } // // public void setBundleContext(BundleContext bundleContext) { // NOSONAR // this.bundleContext = bundleContext; // } // // public static BundleContextHolder getInstance() { // return INSTANCE; // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String ATTRIBUTE_BUNDLE_CONTEXT = "org.osgi.framework.BundleContext"; // Path: src/main/java/com/adeptj/runtime/osgi/BridgeServletContextAttributeListener.java import com.adeptj.runtime.common.BundleContextHolder; import org.apache.commons.lang3.StringUtils; import org.osgi.framework.BundleContext; import javax.servlet.ServletContextAttributeEvent; import javax.servlet.ServletContextAttributeListener; import static com.adeptj.runtime.common.Constants.ATTRIBUTE_BUNDLE_CONTEXT; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.osgi; /** * A {@link ServletContextAttributeListener} which initializes the {@link EventDispatcherTracker} * when {@link BundleContext} is being set as a {@link javax.servlet.ServletContext} attribute and again closes * and opens when {@link BundleContext} is replaced as a {@link javax.servlet.ServletContext} attribute. * * @author Rakesh.Kumar, AdeptJ */ public class BridgeServletContextAttributeListener implements ServletContextAttributeListener { @Override public void attributeAdded(ServletContextAttributeEvent event) { if (StringUtils.equals(event.getName(), ATTRIBUTE_BUNDLE_CONTEXT)) { ServiceTrackers.getInstance().openEventDispatcherTracker((BundleContext) event.getValue()); } } @Override public void attributeReplaced(ServletContextAttributeEvent event) { if (StringUtils.equals(event.getName(), ATTRIBUTE_BUNDLE_CONTEXT)) { ServiceTrackers.getInstance().closeEventDispatcherTracker(); /* * Now open the EventDispatcherTracker with fresh BundleContext which is already hold by * BundleContextHolder after being set in FrameworkLifecycleListener. * * Rationale: If we use the BundleContext contained in the passed event which is a stale * BundleContext in case of a framework restart event and results in an IllegalStateException. */ ServiceTrackers.getInstance()
.openEventDispatcherTracker(BundleContextHolder.getInstance().getBundleContext());
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/common/Environment.java
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String DIR_ADEPTJ_RUNTIME = "adeptj-runtime"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String DIR_DEPLOYMENT = "deployment"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String FRAMEWORK_CONF_FILE = "framework.properties"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String SYS_PROP_SERVER_MODE = "adeptj.rt.mode";
import java.nio.file.Path; import java.nio.file.Paths; import static com.adeptj.runtime.common.Constants.DIR_ADEPTJ_RUNTIME; import static com.adeptj.runtime.common.Constants.DIR_DEPLOYMENT; import static com.adeptj.runtime.common.Constants.FRAMEWORK_CONF_FILE; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_SERVER_MODE; import static org.apache.commons.lang3.SystemUtils.USER_DIR;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utility methods for getting environment details AdeptJ Runtime is running in. * * @author Rakesh.Kumar, AdeptJ. */ public final class Environment { /** * Deny direct instantiation. */ private Environment() { } public static boolean isDev() {
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String DIR_ADEPTJ_RUNTIME = "adeptj-runtime"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String DIR_DEPLOYMENT = "deployment"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String FRAMEWORK_CONF_FILE = "framework.properties"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String SYS_PROP_SERVER_MODE = "adeptj.rt.mode"; // Path: src/main/java/com/adeptj/runtime/common/Environment.java import java.nio.file.Path; import java.nio.file.Paths; import static com.adeptj.runtime.common.Constants.DIR_ADEPTJ_RUNTIME; import static com.adeptj.runtime.common.Constants.DIR_DEPLOYMENT; import static com.adeptj.runtime.common.Constants.FRAMEWORK_CONF_FILE; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_SERVER_MODE; import static org.apache.commons.lang3.SystemUtils.USER_DIR; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utility methods for getting environment details AdeptJ Runtime is running in. * * @author Rakesh.Kumar, AdeptJ. */ public final class Environment { /** * Deny direct instantiation. */ private Environment() { } public static boolean isDev() {
return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE));
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/common/Environment.java
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String DIR_ADEPTJ_RUNTIME = "adeptj-runtime"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String DIR_DEPLOYMENT = "deployment"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String FRAMEWORK_CONF_FILE = "framework.properties"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String SYS_PROP_SERVER_MODE = "adeptj.rt.mode";
import java.nio.file.Path; import java.nio.file.Paths; import static com.adeptj.runtime.common.Constants.DIR_ADEPTJ_RUNTIME; import static com.adeptj.runtime.common.Constants.DIR_DEPLOYMENT; import static com.adeptj.runtime.common.Constants.FRAMEWORK_CONF_FILE; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_SERVER_MODE; import static org.apache.commons.lang3.SystemUtils.USER_DIR;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utility methods for getting environment details AdeptJ Runtime is running in. * * @author Rakesh.Kumar, AdeptJ. */ public final class Environment { /** * Deny direct instantiation. */ private Environment() { } public static boolean isDev() { return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); } public static Path getServerConfPath() {
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String DIR_ADEPTJ_RUNTIME = "adeptj-runtime"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String DIR_DEPLOYMENT = "deployment"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String FRAMEWORK_CONF_FILE = "framework.properties"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String SYS_PROP_SERVER_MODE = "adeptj.rt.mode"; // Path: src/main/java/com/adeptj/runtime/common/Environment.java import java.nio.file.Path; import java.nio.file.Paths; import static com.adeptj.runtime.common.Constants.DIR_ADEPTJ_RUNTIME; import static com.adeptj.runtime.common.Constants.DIR_DEPLOYMENT; import static com.adeptj.runtime.common.Constants.FRAMEWORK_CONF_FILE; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_SERVER_MODE; import static org.apache.commons.lang3.SystemUtils.USER_DIR; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utility methods for getting environment details AdeptJ Runtime is running in. * * @author Rakesh.Kumar, AdeptJ. */ public final class Environment { /** * Deny direct instantiation. */ private Environment() { } public static boolean isDev() { return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); } public static Path getServerConfPath() {
return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, SERVER_CONF_FILE);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/common/Environment.java
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String DIR_ADEPTJ_RUNTIME = "adeptj-runtime"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String DIR_DEPLOYMENT = "deployment"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String FRAMEWORK_CONF_FILE = "framework.properties"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String SYS_PROP_SERVER_MODE = "adeptj.rt.mode";
import java.nio.file.Path; import java.nio.file.Paths; import static com.adeptj.runtime.common.Constants.DIR_ADEPTJ_RUNTIME; import static com.adeptj.runtime.common.Constants.DIR_DEPLOYMENT; import static com.adeptj.runtime.common.Constants.FRAMEWORK_CONF_FILE; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_SERVER_MODE; import static org.apache.commons.lang3.SystemUtils.USER_DIR;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utility methods for getting environment details AdeptJ Runtime is running in. * * @author Rakesh.Kumar, AdeptJ. */ public final class Environment { /** * Deny direct instantiation. */ private Environment() { } public static boolean isDev() { return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); } public static Path getServerConfPath() {
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String DIR_ADEPTJ_RUNTIME = "adeptj-runtime"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String DIR_DEPLOYMENT = "deployment"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String FRAMEWORK_CONF_FILE = "framework.properties"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String SYS_PROP_SERVER_MODE = "adeptj.rt.mode"; // Path: src/main/java/com/adeptj/runtime/common/Environment.java import java.nio.file.Path; import java.nio.file.Paths; import static com.adeptj.runtime.common.Constants.DIR_ADEPTJ_RUNTIME; import static com.adeptj.runtime.common.Constants.DIR_DEPLOYMENT; import static com.adeptj.runtime.common.Constants.FRAMEWORK_CONF_FILE; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_SERVER_MODE; import static org.apache.commons.lang3.SystemUtils.USER_DIR; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utility methods for getting environment details AdeptJ Runtime is running in. * * @author Rakesh.Kumar, AdeptJ. */ public final class Environment { /** * Deny direct instantiation. */ private Environment() { } public static boolean isDev() { return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); } public static Path getServerConfPath() {
return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, SERVER_CONF_FILE);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/common/Environment.java
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String DIR_ADEPTJ_RUNTIME = "adeptj-runtime"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String DIR_DEPLOYMENT = "deployment"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String FRAMEWORK_CONF_FILE = "framework.properties"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String SYS_PROP_SERVER_MODE = "adeptj.rt.mode";
import java.nio.file.Path; import java.nio.file.Paths; import static com.adeptj.runtime.common.Constants.DIR_ADEPTJ_RUNTIME; import static com.adeptj.runtime.common.Constants.DIR_DEPLOYMENT; import static com.adeptj.runtime.common.Constants.FRAMEWORK_CONF_FILE; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_SERVER_MODE; import static org.apache.commons.lang3.SystemUtils.USER_DIR;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utility methods for getting environment details AdeptJ Runtime is running in. * * @author Rakesh.Kumar, AdeptJ. */ public final class Environment { /** * Deny direct instantiation. */ private Environment() { } public static boolean isDev() { return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); } public static Path getServerConfPath() {
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String DIR_ADEPTJ_RUNTIME = "adeptj-runtime"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String DIR_DEPLOYMENT = "deployment"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String FRAMEWORK_CONF_FILE = "framework.properties"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String SYS_PROP_SERVER_MODE = "adeptj.rt.mode"; // Path: src/main/java/com/adeptj/runtime/common/Environment.java import java.nio.file.Path; import java.nio.file.Paths; import static com.adeptj.runtime.common.Constants.DIR_ADEPTJ_RUNTIME; import static com.adeptj.runtime.common.Constants.DIR_DEPLOYMENT; import static com.adeptj.runtime.common.Constants.FRAMEWORK_CONF_FILE; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_SERVER_MODE; import static org.apache.commons.lang3.SystemUtils.USER_DIR; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utility methods for getting environment details AdeptJ Runtime is running in. * * @author Rakesh.Kumar, AdeptJ. */ public final class Environment { /** * Deny direct instantiation. */ private Environment() { } public static boolean isDev() { return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); } public static Path getServerConfPath() {
return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, SERVER_CONF_FILE);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/common/Environment.java
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String DIR_ADEPTJ_RUNTIME = "adeptj-runtime"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String DIR_DEPLOYMENT = "deployment"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String FRAMEWORK_CONF_FILE = "framework.properties"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String SYS_PROP_SERVER_MODE = "adeptj.rt.mode";
import java.nio.file.Path; import java.nio.file.Paths; import static com.adeptj.runtime.common.Constants.DIR_ADEPTJ_RUNTIME; import static com.adeptj.runtime.common.Constants.DIR_DEPLOYMENT; import static com.adeptj.runtime.common.Constants.FRAMEWORK_CONF_FILE; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_SERVER_MODE; import static org.apache.commons.lang3.SystemUtils.USER_DIR;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utility methods for getting environment details AdeptJ Runtime is running in. * * @author Rakesh.Kumar, AdeptJ. */ public final class Environment { /** * Deny direct instantiation. */ private Environment() { } public static boolean isDev() { return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); } public static Path getServerConfPath() { return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, SERVER_CONF_FILE); } public static Path getFrameworkConfPath() {
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String DIR_ADEPTJ_RUNTIME = "adeptj-runtime"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String DIR_DEPLOYMENT = "deployment"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String FRAMEWORK_CONF_FILE = "framework.properties"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String SYS_PROP_SERVER_MODE = "adeptj.rt.mode"; // Path: src/main/java/com/adeptj/runtime/common/Environment.java import java.nio.file.Path; import java.nio.file.Paths; import static com.adeptj.runtime.common.Constants.DIR_ADEPTJ_RUNTIME; import static com.adeptj.runtime.common.Constants.DIR_DEPLOYMENT; import static com.adeptj.runtime.common.Constants.FRAMEWORK_CONF_FILE; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_SERVER_MODE; import static org.apache.commons.lang3.SystemUtils.USER_DIR; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utility methods for getting environment details AdeptJ Runtime is running in. * * @author Rakesh.Kumar, AdeptJ. */ public final class Environment { /** * Deny direct instantiation. */ private Environment() { } public static boolean isDev() { return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); } public static Path getServerConfPath() { return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, SERVER_CONF_FILE); } public static Path getFrameworkConfPath() {
return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, FRAMEWORK_CONF_FILE);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/handler/ServletInitialHandlerWrapper.java
// Path: src/main/java/com/adeptj/runtime/config/Configs.java // public enum Configs { // // INSTANCE; // // /** // * This will include system properties as well. // */ // private final Config root; // // Configs() { // this.root = this.loadConf(); // } // // public Config root() { // return this.root; // } // // public Config main() { // return this.root.getConfig(MAIN_CONF_SECTION); // } // // public Config undertow() { // return this.main().getConfig(UNDERTOW_CONF_SECTION); // } // // public Config felix() { // return this.main().getConfig(FELIX_CONF_SECTION); // } // // public Config common() { // return this.main().getConfig(COMMON_CONF_SECTION); // } // // public Config logging() { // return this.main().getConfig(LOGGING_CONF_SECTION); // } // // public Config trimou() { // return this.main().getConfig(TRIMOU_CONF_SECTION); // } // // public Config resteasy() { // return this.main().getConfig(RESTEASY_CONF_SECTION); // } // // private Config loadConf() { // Config config; // File configFile = Environment.getServerConfPath().toFile(); // if (configFile.exists()) { // // if overwrite.server.conf.file system property is provided, then load the configs from classpath. // if (Boolean.getBoolean(SYS_PROP_OVERWRITE_SERVER_CONF)) { // config = ConfigFactory.load(SERVER_CONF_FILE); // } else { // config = ConfigFactory.parseFile(configFile) // .withFallback(ConfigFactory.systemProperties()) // .resolve(); // } // } else { // config = ConfigFactory.load(SERVER_CONF_FILE); // } // return config; // } // // public static Configs of() { // return INSTANCE; // } // // }
import com.adeptj.runtime.config.Configs; import com.typesafe.config.Config; import io.undertow.Handlers; import io.undertow.predicate.Predicate; import io.undertow.predicate.Predicates; import io.undertow.server.HandlerWrapper; import io.undertow.server.HttpHandler; import io.undertow.server.handlers.resource.ClassPathResourceManager; import io.undertow.servlet.handlers.ServletInitialHandler;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.handler; /** * Handler returned by this HandlerWrapper is invoked before any Servlet handlers are invoked. * <p> * Here it registers Undertow's ClassPath based ResourceHandler for serving static content. * If the Predicate grouping is true then it invokes the non blocking ResourceHandler * completely bypassing security handler chain, which is desirable as we don't need security * and blocking I/O to kick in while serving static content. * <p> * Undertow order of precedence to invoke HandlerChainWrapper(s). * <p> * 1. OuterHandlerChainWrapper - Run after the servlet initial handler, but before any other handlers. * These are only run on REQUEST invocations, they are not invoked on a FORWARD or INCLUDE. * <p> * 2. InnerHandlerChainWrapper - This handler will run after the security handler, but before any other * servlet handlers, and will run for every request. * <p> * 3. InitialHandlerChainWrapper - Run before security and servlet initial handler. * * @author Rakesh.Kumar, AdeptJ */ public final class ServletInitialHandlerWrapper implements HandlerWrapper { private static final String RESOURCE_PREFIX = "common.static-resource-prefix"; private static final String RESOURCE_EXTNS = "common.static-resource-extns"; private static final String RESOURCE_MGR_PREFIX = "common.resource-mgr-prefix"; /** * Wraps the passed {@link ServletInitialHandler} with a PredicateHandler for serving static content. * * @param servletInitialHandler the ServletInitialHandler * @return PredicateHandler which decides whether to invoke ResourceHandler or pass on the request to * next handler in the chain which is ServletInitialHandler. * @see ServletInitialHandlerWrapper class header for detailed information. */ @Override public HttpHandler wrap(HttpHandler servletInitialHandler) {
// Path: src/main/java/com/adeptj/runtime/config/Configs.java // public enum Configs { // // INSTANCE; // // /** // * This will include system properties as well. // */ // private final Config root; // // Configs() { // this.root = this.loadConf(); // } // // public Config root() { // return this.root; // } // // public Config main() { // return this.root.getConfig(MAIN_CONF_SECTION); // } // // public Config undertow() { // return this.main().getConfig(UNDERTOW_CONF_SECTION); // } // // public Config felix() { // return this.main().getConfig(FELIX_CONF_SECTION); // } // // public Config common() { // return this.main().getConfig(COMMON_CONF_SECTION); // } // // public Config logging() { // return this.main().getConfig(LOGGING_CONF_SECTION); // } // // public Config trimou() { // return this.main().getConfig(TRIMOU_CONF_SECTION); // } // // public Config resteasy() { // return this.main().getConfig(RESTEASY_CONF_SECTION); // } // // private Config loadConf() { // Config config; // File configFile = Environment.getServerConfPath().toFile(); // if (configFile.exists()) { // // if overwrite.server.conf.file system property is provided, then load the configs from classpath. // if (Boolean.getBoolean(SYS_PROP_OVERWRITE_SERVER_CONF)) { // config = ConfigFactory.load(SERVER_CONF_FILE); // } else { // config = ConfigFactory.parseFile(configFile) // .withFallback(ConfigFactory.systemProperties()) // .resolve(); // } // } else { // config = ConfigFactory.load(SERVER_CONF_FILE); // } // return config; // } // // public static Configs of() { // return INSTANCE; // } // // } // Path: src/main/java/com/adeptj/runtime/handler/ServletInitialHandlerWrapper.java import com.adeptj.runtime.config.Configs; import com.typesafe.config.Config; import io.undertow.Handlers; import io.undertow.predicate.Predicate; import io.undertow.predicate.Predicates; import io.undertow.server.HandlerWrapper; import io.undertow.server.HttpHandler; import io.undertow.server.handlers.resource.ClassPathResourceManager; import io.undertow.servlet.handlers.ServletInitialHandler; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.handler; /** * Handler returned by this HandlerWrapper is invoked before any Servlet handlers are invoked. * <p> * Here it registers Undertow's ClassPath based ResourceHandler for serving static content. * If the Predicate grouping is true then it invokes the non blocking ResourceHandler * completely bypassing security handler chain, which is desirable as we don't need security * and blocking I/O to kick in while serving static content. * <p> * Undertow order of precedence to invoke HandlerChainWrapper(s). * <p> * 1. OuterHandlerChainWrapper - Run after the servlet initial handler, but before any other handlers. * These are only run on REQUEST invocations, they are not invoked on a FORWARD or INCLUDE. * <p> * 2. InnerHandlerChainWrapper - This handler will run after the security handler, but before any other * servlet handlers, and will run for every request. * <p> * 3. InitialHandlerChainWrapper - Run before security and servlet initial handler. * * @author Rakesh.Kumar, AdeptJ */ public final class ServletInitialHandlerWrapper implements HandlerWrapper { private static final String RESOURCE_PREFIX = "common.static-resource-prefix"; private static final String RESOURCE_EXTNS = "common.static-resource-extns"; private static final String RESOURCE_MGR_PREFIX = "common.resource-mgr-prefix"; /** * Wraps the passed {@link ServletInitialHandler} with a PredicateHandler for serving static content. * * @param servletInitialHandler the ServletInitialHandler * @return PredicateHandler which decides whether to invoke ResourceHandler or pass on the request to * next handler in the chain which is ServletInitialHandler. * @see ServletInitialHandlerWrapper class header for detailed information. */ @Override public HttpHandler wrap(HttpHandler servletInitialHandler) {
Config cfg = Configs.of().undertow();
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/common/SslContextFactory.java
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_KEYSTORE_TYPE = "keystore-type"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_FILE_LOCATION = "p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_PASSWORD = "p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_TLS_VERSION = "tlsVersion"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_EXTERNAL = "adeptj.rt.p12-file-external"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_LOCATION = "adeptj.rt.p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_PASSWORD = "adeptj.rt.p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_TLS_VERSION = "tls.version";
import static com.adeptj.runtime.common.Constants.KEY_TLS_VERSION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_EXTERNAL; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_PASSWORD; import static com.adeptj.runtime.common.Constants.SYS_PROP_TLS_VERSION; import com.typesafe.config.Config; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import java.security.GeneralSecurityException; import java.security.KeyStore; import static com.adeptj.runtime.common.Constants.KEY_KEYSTORE_TYPE; import static com.adeptj.runtime.common.Constants.KEY_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.KEY_P12_PASSWORD;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utilities for SSL/TLS. * * @author Rakesh.Kumar, AdeptJ */ public final class SslContextFactory { private SslContextFactory() { } public static SSLContext newSslContext(Config httpsConf) throws GeneralSecurityException { String p12Loc; char[] p12Pwd;
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_KEYSTORE_TYPE = "keystore-type"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_FILE_LOCATION = "p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_PASSWORD = "p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_TLS_VERSION = "tlsVersion"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_EXTERNAL = "adeptj.rt.p12-file-external"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_LOCATION = "adeptj.rt.p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_PASSWORD = "adeptj.rt.p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_TLS_VERSION = "tls.version"; // Path: src/main/java/com/adeptj/runtime/common/SslContextFactory.java import static com.adeptj.runtime.common.Constants.KEY_TLS_VERSION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_EXTERNAL; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_PASSWORD; import static com.adeptj.runtime.common.Constants.SYS_PROP_TLS_VERSION; import com.typesafe.config.Config; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import java.security.GeneralSecurityException; import java.security.KeyStore; import static com.adeptj.runtime.common.Constants.KEY_KEYSTORE_TYPE; import static com.adeptj.runtime.common.Constants.KEY_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.KEY_P12_PASSWORD; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utilities for SSL/TLS. * * @author Rakesh.Kumar, AdeptJ */ public final class SslContextFactory { private SslContextFactory() { } public static SSLContext newSslContext(Config httpsConf) throws GeneralSecurityException { String p12Loc; char[] p12Pwd;
boolean p12FileExternal = Boolean.getBoolean(SYS_PROP_P12_FILE_EXTERNAL);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/common/SslContextFactory.java
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_KEYSTORE_TYPE = "keystore-type"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_FILE_LOCATION = "p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_PASSWORD = "p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_TLS_VERSION = "tlsVersion"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_EXTERNAL = "adeptj.rt.p12-file-external"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_LOCATION = "adeptj.rt.p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_PASSWORD = "adeptj.rt.p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_TLS_VERSION = "tls.version";
import static com.adeptj.runtime.common.Constants.KEY_TLS_VERSION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_EXTERNAL; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_PASSWORD; import static com.adeptj.runtime.common.Constants.SYS_PROP_TLS_VERSION; import com.typesafe.config.Config; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import java.security.GeneralSecurityException; import java.security.KeyStore; import static com.adeptj.runtime.common.Constants.KEY_KEYSTORE_TYPE; import static com.adeptj.runtime.common.Constants.KEY_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.KEY_P12_PASSWORD;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utilities for SSL/TLS. * * @author Rakesh.Kumar, AdeptJ */ public final class SslContextFactory { private SslContextFactory() { } public static SSLContext newSslContext(Config httpsConf) throws GeneralSecurityException { String p12Loc; char[] p12Pwd; boolean p12FileExternal = Boolean.getBoolean(SYS_PROP_P12_FILE_EXTERNAL); if (p12FileExternal) {
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_KEYSTORE_TYPE = "keystore-type"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_FILE_LOCATION = "p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_PASSWORD = "p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_TLS_VERSION = "tlsVersion"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_EXTERNAL = "adeptj.rt.p12-file-external"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_LOCATION = "adeptj.rt.p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_PASSWORD = "adeptj.rt.p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_TLS_VERSION = "tls.version"; // Path: src/main/java/com/adeptj/runtime/common/SslContextFactory.java import static com.adeptj.runtime.common.Constants.KEY_TLS_VERSION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_EXTERNAL; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_PASSWORD; import static com.adeptj.runtime.common.Constants.SYS_PROP_TLS_VERSION; import com.typesafe.config.Config; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import java.security.GeneralSecurityException; import java.security.KeyStore; import static com.adeptj.runtime.common.Constants.KEY_KEYSTORE_TYPE; import static com.adeptj.runtime.common.Constants.KEY_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.KEY_P12_PASSWORD; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utilities for SSL/TLS. * * @author Rakesh.Kumar, AdeptJ */ public final class SslContextFactory { private SslContextFactory() { } public static SSLContext newSslContext(Config httpsConf) throws GeneralSecurityException { String p12Loc; char[] p12Pwd; boolean p12FileExternal = Boolean.getBoolean(SYS_PROP_P12_FILE_EXTERNAL); if (p12FileExternal) {
p12Loc = System.getProperty(SYS_PROP_P12_FILE_LOCATION);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/common/SslContextFactory.java
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_KEYSTORE_TYPE = "keystore-type"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_FILE_LOCATION = "p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_PASSWORD = "p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_TLS_VERSION = "tlsVersion"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_EXTERNAL = "adeptj.rt.p12-file-external"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_LOCATION = "adeptj.rt.p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_PASSWORD = "adeptj.rt.p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_TLS_VERSION = "tls.version";
import static com.adeptj.runtime.common.Constants.KEY_TLS_VERSION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_EXTERNAL; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_PASSWORD; import static com.adeptj.runtime.common.Constants.SYS_PROP_TLS_VERSION; import com.typesafe.config.Config; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import java.security.GeneralSecurityException; import java.security.KeyStore; import static com.adeptj.runtime.common.Constants.KEY_KEYSTORE_TYPE; import static com.adeptj.runtime.common.Constants.KEY_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.KEY_P12_PASSWORD;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utilities for SSL/TLS. * * @author Rakesh.Kumar, AdeptJ */ public final class SslContextFactory { private SslContextFactory() { } public static SSLContext newSslContext(Config httpsConf) throws GeneralSecurityException { String p12Loc; char[] p12Pwd; boolean p12FileExternal = Boolean.getBoolean(SYS_PROP_P12_FILE_EXTERNAL); if (p12FileExternal) { p12Loc = System.getProperty(SYS_PROP_P12_FILE_LOCATION);
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_KEYSTORE_TYPE = "keystore-type"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_FILE_LOCATION = "p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_PASSWORD = "p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_TLS_VERSION = "tlsVersion"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_EXTERNAL = "adeptj.rt.p12-file-external"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_LOCATION = "adeptj.rt.p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_PASSWORD = "adeptj.rt.p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_TLS_VERSION = "tls.version"; // Path: src/main/java/com/adeptj/runtime/common/SslContextFactory.java import static com.adeptj.runtime.common.Constants.KEY_TLS_VERSION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_EXTERNAL; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_PASSWORD; import static com.adeptj.runtime.common.Constants.SYS_PROP_TLS_VERSION; import com.typesafe.config.Config; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import java.security.GeneralSecurityException; import java.security.KeyStore; import static com.adeptj.runtime.common.Constants.KEY_KEYSTORE_TYPE; import static com.adeptj.runtime.common.Constants.KEY_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.KEY_P12_PASSWORD; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utilities for SSL/TLS. * * @author Rakesh.Kumar, AdeptJ */ public final class SslContextFactory { private SslContextFactory() { } public static SSLContext newSslContext(Config httpsConf) throws GeneralSecurityException { String p12Loc; char[] p12Pwd; boolean p12FileExternal = Boolean.getBoolean(SYS_PROP_P12_FILE_EXTERNAL); if (p12FileExternal) { p12Loc = System.getProperty(SYS_PROP_P12_FILE_LOCATION);
p12Pwd = System.getProperty(SYS_PROP_P12_PASSWORD).toCharArray();
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/common/SslContextFactory.java
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_KEYSTORE_TYPE = "keystore-type"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_FILE_LOCATION = "p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_PASSWORD = "p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_TLS_VERSION = "tlsVersion"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_EXTERNAL = "adeptj.rt.p12-file-external"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_LOCATION = "adeptj.rt.p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_PASSWORD = "adeptj.rt.p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_TLS_VERSION = "tls.version";
import static com.adeptj.runtime.common.Constants.KEY_TLS_VERSION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_EXTERNAL; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_PASSWORD; import static com.adeptj.runtime.common.Constants.SYS_PROP_TLS_VERSION; import com.typesafe.config.Config; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import java.security.GeneralSecurityException; import java.security.KeyStore; import static com.adeptj.runtime.common.Constants.KEY_KEYSTORE_TYPE; import static com.adeptj.runtime.common.Constants.KEY_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.KEY_P12_PASSWORD;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utilities for SSL/TLS. * * @author Rakesh.Kumar, AdeptJ */ public final class SslContextFactory { private SslContextFactory() { } public static SSLContext newSslContext(Config httpsConf) throws GeneralSecurityException { String p12Loc; char[] p12Pwd; boolean p12FileExternal = Boolean.getBoolean(SYS_PROP_P12_FILE_EXTERNAL); if (p12FileExternal) { p12Loc = System.getProperty(SYS_PROP_P12_FILE_LOCATION); p12Pwd = System.getProperty(SYS_PROP_P12_PASSWORD).toCharArray(); } else {
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_KEYSTORE_TYPE = "keystore-type"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_FILE_LOCATION = "p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_PASSWORD = "p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_TLS_VERSION = "tlsVersion"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_EXTERNAL = "adeptj.rt.p12-file-external"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_LOCATION = "adeptj.rt.p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_PASSWORD = "adeptj.rt.p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_TLS_VERSION = "tls.version"; // Path: src/main/java/com/adeptj/runtime/common/SslContextFactory.java import static com.adeptj.runtime.common.Constants.KEY_TLS_VERSION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_EXTERNAL; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_PASSWORD; import static com.adeptj.runtime.common.Constants.SYS_PROP_TLS_VERSION; import com.typesafe.config.Config; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import java.security.GeneralSecurityException; import java.security.KeyStore; import static com.adeptj.runtime.common.Constants.KEY_KEYSTORE_TYPE; import static com.adeptj.runtime.common.Constants.KEY_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.KEY_P12_PASSWORD; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utilities for SSL/TLS. * * @author Rakesh.Kumar, AdeptJ */ public final class SslContextFactory { private SslContextFactory() { } public static SSLContext newSslContext(Config httpsConf) throws GeneralSecurityException { String p12Loc; char[] p12Pwd; boolean p12FileExternal = Boolean.getBoolean(SYS_PROP_P12_FILE_EXTERNAL); if (p12FileExternal) { p12Loc = System.getProperty(SYS_PROP_P12_FILE_LOCATION); p12Pwd = System.getProperty(SYS_PROP_P12_PASSWORD).toCharArray(); } else {
p12Loc = httpsConf.getString(KEY_P12_FILE_LOCATION);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/common/SslContextFactory.java
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_KEYSTORE_TYPE = "keystore-type"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_FILE_LOCATION = "p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_PASSWORD = "p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_TLS_VERSION = "tlsVersion"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_EXTERNAL = "adeptj.rt.p12-file-external"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_LOCATION = "adeptj.rt.p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_PASSWORD = "adeptj.rt.p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_TLS_VERSION = "tls.version";
import static com.adeptj.runtime.common.Constants.KEY_TLS_VERSION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_EXTERNAL; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_PASSWORD; import static com.adeptj.runtime.common.Constants.SYS_PROP_TLS_VERSION; import com.typesafe.config.Config; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import java.security.GeneralSecurityException; import java.security.KeyStore; import static com.adeptj.runtime.common.Constants.KEY_KEYSTORE_TYPE; import static com.adeptj.runtime.common.Constants.KEY_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.KEY_P12_PASSWORD;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utilities for SSL/TLS. * * @author Rakesh.Kumar, AdeptJ */ public final class SslContextFactory { private SslContextFactory() { } public static SSLContext newSslContext(Config httpsConf) throws GeneralSecurityException { String p12Loc; char[] p12Pwd; boolean p12FileExternal = Boolean.getBoolean(SYS_PROP_P12_FILE_EXTERNAL); if (p12FileExternal) { p12Loc = System.getProperty(SYS_PROP_P12_FILE_LOCATION); p12Pwd = System.getProperty(SYS_PROP_P12_PASSWORD).toCharArray(); } else { p12Loc = httpsConf.getString(KEY_P12_FILE_LOCATION);
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_KEYSTORE_TYPE = "keystore-type"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_FILE_LOCATION = "p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_PASSWORD = "p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_TLS_VERSION = "tlsVersion"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_EXTERNAL = "adeptj.rt.p12-file-external"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_LOCATION = "adeptj.rt.p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_PASSWORD = "adeptj.rt.p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_TLS_VERSION = "tls.version"; // Path: src/main/java/com/adeptj/runtime/common/SslContextFactory.java import static com.adeptj.runtime.common.Constants.KEY_TLS_VERSION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_EXTERNAL; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_PASSWORD; import static com.adeptj.runtime.common.Constants.SYS_PROP_TLS_VERSION; import com.typesafe.config.Config; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import java.security.GeneralSecurityException; import java.security.KeyStore; import static com.adeptj.runtime.common.Constants.KEY_KEYSTORE_TYPE; import static com.adeptj.runtime.common.Constants.KEY_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.KEY_P12_PASSWORD; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utilities for SSL/TLS. * * @author Rakesh.Kumar, AdeptJ */ public final class SslContextFactory { private SslContextFactory() { } public static SSLContext newSslContext(Config httpsConf) throws GeneralSecurityException { String p12Loc; char[] p12Pwd; boolean p12FileExternal = Boolean.getBoolean(SYS_PROP_P12_FILE_EXTERNAL); if (p12FileExternal) { p12Loc = System.getProperty(SYS_PROP_P12_FILE_LOCATION); p12Pwd = System.getProperty(SYS_PROP_P12_PASSWORD).toCharArray(); } else { p12Loc = httpsConf.getString(KEY_P12_FILE_LOCATION);
p12Pwd = httpsConf.getString(KEY_P12_PASSWORD).toCharArray();
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/common/SslContextFactory.java
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_KEYSTORE_TYPE = "keystore-type"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_FILE_LOCATION = "p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_PASSWORD = "p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_TLS_VERSION = "tlsVersion"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_EXTERNAL = "adeptj.rt.p12-file-external"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_LOCATION = "adeptj.rt.p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_PASSWORD = "adeptj.rt.p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_TLS_VERSION = "tls.version";
import static com.adeptj.runtime.common.Constants.KEY_TLS_VERSION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_EXTERNAL; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_PASSWORD; import static com.adeptj.runtime.common.Constants.SYS_PROP_TLS_VERSION; import com.typesafe.config.Config; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import java.security.GeneralSecurityException; import java.security.KeyStore; import static com.adeptj.runtime.common.Constants.KEY_KEYSTORE_TYPE; import static com.adeptj.runtime.common.Constants.KEY_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.KEY_P12_PASSWORD;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utilities for SSL/TLS. * * @author Rakesh.Kumar, AdeptJ */ public final class SslContextFactory { private SslContextFactory() { } public static SSLContext newSslContext(Config httpsConf) throws GeneralSecurityException { String p12Loc; char[] p12Pwd; boolean p12FileExternal = Boolean.getBoolean(SYS_PROP_P12_FILE_EXTERNAL); if (p12FileExternal) { p12Loc = System.getProperty(SYS_PROP_P12_FILE_LOCATION); p12Pwd = System.getProperty(SYS_PROP_P12_PASSWORD).toCharArray(); } else { p12Loc = httpsConf.getString(KEY_P12_FILE_LOCATION); p12Pwd = httpsConf.getString(KEY_P12_PASSWORD).toCharArray(); }
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_KEYSTORE_TYPE = "keystore-type"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_FILE_LOCATION = "p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_PASSWORD = "p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_TLS_VERSION = "tlsVersion"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_EXTERNAL = "adeptj.rt.p12-file-external"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_LOCATION = "adeptj.rt.p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_PASSWORD = "adeptj.rt.p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_TLS_VERSION = "tls.version"; // Path: src/main/java/com/adeptj/runtime/common/SslContextFactory.java import static com.adeptj.runtime.common.Constants.KEY_TLS_VERSION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_EXTERNAL; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_PASSWORD; import static com.adeptj.runtime.common.Constants.SYS_PROP_TLS_VERSION; import com.typesafe.config.Config; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import java.security.GeneralSecurityException; import java.security.KeyStore; import static com.adeptj.runtime.common.Constants.KEY_KEYSTORE_TYPE; import static com.adeptj.runtime.common.Constants.KEY_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.KEY_P12_PASSWORD; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utilities for SSL/TLS. * * @author Rakesh.Kumar, AdeptJ */ public final class SslContextFactory { private SslContextFactory() { } public static SSLContext newSslContext(Config httpsConf) throws GeneralSecurityException { String p12Loc; char[] p12Pwd; boolean p12FileExternal = Boolean.getBoolean(SYS_PROP_P12_FILE_EXTERNAL); if (p12FileExternal) { p12Loc = System.getProperty(SYS_PROP_P12_FILE_LOCATION); p12Pwd = System.getProperty(SYS_PROP_P12_PASSWORD).toCharArray(); } else { p12Loc = httpsConf.getString(KEY_P12_FILE_LOCATION); p12Pwd = httpsConf.getString(KEY_P12_PASSWORD).toCharArray(); }
String keyStoreType = httpsConf.getString(KEY_KEYSTORE_TYPE);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/common/SslContextFactory.java
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_KEYSTORE_TYPE = "keystore-type"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_FILE_LOCATION = "p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_PASSWORD = "p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_TLS_VERSION = "tlsVersion"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_EXTERNAL = "adeptj.rt.p12-file-external"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_LOCATION = "adeptj.rt.p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_PASSWORD = "adeptj.rt.p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_TLS_VERSION = "tls.version";
import static com.adeptj.runtime.common.Constants.KEY_TLS_VERSION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_EXTERNAL; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_PASSWORD; import static com.adeptj.runtime.common.Constants.SYS_PROP_TLS_VERSION; import com.typesafe.config.Config; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import java.security.GeneralSecurityException; import java.security.KeyStore; import static com.adeptj.runtime.common.Constants.KEY_KEYSTORE_TYPE; import static com.adeptj.runtime.common.Constants.KEY_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.KEY_P12_PASSWORD;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utilities for SSL/TLS. * * @author Rakesh.Kumar, AdeptJ */ public final class SslContextFactory { private SslContextFactory() { } public static SSLContext newSslContext(Config httpsConf) throws GeneralSecurityException { String p12Loc; char[] p12Pwd; boolean p12FileExternal = Boolean.getBoolean(SYS_PROP_P12_FILE_EXTERNAL); if (p12FileExternal) { p12Loc = System.getProperty(SYS_PROP_P12_FILE_LOCATION); p12Pwd = System.getProperty(SYS_PROP_P12_PASSWORD).toCharArray(); } else { p12Loc = httpsConf.getString(KEY_P12_FILE_LOCATION); p12Pwd = httpsConf.getString(KEY_P12_PASSWORD).toCharArray(); } String keyStoreType = httpsConf.getString(KEY_KEYSTORE_TYPE); KeyStore keyStore = KeyStores.getKeyStore(p12FileExternal, keyStoreType, p12Loc, p12Pwd); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keyStore, p12Pwd);
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_KEYSTORE_TYPE = "keystore-type"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_FILE_LOCATION = "p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_PASSWORD = "p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_TLS_VERSION = "tlsVersion"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_EXTERNAL = "adeptj.rt.p12-file-external"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_LOCATION = "adeptj.rt.p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_PASSWORD = "adeptj.rt.p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_TLS_VERSION = "tls.version"; // Path: src/main/java/com/adeptj/runtime/common/SslContextFactory.java import static com.adeptj.runtime.common.Constants.KEY_TLS_VERSION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_EXTERNAL; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_PASSWORD; import static com.adeptj.runtime.common.Constants.SYS_PROP_TLS_VERSION; import com.typesafe.config.Config; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import java.security.GeneralSecurityException; import java.security.KeyStore; import static com.adeptj.runtime.common.Constants.KEY_KEYSTORE_TYPE; import static com.adeptj.runtime.common.Constants.KEY_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.KEY_P12_PASSWORD; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utilities for SSL/TLS. * * @author Rakesh.Kumar, AdeptJ */ public final class SslContextFactory { private SslContextFactory() { } public static SSLContext newSslContext(Config httpsConf) throws GeneralSecurityException { String p12Loc; char[] p12Pwd; boolean p12FileExternal = Boolean.getBoolean(SYS_PROP_P12_FILE_EXTERNAL); if (p12FileExternal) { p12Loc = System.getProperty(SYS_PROP_P12_FILE_LOCATION); p12Pwd = System.getProperty(SYS_PROP_P12_PASSWORD).toCharArray(); } else { p12Loc = httpsConf.getString(KEY_P12_FILE_LOCATION); p12Pwd = httpsConf.getString(KEY_P12_PASSWORD).toCharArray(); } String keyStoreType = httpsConf.getString(KEY_KEYSTORE_TYPE); KeyStore keyStore = KeyStores.getKeyStore(p12FileExternal, keyStoreType, p12Loc, p12Pwd); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keyStore, p12Pwd);
String protocol = System.getProperty(SYS_PROP_TLS_VERSION, httpsConf.getString(KEY_TLS_VERSION));
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/common/SslContextFactory.java
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_KEYSTORE_TYPE = "keystore-type"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_FILE_LOCATION = "p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_PASSWORD = "p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_TLS_VERSION = "tlsVersion"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_EXTERNAL = "adeptj.rt.p12-file-external"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_LOCATION = "adeptj.rt.p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_PASSWORD = "adeptj.rt.p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_TLS_VERSION = "tls.version";
import static com.adeptj.runtime.common.Constants.KEY_TLS_VERSION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_EXTERNAL; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_PASSWORD; import static com.adeptj.runtime.common.Constants.SYS_PROP_TLS_VERSION; import com.typesafe.config.Config; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import java.security.GeneralSecurityException; import java.security.KeyStore; import static com.adeptj.runtime.common.Constants.KEY_KEYSTORE_TYPE; import static com.adeptj.runtime.common.Constants.KEY_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.KEY_P12_PASSWORD;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utilities for SSL/TLS. * * @author Rakesh.Kumar, AdeptJ */ public final class SslContextFactory { private SslContextFactory() { } public static SSLContext newSslContext(Config httpsConf) throws GeneralSecurityException { String p12Loc; char[] p12Pwd; boolean p12FileExternal = Boolean.getBoolean(SYS_PROP_P12_FILE_EXTERNAL); if (p12FileExternal) { p12Loc = System.getProperty(SYS_PROP_P12_FILE_LOCATION); p12Pwd = System.getProperty(SYS_PROP_P12_PASSWORD).toCharArray(); } else { p12Loc = httpsConf.getString(KEY_P12_FILE_LOCATION); p12Pwd = httpsConf.getString(KEY_P12_PASSWORD).toCharArray(); } String keyStoreType = httpsConf.getString(KEY_KEYSTORE_TYPE); KeyStore keyStore = KeyStores.getKeyStore(p12FileExternal, keyStoreType, p12Loc, p12Pwd); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keyStore, p12Pwd);
// Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_KEYSTORE_TYPE = "keystore-type"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_FILE_LOCATION = "p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String KEY_P12_PASSWORD = "p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // static final String KEY_TLS_VERSION = "tlsVersion"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_EXTERNAL = "adeptj.rt.p12-file-external"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_FILE_LOCATION = "adeptj.rt.p12-file-location"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_P12_PASSWORD = "adeptj.rt.p12-password"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_TLS_VERSION = "tls.version"; // Path: src/main/java/com/adeptj/runtime/common/SslContextFactory.java import static com.adeptj.runtime.common.Constants.KEY_TLS_VERSION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_EXTERNAL; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.SYS_PROP_P12_PASSWORD; import static com.adeptj.runtime.common.Constants.SYS_PROP_TLS_VERSION; import com.typesafe.config.Config; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import java.security.GeneralSecurityException; import java.security.KeyStore; import static com.adeptj.runtime.common.Constants.KEY_KEYSTORE_TYPE; import static com.adeptj.runtime.common.Constants.KEY_P12_FILE_LOCATION; import static com.adeptj.runtime.common.Constants.KEY_P12_PASSWORD; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utilities for SSL/TLS. * * @author Rakesh.Kumar, AdeptJ */ public final class SslContextFactory { private SslContextFactory() { } public static SSLContext newSslContext(Config httpsConf) throws GeneralSecurityException { String p12Loc; char[] p12Pwd; boolean p12FileExternal = Boolean.getBoolean(SYS_PROP_P12_FILE_EXTERNAL); if (p12FileExternal) { p12Loc = System.getProperty(SYS_PROP_P12_FILE_LOCATION); p12Pwd = System.getProperty(SYS_PROP_P12_PASSWORD).toCharArray(); } else { p12Loc = httpsConf.getString(KEY_P12_FILE_LOCATION); p12Pwd = httpsConf.getString(KEY_P12_PASSWORD).toCharArray(); } String keyStoreType = httpsConf.getString(KEY_KEYSTORE_TYPE); KeyStore keyStore = KeyStores.getKeyStore(p12FileExternal, keyStoreType, p12Loc, p12Pwd); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keyStore, p12Pwd);
String protocol = System.getProperty(SYS_PROP_TLS_VERSION, httpsConf.getString(KEY_TLS_VERSION));
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/config/Configs.java
// Path: src/main/java/com/adeptj/runtime/common/Environment.java // public final class Environment { // // /** // * Deny direct instantiation. // */ // private Environment() { // } // // public static boolean isDev() { // return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); // } // // public static Path getServerConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, SERVER_CONF_FILE); // } // // public static Path getFrameworkConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, FRAMEWORK_CONF_FILE); // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String COMMON_CONF_SECTION = "common"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String FELIX_CONF_SECTION = "felix"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String LOGGING_CONF_SECTION = "logging"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String MAIN_CONF_SECTION = "main"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String RESTEASY_CONF_SECTION = "resteasy"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_OVERWRITE_SERVER_CONF = "overwrite.server.conf.file"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String TRIMOU_CONF_SECTION = "trimou"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String UNDERTOW_CONF_SECTION = "undertow";
import static com.adeptj.runtime.common.Constants.RESTEASY_CONF_SECTION; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_OVERWRITE_SERVER_CONF; import static com.adeptj.runtime.common.Constants.TRIMOU_CONF_SECTION; import static com.adeptj.runtime.common.Constants.UNDERTOW_CONF_SECTION; import com.adeptj.runtime.common.Environment; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.io.File; import static com.adeptj.runtime.common.Constants.COMMON_CONF_SECTION; import static com.adeptj.runtime.common.Constants.FELIX_CONF_SECTION; import static com.adeptj.runtime.common.Constants.LOGGING_CONF_SECTION; import static com.adeptj.runtime.common.Constants.MAIN_CONF_SECTION;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.config; /** * Initializes the application configurations. * * @author Rakesh.Kumar, AdeptJ */ public enum Configs { INSTANCE; /** * This will include system properties as well. */ private final Config root; Configs() { this.root = this.loadConf(); } public Config root() { return this.root; } public Config main() {
// Path: src/main/java/com/adeptj/runtime/common/Environment.java // public final class Environment { // // /** // * Deny direct instantiation. // */ // private Environment() { // } // // public static boolean isDev() { // return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); // } // // public static Path getServerConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, SERVER_CONF_FILE); // } // // public static Path getFrameworkConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, FRAMEWORK_CONF_FILE); // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String COMMON_CONF_SECTION = "common"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String FELIX_CONF_SECTION = "felix"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String LOGGING_CONF_SECTION = "logging"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String MAIN_CONF_SECTION = "main"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String RESTEASY_CONF_SECTION = "resteasy"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_OVERWRITE_SERVER_CONF = "overwrite.server.conf.file"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String TRIMOU_CONF_SECTION = "trimou"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String UNDERTOW_CONF_SECTION = "undertow"; // Path: src/main/java/com/adeptj/runtime/config/Configs.java import static com.adeptj.runtime.common.Constants.RESTEASY_CONF_SECTION; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_OVERWRITE_SERVER_CONF; import static com.adeptj.runtime.common.Constants.TRIMOU_CONF_SECTION; import static com.adeptj.runtime.common.Constants.UNDERTOW_CONF_SECTION; import com.adeptj.runtime.common.Environment; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.io.File; import static com.adeptj.runtime.common.Constants.COMMON_CONF_SECTION; import static com.adeptj.runtime.common.Constants.FELIX_CONF_SECTION; import static com.adeptj.runtime.common.Constants.LOGGING_CONF_SECTION; import static com.adeptj.runtime.common.Constants.MAIN_CONF_SECTION; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.config; /** * Initializes the application configurations. * * @author Rakesh.Kumar, AdeptJ */ public enum Configs { INSTANCE; /** * This will include system properties as well. */ private final Config root; Configs() { this.root = this.loadConf(); } public Config root() { return this.root; } public Config main() {
return this.root.getConfig(MAIN_CONF_SECTION);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/config/Configs.java
// Path: src/main/java/com/adeptj/runtime/common/Environment.java // public final class Environment { // // /** // * Deny direct instantiation. // */ // private Environment() { // } // // public static boolean isDev() { // return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); // } // // public static Path getServerConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, SERVER_CONF_FILE); // } // // public static Path getFrameworkConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, FRAMEWORK_CONF_FILE); // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String COMMON_CONF_SECTION = "common"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String FELIX_CONF_SECTION = "felix"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String LOGGING_CONF_SECTION = "logging"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String MAIN_CONF_SECTION = "main"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String RESTEASY_CONF_SECTION = "resteasy"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_OVERWRITE_SERVER_CONF = "overwrite.server.conf.file"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String TRIMOU_CONF_SECTION = "trimou"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String UNDERTOW_CONF_SECTION = "undertow";
import static com.adeptj.runtime.common.Constants.RESTEASY_CONF_SECTION; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_OVERWRITE_SERVER_CONF; import static com.adeptj.runtime.common.Constants.TRIMOU_CONF_SECTION; import static com.adeptj.runtime.common.Constants.UNDERTOW_CONF_SECTION; import com.adeptj.runtime.common.Environment; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.io.File; import static com.adeptj.runtime.common.Constants.COMMON_CONF_SECTION; import static com.adeptj.runtime.common.Constants.FELIX_CONF_SECTION; import static com.adeptj.runtime.common.Constants.LOGGING_CONF_SECTION; import static com.adeptj.runtime.common.Constants.MAIN_CONF_SECTION;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.config; /** * Initializes the application configurations. * * @author Rakesh.Kumar, AdeptJ */ public enum Configs { INSTANCE; /** * This will include system properties as well. */ private final Config root; Configs() { this.root = this.loadConf(); } public Config root() { return this.root; } public Config main() { return this.root.getConfig(MAIN_CONF_SECTION); } public Config undertow() {
// Path: src/main/java/com/adeptj/runtime/common/Environment.java // public final class Environment { // // /** // * Deny direct instantiation. // */ // private Environment() { // } // // public static boolean isDev() { // return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); // } // // public static Path getServerConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, SERVER_CONF_FILE); // } // // public static Path getFrameworkConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, FRAMEWORK_CONF_FILE); // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String COMMON_CONF_SECTION = "common"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String FELIX_CONF_SECTION = "felix"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String LOGGING_CONF_SECTION = "logging"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String MAIN_CONF_SECTION = "main"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String RESTEASY_CONF_SECTION = "resteasy"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_OVERWRITE_SERVER_CONF = "overwrite.server.conf.file"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String TRIMOU_CONF_SECTION = "trimou"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String UNDERTOW_CONF_SECTION = "undertow"; // Path: src/main/java/com/adeptj/runtime/config/Configs.java import static com.adeptj.runtime.common.Constants.RESTEASY_CONF_SECTION; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_OVERWRITE_SERVER_CONF; import static com.adeptj.runtime.common.Constants.TRIMOU_CONF_SECTION; import static com.adeptj.runtime.common.Constants.UNDERTOW_CONF_SECTION; import com.adeptj.runtime.common.Environment; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.io.File; import static com.adeptj.runtime.common.Constants.COMMON_CONF_SECTION; import static com.adeptj.runtime.common.Constants.FELIX_CONF_SECTION; import static com.adeptj.runtime.common.Constants.LOGGING_CONF_SECTION; import static com.adeptj.runtime.common.Constants.MAIN_CONF_SECTION; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.config; /** * Initializes the application configurations. * * @author Rakesh.Kumar, AdeptJ */ public enum Configs { INSTANCE; /** * This will include system properties as well. */ private final Config root; Configs() { this.root = this.loadConf(); } public Config root() { return this.root; } public Config main() { return this.root.getConfig(MAIN_CONF_SECTION); } public Config undertow() {
return this.main().getConfig(UNDERTOW_CONF_SECTION);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/config/Configs.java
// Path: src/main/java/com/adeptj/runtime/common/Environment.java // public final class Environment { // // /** // * Deny direct instantiation. // */ // private Environment() { // } // // public static boolean isDev() { // return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); // } // // public static Path getServerConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, SERVER_CONF_FILE); // } // // public static Path getFrameworkConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, FRAMEWORK_CONF_FILE); // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String COMMON_CONF_SECTION = "common"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String FELIX_CONF_SECTION = "felix"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String LOGGING_CONF_SECTION = "logging"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String MAIN_CONF_SECTION = "main"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String RESTEASY_CONF_SECTION = "resteasy"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_OVERWRITE_SERVER_CONF = "overwrite.server.conf.file"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String TRIMOU_CONF_SECTION = "trimou"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String UNDERTOW_CONF_SECTION = "undertow";
import static com.adeptj.runtime.common.Constants.RESTEASY_CONF_SECTION; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_OVERWRITE_SERVER_CONF; import static com.adeptj.runtime.common.Constants.TRIMOU_CONF_SECTION; import static com.adeptj.runtime.common.Constants.UNDERTOW_CONF_SECTION; import com.adeptj.runtime.common.Environment; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.io.File; import static com.adeptj.runtime.common.Constants.COMMON_CONF_SECTION; import static com.adeptj.runtime.common.Constants.FELIX_CONF_SECTION; import static com.adeptj.runtime.common.Constants.LOGGING_CONF_SECTION; import static com.adeptj.runtime.common.Constants.MAIN_CONF_SECTION;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.config; /** * Initializes the application configurations. * * @author Rakesh.Kumar, AdeptJ */ public enum Configs { INSTANCE; /** * This will include system properties as well. */ private final Config root; Configs() { this.root = this.loadConf(); } public Config root() { return this.root; } public Config main() { return this.root.getConfig(MAIN_CONF_SECTION); } public Config undertow() { return this.main().getConfig(UNDERTOW_CONF_SECTION); } public Config felix() {
// Path: src/main/java/com/adeptj/runtime/common/Environment.java // public final class Environment { // // /** // * Deny direct instantiation. // */ // private Environment() { // } // // public static boolean isDev() { // return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); // } // // public static Path getServerConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, SERVER_CONF_FILE); // } // // public static Path getFrameworkConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, FRAMEWORK_CONF_FILE); // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String COMMON_CONF_SECTION = "common"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String FELIX_CONF_SECTION = "felix"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String LOGGING_CONF_SECTION = "logging"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String MAIN_CONF_SECTION = "main"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String RESTEASY_CONF_SECTION = "resteasy"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_OVERWRITE_SERVER_CONF = "overwrite.server.conf.file"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String TRIMOU_CONF_SECTION = "trimou"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String UNDERTOW_CONF_SECTION = "undertow"; // Path: src/main/java/com/adeptj/runtime/config/Configs.java import static com.adeptj.runtime.common.Constants.RESTEASY_CONF_SECTION; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_OVERWRITE_SERVER_CONF; import static com.adeptj.runtime.common.Constants.TRIMOU_CONF_SECTION; import static com.adeptj.runtime.common.Constants.UNDERTOW_CONF_SECTION; import com.adeptj.runtime.common.Environment; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.io.File; import static com.adeptj.runtime.common.Constants.COMMON_CONF_SECTION; import static com.adeptj.runtime.common.Constants.FELIX_CONF_SECTION; import static com.adeptj.runtime.common.Constants.LOGGING_CONF_SECTION; import static com.adeptj.runtime.common.Constants.MAIN_CONF_SECTION; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.config; /** * Initializes the application configurations. * * @author Rakesh.Kumar, AdeptJ */ public enum Configs { INSTANCE; /** * This will include system properties as well. */ private final Config root; Configs() { this.root = this.loadConf(); } public Config root() { return this.root; } public Config main() { return this.root.getConfig(MAIN_CONF_SECTION); } public Config undertow() { return this.main().getConfig(UNDERTOW_CONF_SECTION); } public Config felix() {
return this.main().getConfig(FELIX_CONF_SECTION);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/config/Configs.java
// Path: src/main/java/com/adeptj/runtime/common/Environment.java // public final class Environment { // // /** // * Deny direct instantiation. // */ // private Environment() { // } // // public static boolean isDev() { // return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); // } // // public static Path getServerConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, SERVER_CONF_FILE); // } // // public static Path getFrameworkConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, FRAMEWORK_CONF_FILE); // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String COMMON_CONF_SECTION = "common"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String FELIX_CONF_SECTION = "felix"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String LOGGING_CONF_SECTION = "logging"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String MAIN_CONF_SECTION = "main"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String RESTEASY_CONF_SECTION = "resteasy"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_OVERWRITE_SERVER_CONF = "overwrite.server.conf.file"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String TRIMOU_CONF_SECTION = "trimou"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String UNDERTOW_CONF_SECTION = "undertow";
import static com.adeptj.runtime.common.Constants.RESTEASY_CONF_SECTION; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_OVERWRITE_SERVER_CONF; import static com.adeptj.runtime.common.Constants.TRIMOU_CONF_SECTION; import static com.adeptj.runtime.common.Constants.UNDERTOW_CONF_SECTION; import com.adeptj.runtime.common.Environment; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.io.File; import static com.adeptj.runtime.common.Constants.COMMON_CONF_SECTION; import static com.adeptj.runtime.common.Constants.FELIX_CONF_SECTION; import static com.adeptj.runtime.common.Constants.LOGGING_CONF_SECTION; import static com.adeptj.runtime.common.Constants.MAIN_CONF_SECTION;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.config; /** * Initializes the application configurations. * * @author Rakesh.Kumar, AdeptJ */ public enum Configs { INSTANCE; /** * This will include system properties as well. */ private final Config root; Configs() { this.root = this.loadConf(); } public Config root() { return this.root; } public Config main() { return this.root.getConfig(MAIN_CONF_SECTION); } public Config undertow() { return this.main().getConfig(UNDERTOW_CONF_SECTION); } public Config felix() { return this.main().getConfig(FELIX_CONF_SECTION); } public Config common() {
// Path: src/main/java/com/adeptj/runtime/common/Environment.java // public final class Environment { // // /** // * Deny direct instantiation. // */ // private Environment() { // } // // public static boolean isDev() { // return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); // } // // public static Path getServerConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, SERVER_CONF_FILE); // } // // public static Path getFrameworkConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, FRAMEWORK_CONF_FILE); // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String COMMON_CONF_SECTION = "common"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String FELIX_CONF_SECTION = "felix"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String LOGGING_CONF_SECTION = "logging"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String MAIN_CONF_SECTION = "main"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String RESTEASY_CONF_SECTION = "resteasy"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_OVERWRITE_SERVER_CONF = "overwrite.server.conf.file"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String TRIMOU_CONF_SECTION = "trimou"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String UNDERTOW_CONF_SECTION = "undertow"; // Path: src/main/java/com/adeptj/runtime/config/Configs.java import static com.adeptj.runtime.common.Constants.RESTEASY_CONF_SECTION; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_OVERWRITE_SERVER_CONF; import static com.adeptj.runtime.common.Constants.TRIMOU_CONF_SECTION; import static com.adeptj.runtime.common.Constants.UNDERTOW_CONF_SECTION; import com.adeptj.runtime.common.Environment; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.io.File; import static com.adeptj.runtime.common.Constants.COMMON_CONF_SECTION; import static com.adeptj.runtime.common.Constants.FELIX_CONF_SECTION; import static com.adeptj.runtime.common.Constants.LOGGING_CONF_SECTION; import static com.adeptj.runtime.common.Constants.MAIN_CONF_SECTION; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.config; /** * Initializes the application configurations. * * @author Rakesh.Kumar, AdeptJ */ public enum Configs { INSTANCE; /** * This will include system properties as well. */ private final Config root; Configs() { this.root = this.loadConf(); } public Config root() { return this.root; } public Config main() { return this.root.getConfig(MAIN_CONF_SECTION); } public Config undertow() { return this.main().getConfig(UNDERTOW_CONF_SECTION); } public Config felix() { return this.main().getConfig(FELIX_CONF_SECTION); } public Config common() {
return this.main().getConfig(COMMON_CONF_SECTION);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/config/Configs.java
// Path: src/main/java/com/adeptj/runtime/common/Environment.java // public final class Environment { // // /** // * Deny direct instantiation. // */ // private Environment() { // } // // public static boolean isDev() { // return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); // } // // public static Path getServerConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, SERVER_CONF_FILE); // } // // public static Path getFrameworkConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, FRAMEWORK_CONF_FILE); // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String COMMON_CONF_SECTION = "common"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String FELIX_CONF_SECTION = "felix"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String LOGGING_CONF_SECTION = "logging"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String MAIN_CONF_SECTION = "main"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String RESTEASY_CONF_SECTION = "resteasy"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_OVERWRITE_SERVER_CONF = "overwrite.server.conf.file"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String TRIMOU_CONF_SECTION = "trimou"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String UNDERTOW_CONF_SECTION = "undertow";
import static com.adeptj.runtime.common.Constants.RESTEASY_CONF_SECTION; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_OVERWRITE_SERVER_CONF; import static com.adeptj.runtime.common.Constants.TRIMOU_CONF_SECTION; import static com.adeptj.runtime.common.Constants.UNDERTOW_CONF_SECTION; import com.adeptj.runtime.common.Environment; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.io.File; import static com.adeptj.runtime.common.Constants.COMMON_CONF_SECTION; import static com.adeptj.runtime.common.Constants.FELIX_CONF_SECTION; import static com.adeptj.runtime.common.Constants.LOGGING_CONF_SECTION; import static com.adeptj.runtime.common.Constants.MAIN_CONF_SECTION;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.config; /** * Initializes the application configurations. * * @author Rakesh.Kumar, AdeptJ */ public enum Configs { INSTANCE; /** * This will include system properties as well. */ private final Config root; Configs() { this.root = this.loadConf(); } public Config root() { return this.root; } public Config main() { return this.root.getConfig(MAIN_CONF_SECTION); } public Config undertow() { return this.main().getConfig(UNDERTOW_CONF_SECTION); } public Config felix() { return this.main().getConfig(FELIX_CONF_SECTION); } public Config common() { return this.main().getConfig(COMMON_CONF_SECTION); } public Config logging() {
// Path: src/main/java/com/adeptj/runtime/common/Environment.java // public final class Environment { // // /** // * Deny direct instantiation. // */ // private Environment() { // } // // public static boolean isDev() { // return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); // } // // public static Path getServerConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, SERVER_CONF_FILE); // } // // public static Path getFrameworkConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, FRAMEWORK_CONF_FILE); // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String COMMON_CONF_SECTION = "common"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String FELIX_CONF_SECTION = "felix"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String LOGGING_CONF_SECTION = "logging"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String MAIN_CONF_SECTION = "main"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String RESTEASY_CONF_SECTION = "resteasy"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_OVERWRITE_SERVER_CONF = "overwrite.server.conf.file"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String TRIMOU_CONF_SECTION = "trimou"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String UNDERTOW_CONF_SECTION = "undertow"; // Path: src/main/java/com/adeptj/runtime/config/Configs.java import static com.adeptj.runtime.common.Constants.RESTEASY_CONF_SECTION; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_OVERWRITE_SERVER_CONF; import static com.adeptj.runtime.common.Constants.TRIMOU_CONF_SECTION; import static com.adeptj.runtime.common.Constants.UNDERTOW_CONF_SECTION; import com.adeptj.runtime.common.Environment; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.io.File; import static com.adeptj.runtime.common.Constants.COMMON_CONF_SECTION; import static com.adeptj.runtime.common.Constants.FELIX_CONF_SECTION; import static com.adeptj.runtime.common.Constants.LOGGING_CONF_SECTION; import static com.adeptj.runtime.common.Constants.MAIN_CONF_SECTION; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.config; /** * Initializes the application configurations. * * @author Rakesh.Kumar, AdeptJ */ public enum Configs { INSTANCE; /** * This will include system properties as well. */ private final Config root; Configs() { this.root = this.loadConf(); } public Config root() { return this.root; } public Config main() { return this.root.getConfig(MAIN_CONF_SECTION); } public Config undertow() { return this.main().getConfig(UNDERTOW_CONF_SECTION); } public Config felix() { return this.main().getConfig(FELIX_CONF_SECTION); } public Config common() { return this.main().getConfig(COMMON_CONF_SECTION); } public Config logging() {
return this.main().getConfig(LOGGING_CONF_SECTION);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/config/Configs.java
// Path: src/main/java/com/adeptj/runtime/common/Environment.java // public final class Environment { // // /** // * Deny direct instantiation. // */ // private Environment() { // } // // public static boolean isDev() { // return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); // } // // public static Path getServerConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, SERVER_CONF_FILE); // } // // public static Path getFrameworkConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, FRAMEWORK_CONF_FILE); // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String COMMON_CONF_SECTION = "common"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String FELIX_CONF_SECTION = "felix"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String LOGGING_CONF_SECTION = "logging"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String MAIN_CONF_SECTION = "main"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String RESTEASY_CONF_SECTION = "resteasy"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_OVERWRITE_SERVER_CONF = "overwrite.server.conf.file"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String TRIMOU_CONF_SECTION = "trimou"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String UNDERTOW_CONF_SECTION = "undertow";
import static com.adeptj.runtime.common.Constants.RESTEASY_CONF_SECTION; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_OVERWRITE_SERVER_CONF; import static com.adeptj.runtime.common.Constants.TRIMOU_CONF_SECTION; import static com.adeptj.runtime.common.Constants.UNDERTOW_CONF_SECTION; import com.adeptj.runtime.common.Environment; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.io.File; import static com.adeptj.runtime.common.Constants.COMMON_CONF_SECTION; import static com.adeptj.runtime.common.Constants.FELIX_CONF_SECTION; import static com.adeptj.runtime.common.Constants.LOGGING_CONF_SECTION; import static com.adeptj.runtime.common.Constants.MAIN_CONF_SECTION;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.config; /** * Initializes the application configurations. * * @author Rakesh.Kumar, AdeptJ */ public enum Configs { INSTANCE; /** * This will include system properties as well. */ private final Config root; Configs() { this.root = this.loadConf(); } public Config root() { return this.root; } public Config main() { return this.root.getConfig(MAIN_CONF_SECTION); } public Config undertow() { return this.main().getConfig(UNDERTOW_CONF_SECTION); } public Config felix() { return this.main().getConfig(FELIX_CONF_SECTION); } public Config common() { return this.main().getConfig(COMMON_CONF_SECTION); } public Config logging() { return this.main().getConfig(LOGGING_CONF_SECTION); } public Config trimou() {
// Path: src/main/java/com/adeptj/runtime/common/Environment.java // public final class Environment { // // /** // * Deny direct instantiation. // */ // private Environment() { // } // // public static boolean isDev() { // return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); // } // // public static Path getServerConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, SERVER_CONF_FILE); // } // // public static Path getFrameworkConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, FRAMEWORK_CONF_FILE); // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String COMMON_CONF_SECTION = "common"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String FELIX_CONF_SECTION = "felix"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String LOGGING_CONF_SECTION = "logging"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String MAIN_CONF_SECTION = "main"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String RESTEASY_CONF_SECTION = "resteasy"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_OVERWRITE_SERVER_CONF = "overwrite.server.conf.file"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String TRIMOU_CONF_SECTION = "trimou"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String UNDERTOW_CONF_SECTION = "undertow"; // Path: src/main/java/com/adeptj/runtime/config/Configs.java import static com.adeptj.runtime.common.Constants.RESTEASY_CONF_SECTION; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_OVERWRITE_SERVER_CONF; import static com.adeptj.runtime.common.Constants.TRIMOU_CONF_SECTION; import static com.adeptj.runtime.common.Constants.UNDERTOW_CONF_SECTION; import com.adeptj.runtime.common.Environment; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.io.File; import static com.adeptj.runtime.common.Constants.COMMON_CONF_SECTION; import static com.adeptj.runtime.common.Constants.FELIX_CONF_SECTION; import static com.adeptj.runtime.common.Constants.LOGGING_CONF_SECTION; import static com.adeptj.runtime.common.Constants.MAIN_CONF_SECTION; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.config; /** * Initializes the application configurations. * * @author Rakesh.Kumar, AdeptJ */ public enum Configs { INSTANCE; /** * This will include system properties as well. */ private final Config root; Configs() { this.root = this.loadConf(); } public Config root() { return this.root; } public Config main() { return this.root.getConfig(MAIN_CONF_SECTION); } public Config undertow() { return this.main().getConfig(UNDERTOW_CONF_SECTION); } public Config felix() { return this.main().getConfig(FELIX_CONF_SECTION); } public Config common() { return this.main().getConfig(COMMON_CONF_SECTION); } public Config logging() { return this.main().getConfig(LOGGING_CONF_SECTION); } public Config trimou() {
return this.main().getConfig(TRIMOU_CONF_SECTION);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/config/Configs.java
// Path: src/main/java/com/adeptj/runtime/common/Environment.java // public final class Environment { // // /** // * Deny direct instantiation. // */ // private Environment() { // } // // public static boolean isDev() { // return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); // } // // public static Path getServerConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, SERVER_CONF_FILE); // } // // public static Path getFrameworkConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, FRAMEWORK_CONF_FILE); // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String COMMON_CONF_SECTION = "common"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String FELIX_CONF_SECTION = "felix"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String LOGGING_CONF_SECTION = "logging"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String MAIN_CONF_SECTION = "main"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String RESTEASY_CONF_SECTION = "resteasy"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_OVERWRITE_SERVER_CONF = "overwrite.server.conf.file"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String TRIMOU_CONF_SECTION = "trimou"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String UNDERTOW_CONF_SECTION = "undertow";
import static com.adeptj.runtime.common.Constants.RESTEASY_CONF_SECTION; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_OVERWRITE_SERVER_CONF; import static com.adeptj.runtime.common.Constants.TRIMOU_CONF_SECTION; import static com.adeptj.runtime.common.Constants.UNDERTOW_CONF_SECTION; import com.adeptj.runtime.common.Environment; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.io.File; import static com.adeptj.runtime.common.Constants.COMMON_CONF_SECTION; import static com.adeptj.runtime.common.Constants.FELIX_CONF_SECTION; import static com.adeptj.runtime.common.Constants.LOGGING_CONF_SECTION; import static com.adeptj.runtime.common.Constants.MAIN_CONF_SECTION;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.config; /** * Initializes the application configurations. * * @author Rakesh.Kumar, AdeptJ */ public enum Configs { INSTANCE; /** * This will include system properties as well. */ private final Config root; Configs() { this.root = this.loadConf(); } public Config root() { return this.root; } public Config main() { return this.root.getConfig(MAIN_CONF_SECTION); } public Config undertow() { return this.main().getConfig(UNDERTOW_CONF_SECTION); } public Config felix() { return this.main().getConfig(FELIX_CONF_SECTION); } public Config common() { return this.main().getConfig(COMMON_CONF_SECTION); } public Config logging() { return this.main().getConfig(LOGGING_CONF_SECTION); } public Config trimou() { return this.main().getConfig(TRIMOU_CONF_SECTION); } public Config resteasy() {
// Path: src/main/java/com/adeptj/runtime/common/Environment.java // public final class Environment { // // /** // * Deny direct instantiation. // */ // private Environment() { // } // // public static boolean isDev() { // return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); // } // // public static Path getServerConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, SERVER_CONF_FILE); // } // // public static Path getFrameworkConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, FRAMEWORK_CONF_FILE); // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String COMMON_CONF_SECTION = "common"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String FELIX_CONF_SECTION = "felix"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String LOGGING_CONF_SECTION = "logging"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String MAIN_CONF_SECTION = "main"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String RESTEASY_CONF_SECTION = "resteasy"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_OVERWRITE_SERVER_CONF = "overwrite.server.conf.file"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String TRIMOU_CONF_SECTION = "trimou"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String UNDERTOW_CONF_SECTION = "undertow"; // Path: src/main/java/com/adeptj/runtime/config/Configs.java import static com.adeptj.runtime.common.Constants.RESTEASY_CONF_SECTION; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_OVERWRITE_SERVER_CONF; import static com.adeptj.runtime.common.Constants.TRIMOU_CONF_SECTION; import static com.adeptj.runtime.common.Constants.UNDERTOW_CONF_SECTION; import com.adeptj.runtime.common.Environment; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.io.File; import static com.adeptj.runtime.common.Constants.COMMON_CONF_SECTION; import static com.adeptj.runtime.common.Constants.FELIX_CONF_SECTION; import static com.adeptj.runtime.common.Constants.LOGGING_CONF_SECTION; import static com.adeptj.runtime.common.Constants.MAIN_CONF_SECTION; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.config; /** * Initializes the application configurations. * * @author Rakesh.Kumar, AdeptJ */ public enum Configs { INSTANCE; /** * This will include system properties as well. */ private final Config root; Configs() { this.root = this.loadConf(); } public Config root() { return this.root; } public Config main() { return this.root.getConfig(MAIN_CONF_SECTION); } public Config undertow() { return this.main().getConfig(UNDERTOW_CONF_SECTION); } public Config felix() { return this.main().getConfig(FELIX_CONF_SECTION); } public Config common() { return this.main().getConfig(COMMON_CONF_SECTION); } public Config logging() { return this.main().getConfig(LOGGING_CONF_SECTION); } public Config trimou() { return this.main().getConfig(TRIMOU_CONF_SECTION); } public Config resteasy() {
return this.main().getConfig(RESTEASY_CONF_SECTION);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/config/Configs.java
// Path: src/main/java/com/adeptj/runtime/common/Environment.java // public final class Environment { // // /** // * Deny direct instantiation. // */ // private Environment() { // } // // public static boolean isDev() { // return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); // } // // public static Path getServerConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, SERVER_CONF_FILE); // } // // public static Path getFrameworkConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, FRAMEWORK_CONF_FILE); // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String COMMON_CONF_SECTION = "common"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String FELIX_CONF_SECTION = "felix"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String LOGGING_CONF_SECTION = "logging"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String MAIN_CONF_SECTION = "main"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String RESTEASY_CONF_SECTION = "resteasy"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_OVERWRITE_SERVER_CONF = "overwrite.server.conf.file"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String TRIMOU_CONF_SECTION = "trimou"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String UNDERTOW_CONF_SECTION = "undertow";
import static com.adeptj.runtime.common.Constants.RESTEASY_CONF_SECTION; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_OVERWRITE_SERVER_CONF; import static com.adeptj.runtime.common.Constants.TRIMOU_CONF_SECTION; import static com.adeptj.runtime.common.Constants.UNDERTOW_CONF_SECTION; import com.adeptj.runtime.common.Environment; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.io.File; import static com.adeptj.runtime.common.Constants.COMMON_CONF_SECTION; import static com.adeptj.runtime.common.Constants.FELIX_CONF_SECTION; import static com.adeptj.runtime.common.Constants.LOGGING_CONF_SECTION; import static com.adeptj.runtime.common.Constants.MAIN_CONF_SECTION;
public Config main() { return this.root.getConfig(MAIN_CONF_SECTION); } public Config undertow() { return this.main().getConfig(UNDERTOW_CONF_SECTION); } public Config felix() { return this.main().getConfig(FELIX_CONF_SECTION); } public Config common() { return this.main().getConfig(COMMON_CONF_SECTION); } public Config logging() { return this.main().getConfig(LOGGING_CONF_SECTION); } public Config trimou() { return this.main().getConfig(TRIMOU_CONF_SECTION); } public Config resteasy() { return this.main().getConfig(RESTEASY_CONF_SECTION); } private Config loadConf() { Config config;
// Path: src/main/java/com/adeptj/runtime/common/Environment.java // public final class Environment { // // /** // * Deny direct instantiation. // */ // private Environment() { // } // // public static boolean isDev() { // return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); // } // // public static Path getServerConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, SERVER_CONF_FILE); // } // // public static Path getFrameworkConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, FRAMEWORK_CONF_FILE); // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String COMMON_CONF_SECTION = "common"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String FELIX_CONF_SECTION = "felix"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String LOGGING_CONF_SECTION = "logging"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String MAIN_CONF_SECTION = "main"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String RESTEASY_CONF_SECTION = "resteasy"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_OVERWRITE_SERVER_CONF = "overwrite.server.conf.file"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String TRIMOU_CONF_SECTION = "trimou"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String UNDERTOW_CONF_SECTION = "undertow"; // Path: src/main/java/com/adeptj/runtime/config/Configs.java import static com.adeptj.runtime.common.Constants.RESTEASY_CONF_SECTION; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_OVERWRITE_SERVER_CONF; import static com.adeptj.runtime.common.Constants.TRIMOU_CONF_SECTION; import static com.adeptj.runtime.common.Constants.UNDERTOW_CONF_SECTION; import com.adeptj.runtime.common.Environment; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.io.File; import static com.adeptj.runtime.common.Constants.COMMON_CONF_SECTION; import static com.adeptj.runtime.common.Constants.FELIX_CONF_SECTION; import static com.adeptj.runtime.common.Constants.LOGGING_CONF_SECTION; import static com.adeptj.runtime.common.Constants.MAIN_CONF_SECTION; public Config main() { return this.root.getConfig(MAIN_CONF_SECTION); } public Config undertow() { return this.main().getConfig(UNDERTOW_CONF_SECTION); } public Config felix() { return this.main().getConfig(FELIX_CONF_SECTION); } public Config common() { return this.main().getConfig(COMMON_CONF_SECTION); } public Config logging() { return this.main().getConfig(LOGGING_CONF_SECTION); } public Config trimou() { return this.main().getConfig(TRIMOU_CONF_SECTION); } public Config resteasy() { return this.main().getConfig(RESTEASY_CONF_SECTION); } private Config loadConf() { Config config;
File configFile = Environment.getServerConfPath().toFile();
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/config/Configs.java
// Path: src/main/java/com/adeptj/runtime/common/Environment.java // public final class Environment { // // /** // * Deny direct instantiation. // */ // private Environment() { // } // // public static boolean isDev() { // return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); // } // // public static Path getServerConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, SERVER_CONF_FILE); // } // // public static Path getFrameworkConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, FRAMEWORK_CONF_FILE); // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String COMMON_CONF_SECTION = "common"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String FELIX_CONF_SECTION = "felix"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String LOGGING_CONF_SECTION = "logging"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String MAIN_CONF_SECTION = "main"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String RESTEASY_CONF_SECTION = "resteasy"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_OVERWRITE_SERVER_CONF = "overwrite.server.conf.file"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String TRIMOU_CONF_SECTION = "trimou"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String UNDERTOW_CONF_SECTION = "undertow";
import static com.adeptj.runtime.common.Constants.RESTEASY_CONF_SECTION; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_OVERWRITE_SERVER_CONF; import static com.adeptj.runtime.common.Constants.TRIMOU_CONF_SECTION; import static com.adeptj.runtime.common.Constants.UNDERTOW_CONF_SECTION; import com.adeptj.runtime.common.Environment; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.io.File; import static com.adeptj.runtime.common.Constants.COMMON_CONF_SECTION; import static com.adeptj.runtime.common.Constants.FELIX_CONF_SECTION; import static com.adeptj.runtime.common.Constants.LOGGING_CONF_SECTION; import static com.adeptj.runtime.common.Constants.MAIN_CONF_SECTION;
public Config undertow() { return this.main().getConfig(UNDERTOW_CONF_SECTION); } public Config felix() { return this.main().getConfig(FELIX_CONF_SECTION); } public Config common() { return this.main().getConfig(COMMON_CONF_SECTION); } public Config logging() { return this.main().getConfig(LOGGING_CONF_SECTION); } public Config trimou() { return this.main().getConfig(TRIMOU_CONF_SECTION); } public Config resteasy() { return this.main().getConfig(RESTEASY_CONF_SECTION); } private Config loadConf() { Config config; File configFile = Environment.getServerConfPath().toFile(); if (configFile.exists()) { // if overwrite.server.conf.file system property is provided, then load the configs from classpath.
// Path: src/main/java/com/adeptj/runtime/common/Environment.java // public final class Environment { // // /** // * Deny direct instantiation. // */ // private Environment() { // } // // public static boolean isDev() { // return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); // } // // public static Path getServerConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, SERVER_CONF_FILE); // } // // public static Path getFrameworkConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, FRAMEWORK_CONF_FILE); // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String COMMON_CONF_SECTION = "common"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String FELIX_CONF_SECTION = "felix"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String LOGGING_CONF_SECTION = "logging"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String MAIN_CONF_SECTION = "main"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String RESTEASY_CONF_SECTION = "resteasy"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_OVERWRITE_SERVER_CONF = "overwrite.server.conf.file"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String TRIMOU_CONF_SECTION = "trimou"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String UNDERTOW_CONF_SECTION = "undertow"; // Path: src/main/java/com/adeptj/runtime/config/Configs.java import static com.adeptj.runtime.common.Constants.RESTEASY_CONF_SECTION; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_OVERWRITE_SERVER_CONF; import static com.adeptj.runtime.common.Constants.TRIMOU_CONF_SECTION; import static com.adeptj.runtime.common.Constants.UNDERTOW_CONF_SECTION; import com.adeptj.runtime.common.Environment; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.io.File; import static com.adeptj.runtime.common.Constants.COMMON_CONF_SECTION; import static com.adeptj.runtime.common.Constants.FELIX_CONF_SECTION; import static com.adeptj.runtime.common.Constants.LOGGING_CONF_SECTION; import static com.adeptj.runtime.common.Constants.MAIN_CONF_SECTION; public Config undertow() { return this.main().getConfig(UNDERTOW_CONF_SECTION); } public Config felix() { return this.main().getConfig(FELIX_CONF_SECTION); } public Config common() { return this.main().getConfig(COMMON_CONF_SECTION); } public Config logging() { return this.main().getConfig(LOGGING_CONF_SECTION); } public Config trimou() { return this.main().getConfig(TRIMOU_CONF_SECTION); } public Config resteasy() { return this.main().getConfig(RESTEASY_CONF_SECTION); } private Config loadConf() { Config config; File configFile = Environment.getServerConfPath().toFile(); if (configFile.exists()) { // if overwrite.server.conf.file system property is provided, then load the configs from classpath.
if (Boolean.getBoolean(SYS_PROP_OVERWRITE_SERVER_CONF)) {
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/config/Configs.java
// Path: src/main/java/com/adeptj/runtime/common/Environment.java // public final class Environment { // // /** // * Deny direct instantiation. // */ // private Environment() { // } // // public static boolean isDev() { // return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); // } // // public static Path getServerConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, SERVER_CONF_FILE); // } // // public static Path getFrameworkConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, FRAMEWORK_CONF_FILE); // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String COMMON_CONF_SECTION = "common"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String FELIX_CONF_SECTION = "felix"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String LOGGING_CONF_SECTION = "logging"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String MAIN_CONF_SECTION = "main"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String RESTEASY_CONF_SECTION = "resteasy"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_OVERWRITE_SERVER_CONF = "overwrite.server.conf.file"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String TRIMOU_CONF_SECTION = "trimou"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String UNDERTOW_CONF_SECTION = "undertow";
import static com.adeptj.runtime.common.Constants.RESTEASY_CONF_SECTION; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_OVERWRITE_SERVER_CONF; import static com.adeptj.runtime.common.Constants.TRIMOU_CONF_SECTION; import static com.adeptj.runtime.common.Constants.UNDERTOW_CONF_SECTION; import com.adeptj.runtime.common.Environment; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.io.File; import static com.adeptj.runtime.common.Constants.COMMON_CONF_SECTION; import static com.adeptj.runtime.common.Constants.FELIX_CONF_SECTION; import static com.adeptj.runtime.common.Constants.LOGGING_CONF_SECTION; import static com.adeptj.runtime.common.Constants.MAIN_CONF_SECTION;
public Config undertow() { return this.main().getConfig(UNDERTOW_CONF_SECTION); } public Config felix() { return this.main().getConfig(FELIX_CONF_SECTION); } public Config common() { return this.main().getConfig(COMMON_CONF_SECTION); } public Config logging() { return this.main().getConfig(LOGGING_CONF_SECTION); } public Config trimou() { return this.main().getConfig(TRIMOU_CONF_SECTION); } public Config resteasy() { return this.main().getConfig(RESTEASY_CONF_SECTION); } private Config loadConf() { Config config; File configFile = Environment.getServerConfPath().toFile(); if (configFile.exists()) { // if overwrite.server.conf.file system property is provided, then load the configs from classpath. if (Boolean.getBoolean(SYS_PROP_OVERWRITE_SERVER_CONF)) {
// Path: src/main/java/com/adeptj/runtime/common/Environment.java // public final class Environment { // // /** // * Deny direct instantiation. // */ // private Environment() { // } // // public static boolean isDev() { // return ServerMode.DEV.toString().equalsIgnoreCase(System.getProperty(SYS_PROP_SERVER_MODE)); // } // // public static Path getServerConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, SERVER_CONF_FILE); // } // // public static Path getFrameworkConfPath() { // return Paths.get(USER_DIR, DIR_ADEPTJ_RUNTIME, DIR_DEPLOYMENT, FRAMEWORK_CONF_FILE); // } // } // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String COMMON_CONF_SECTION = "common"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String FELIX_CONF_SECTION = "felix"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String LOGGING_CONF_SECTION = "logging"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String MAIN_CONF_SECTION = "main"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String RESTEASY_CONF_SECTION = "resteasy"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SERVER_CONF_FILE = "server.conf"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String SYS_PROP_OVERWRITE_SERVER_CONF = "overwrite.server.conf.file"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String TRIMOU_CONF_SECTION = "trimou"; // // Path: src/main/java/com/adeptj/runtime/common/Constants.java // public static final String UNDERTOW_CONF_SECTION = "undertow"; // Path: src/main/java/com/adeptj/runtime/config/Configs.java import static com.adeptj.runtime.common.Constants.RESTEASY_CONF_SECTION; import static com.adeptj.runtime.common.Constants.SERVER_CONF_FILE; import static com.adeptj.runtime.common.Constants.SYS_PROP_OVERWRITE_SERVER_CONF; import static com.adeptj.runtime.common.Constants.TRIMOU_CONF_SECTION; import static com.adeptj.runtime.common.Constants.UNDERTOW_CONF_SECTION; import com.adeptj.runtime.common.Environment; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import java.io.File; import static com.adeptj.runtime.common.Constants.COMMON_CONF_SECTION; import static com.adeptj.runtime.common.Constants.FELIX_CONF_SECTION; import static com.adeptj.runtime.common.Constants.LOGGING_CONF_SECTION; import static com.adeptj.runtime.common.Constants.MAIN_CONF_SECTION; public Config undertow() { return this.main().getConfig(UNDERTOW_CONF_SECTION); } public Config felix() { return this.main().getConfig(FELIX_CONF_SECTION); } public Config common() { return this.main().getConfig(COMMON_CONF_SECTION); } public Config logging() { return this.main().getConfig(LOGGING_CONF_SECTION); } public Config trimou() { return this.main().getConfig(TRIMOU_CONF_SECTION); } public Config resteasy() { return this.main().getConfig(RESTEASY_CONF_SECTION); } private Config loadConf() { Config config; File configFile = Environment.getServerConfPath().toFile(); if (configFile.exists()) { // if overwrite.server.conf.file system property is provided, then load the configs from classpath. if (Boolean.getBoolean(SYS_PROP_OVERWRITE_SERVER_CONF)) {
config = ConfigFactory.load(SERVER_CONF_FILE);
AdeptJ/adeptj-runtime
src/main/java/com/adeptj/runtime/common/ResponseUtil.java
// Path: src/main/java/com/adeptj/runtime/exception/ServerException.java // public class ServerException extends RuntimeException { // // private static final long serialVersionUID = 2206058386357128479L; // // public ServerException(Throwable cause) { // super(cause); // } // }
import com.adeptj.runtime.exception.ServerException; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; import static javax.servlet.http.HttpServletResponse.SC_SERVICE_UNAVAILABLE;
/* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utils for {@link HttpServletResponse} * * @author Rakesh.Kumar, AdeptJ */ public final class ResponseUtil { private ResponseUtil() { } public static void serverError(HttpServletResponse resp) { try { resp.sendError(SC_INTERNAL_SERVER_ERROR); } catch (IOException ex) { // Now what? may be wrap and re-throw. Let the container handle it.
// Path: src/main/java/com/adeptj/runtime/exception/ServerException.java // public class ServerException extends RuntimeException { // // private static final long serialVersionUID = 2206058386357128479L; // // public ServerException(Throwable cause) { // super(cause); // } // } // Path: src/main/java/com/adeptj/runtime/common/ResponseUtil.java import com.adeptj.runtime.exception.ServerException; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; import static javax.servlet.http.HttpServletResponse.SC_SERVICE_UNAVAILABLE; /* ############################################################################### # # # Copyright 2016, AdeptJ (http://www.adeptj.com) # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in compliance with the License. # # You may obtain a copy of the License at # # # # http://www.apache.org/licenses/LICENSE-2.0 # # # # Unless required by applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. # # # ############################################################################### */ package com.adeptj.runtime.common; /** * Utils for {@link HttpServletResponse} * * @author Rakesh.Kumar, AdeptJ */ public final class ResponseUtil { private ResponseUtil() { } public static void serverError(HttpServletResponse resp) { try { resp.sendError(SC_INTERNAL_SERVER_ERROR); } catch (IOException ex) { // Now what? may be wrap and re-throw. Let the container handle it.
throw new ServerException(ex);
fergusq/java-nightfall
src/gui/WidgetPadding.java
// Path: src/util/UDim.java // public class UDim { // public UDim() { // this(0, 0, 0, 0); // } // public UDim(FVec offset) { // this(offset.getX(), offset.getY(), 0, 0); // } // public UDim(float offsetx, float offsety) { // this(offsetx, offsety, 0, 0); // } // public UDim(FVec offset, FVec scale) { // this(offset.getX(), offset.getY(), scale.getX(), scale.getY()); // } // public UDim(float offsetx, float offsety, float scalex, float scaley) { // mXOffset = offsetx; // mYOffset = offsety; // mXScale = scalex; // mYScale = scaley; // } // // public FVec getOffset() { // return new FVec(mXOffset, mYOffset); // } // // public float getXOffset() { // return mXOffset; // } // // public float getYOffset() { // return mYOffset; // } // // public FVec getScale() { // return new FVec(mXScale, mYScale); // } // // public float getXScale() { // return mXScale; // } // // public float getYScale() { // return mYScale; // } // // private float mXOffset, mYOffset, mXScale, mYScale; // }
import util.UDim;
package gui; public class WidgetPadding extends Widget { public static void applyPadding(Widget w, int p) { applyPadding(w, p, p, p, p); } public static void applyPadding(Widget w, int r, int l, int t, int b) {
// Path: src/util/UDim.java // public class UDim { // public UDim() { // this(0, 0, 0, 0); // } // public UDim(FVec offset) { // this(offset.getX(), offset.getY(), 0, 0); // } // public UDim(float offsetx, float offsety) { // this(offsetx, offsety, 0, 0); // } // public UDim(FVec offset, FVec scale) { // this(offset.getX(), offset.getY(), scale.getX(), scale.getY()); // } // public UDim(float offsetx, float offsety, float scalex, float scaley) { // mXOffset = offsetx; // mYOffset = offsety; // mXScale = scalex; // mYScale = scaley; // } // // public FVec getOffset() { // return new FVec(mXOffset, mYOffset); // } // // public float getXOffset() { // return mXOffset; // } // // public float getYOffset() { // return mYOffset; // } // // public FVec getScale() { // return new FVec(mXScale, mYScale); // } // // public float getXScale() { // return mXScale; // } // // public float getYScale() { // return mYScale; // } // // private float mXOffset, mYOffset, mXScale, mYScale; // } // Path: src/gui/WidgetPadding.java import util.UDim; package gui; public class WidgetPadding extends Widget { public static void applyPadding(Widget w, int p) { applyPadding(w, p, p, p, p); } public static void applyPadding(Widget w, int r, int l, int t, int b) {
UDim wsz = w.getSize();
fergusq/java-nightfall
src/gui/Widget.java
// Path: src/input/Event.java // public static enum EventType { // Key(1<<0), // Mouse(1<<1), // Custom(1<<2); // // private EventType(int mask) { // mMask = mask; // } // // public int getMask() { // return mMask; // } // // private int mMask; // } // // Path: src/input/MouseEvent.java // public static enum MouseEventType { // Move (1<<0), // Enter (1<<1), // Leave (1<<2), // Press (1<<3), // Release (1<<4), // Scroll (1<<5); // // public static final int ButtonMask = Press.getMask() | Release.getMask(); // public static final int MotionMask = Move.getMask() | Enter.getMask() | Leave.getMask(); // public static final int ScrollMask = Scroll.getMask(); // // private MouseEventType(int mask) { // mMask = mask; // } // // public int getMask() { // return mMask; // } // // private int mMask; // } // // Path: src/input/KeyEvent.java // public static enum KeyEventType { // Press (1<<0), // Release (1<<1); // // public static final int ButtonMask = Press.getMask() | Release.getMask(); // // private KeyEventType(int mask) { // mMask = mask; // } // // public int getMask() { // return mMask; // } // // private int mMask; // }
import java.util.ArrayList; import java.util.Collection; import input.*; import input.Event.EventType; import input.MouseEvent.MouseEventType; import input.KeyEvent.KeyEventType; import util.*;
package gui; public class Widget { //public final static int NUM_LAYERS = 10; protected void onRender(RenderTarget t) {} protected void onLayout() {} protected final void internalOnEvent(Event e) { //not visible, break off if (!mVisible) return; //make up to date if (!mRectValid) internalOnLayout(false); //clear any pending child removals, event handling may remove some children removePendingChildren(); //do children, last added is on top, so it gets a chance //at the event first mChildLock = true; for (int i = mChildren.size()-1; i >= 0; --i) { mChildren.get(i).internalOnEvent(e); if (e.consumed()) return; } mChildLock = false; //if mouse is over, handle event if (contains(e.getInput().getMousePos())) { //active? consume the event if (mActive) e.consume(); //set the input's MouseTarget to this e.getInput().setMouseTarget(this); //dispatch
// Path: src/input/Event.java // public static enum EventType { // Key(1<<0), // Mouse(1<<1), // Custom(1<<2); // // private EventType(int mask) { // mMask = mask; // } // // public int getMask() { // return mMask; // } // // private int mMask; // } // // Path: src/input/MouseEvent.java // public static enum MouseEventType { // Move (1<<0), // Enter (1<<1), // Leave (1<<2), // Press (1<<3), // Release (1<<4), // Scroll (1<<5); // // public static final int ButtonMask = Press.getMask() | Release.getMask(); // public static final int MotionMask = Move.getMask() | Enter.getMask() | Leave.getMask(); // public static final int ScrollMask = Scroll.getMask(); // // private MouseEventType(int mask) { // mMask = mask; // } // // public int getMask() { // return mMask; // } // // private int mMask; // } // // Path: src/input/KeyEvent.java // public static enum KeyEventType { // Press (1<<0), // Release (1<<1); // // public static final int ButtonMask = Press.getMask() | Release.getMask(); // // private KeyEventType(int mask) { // mMask = mask; // } // // public int getMask() { // return mMask; // } // // private int mMask; // } // Path: src/gui/Widget.java import java.util.ArrayList; import java.util.Collection; import input.*; import input.Event.EventType; import input.MouseEvent.MouseEventType; import input.KeyEvent.KeyEventType; import util.*; package gui; public class Widget { //public final static int NUM_LAYERS = 10; protected void onRender(RenderTarget t) {} protected void onLayout() {} protected final void internalOnEvent(Event e) { //not visible, break off if (!mVisible) return; //make up to date if (!mRectValid) internalOnLayout(false); //clear any pending child removals, event handling may remove some children removePendingChildren(); //do children, last added is on top, so it gets a chance //at the event first mChildLock = true; for (int i = mChildren.size()-1; i >= 0; --i) { mChildren.get(i).internalOnEvent(e); if (e.consumed()) return; } mChildLock = false; //if mouse is over, handle event if (contains(e.getInput().getMousePos())) { //active? consume the event if (mActive) e.consume(); //set the input's MouseTarget to this e.getInput().setMouseTarget(this); //dispatch
if (e.getEventType() == EventType.Mouse) {
fergusq/java-nightfall
src/game/Agent.java
// Path: src/util/Vec.java // public class Vec { // public Vec() { // mX = mY = 0; // } // public Vec(int x, int y) { // mX = x; // mY = y; // } // public int getX() { // return mX; // } // public int getY() { // return mY; // } // public Vec add(Vec other) { // return new Vec(mX + other.mX, mY + other.mY); // } // public Vec sub(Vec other) { // return new Vec(mX - other.mX, mY - other.mY); // } // public Vec mul(int other) { // return new Vec(mX*other, mY*other); // } // public Vec div(int other) { // return new Vec(mX/other, mY/other); // } // public Vec neg() { // return new Vec(-mX, -mY); // } // public boolean eq(Vec other) { // return mX == other.mX && mY == other.mY; // } // public boolean eq(int x, int y) { // return mX == x && mY == y; // } // public FVec fvec() { // return new FVec((float)mX, (float)mY); // } // public static Vec[] getDirs() { // return mDirs; // } // public static Vec[] getHorizontalDirs() { // return mHorizontalDirs; // } // public static Vec[] getVerticalDirs() { // return mVerticalDirs; // } // private int mX, mY; // private static final Vec[] mDirs = {new Vec(0, 1), new Vec(0, -1), new Vec(1, 0), new Vec(-1, 0)}; // private static final Vec[] mVerticalDirs = {new Vec(0, 1), new Vec(0, -1)}; // private static final Vec[] mHorizontalDirs = {new Vec(1, 0), new Vec(-1, 0)}; // // public String toString() { // return "Vec(" + mX + ", " + mY + ")"; // } // }
import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import util.Vec;
package game; public class Agent { public static enum TurnState { Ready, //ready to move Moved, //moved Done, //used ability }
// Path: src/util/Vec.java // public class Vec { // public Vec() { // mX = mY = 0; // } // public Vec(int x, int y) { // mX = x; // mY = y; // } // public int getX() { // return mX; // } // public int getY() { // return mY; // } // public Vec add(Vec other) { // return new Vec(mX + other.mX, mY + other.mY); // } // public Vec sub(Vec other) { // return new Vec(mX - other.mX, mY - other.mY); // } // public Vec mul(int other) { // return new Vec(mX*other, mY*other); // } // public Vec div(int other) { // return new Vec(mX/other, mY/other); // } // public Vec neg() { // return new Vec(-mX, -mY); // } // public boolean eq(Vec other) { // return mX == other.mX && mY == other.mY; // } // public boolean eq(int x, int y) { // return mX == x && mY == y; // } // public FVec fvec() { // return new FVec((float)mX, (float)mY); // } // public static Vec[] getDirs() { // return mDirs; // } // public static Vec[] getHorizontalDirs() { // return mHorizontalDirs; // } // public static Vec[] getVerticalDirs() { // return mVerticalDirs; // } // private int mX, mY; // private static final Vec[] mDirs = {new Vec(0, 1), new Vec(0, -1), new Vec(1, 0), new Vec(-1, 0)}; // private static final Vec[] mVerticalDirs = {new Vec(0, 1), new Vec(0, -1)}; // private static final Vec[] mHorizontalDirs = {new Vec(1, 0), new Vec(-1, 0)}; // // public String toString() { // return "Vec(" + mX + ", " + mY + ")"; // } // } // Path: src/game/Agent.java import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import util.Vec; package game; public class Agent { public static enum TurnState { Ready, //ready to move Moved, //moved Done, //used ability }
public Agent(DataBattle board, Team t, Vec startpos, AgentInfo info) {
fergusq/java-nightfall
src/game/DataBattle.java
// Path: src/game/Agent.java // public static enum TurnState { // Ready, //ready to move // Moved, //moved // Done, //used ability // } // // Path: src/util/Vec.java // public class Vec { // public Vec() { // mX = mY = 0; // } // public Vec(int x, int y) { // mX = x; // mY = y; // } // public int getX() { // return mX; // } // public int getY() { // return mY; // } // public Vec add(Vec other) { // return new Vec(mX + other.mX, mY + other.mY); // } // public Vec sub(Vec other) { // return new Vec(mX - other.mX, mY - other.mY); // } // public Vec mul(int other) { // return new Vec(mX*other, mY*other); // } // public Vec div(int other) { // return new Vec(mX/other, mY/other); // } // public Vec neg() { // return new Vec(-mX, -mY); // } // public boolean eq(Vec other) { // return mX == other.mX && mY == other.mY; // } // public boolean eq(int x, int y) { // return mX == x && mY == y; // } // public FVec fvec() { // return new FVec((float)mX, (float)mY); // } // public static Vec[] getDirs() { // return mDirs; // } // public static Vec[] getHorizontalDirs() { // return mHorizontalDirs; // } // public static Vec[] getVerticalDirs() { // return mVerticalDirs; // } // private int mX, mY; // private static final Vec[] mDirs = {new Vec(0, 1), new Vec(0, -1), new Vec(1, 0), new Vec(-1, 0)}; // private static final Vec[] mVerticalDirs = {new Vec(0, 1), new Vec(0, -1)}; // private static final Vec[] mHorizontalDirs = {new Vec(1, 0), new Vec(-1, 0)}; // // public String toString() { // return "Vec(" + mX + ", " + mY + ")"; // } // }
import game.Agent.TurnState; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import util.Vec;
package game; public class DataBattle { /////////////// board utility classes ///////////// //how to draw a tile public static enum TileOverlay { None, //no overlay Neg, //red - (neg)ative stuff Pos, //blue - (pos)itive stuff Mod, //green - (mod)ification to the tile Sel, //white - (sel)ection Move, //box - This is in movement range MoveTo, //arrow - (move to) here MoveToNorth, MoveToSouth, MoveToEast, MoveToWest } //board tile public static class Tile { boolean Upload = false; boolean Select = false; boolean Flood = false; boolean Data = false; int FloodNum = 0; boolean Filled = true; int Credit = 0; Agent Agent = null; TileOverlay Overlay = TileOverlay.None; } ///////////// signals for view ///////////// //signal agent damaged public static interface ListenerAgentDamage {
// Path: src/game/Agent.java // public static enum TurnState { // Ready, //ready to move // Moved, //moved // Done, //used ability // } // // Path: src/util/Vec.java // public class Vec { // public Vec() { // mX = mY = 0; // } // public Vec(int x, int y) { // mX = x; // mY = y; // } // public int getX() { // return mX; // } // public int getY() { // return mY; // } // public Vec add(Vec other) { // return new Vec(mX + other.mX, mY + other.mY); // } // public Vec sub(Vec other) { // return new Vec(mX - other.mX, mY - other.mY); // } // public Vec mul(int other) { // return new Vec(mX*other, mY*other); // } // public Vec div(int other) { // return new Vec(mX/other, mY/other); // } // public Vec neg() { // return new Vec(-mX, -mY); // } // public boolean eq(Vec other) { // return mX == other.mX && mY == other.mY; // } // public boolean eq(int x, int y) { // return mX == x && mY == y; // } // public FVec fvec() { // return new FVec((float)mX, (float)mY); // } // public static Vec[] getDirs() { // return mDirs; // } // public static Vec[] getHorizontalDirs() { // return mHorizontalDirs; // } // public static Vec[] getVerticalDirs() { // return mVerticalDirs; // } // private int mX, mY; // private static final Vec[] mDirs = {new Vec(0, 1), new Vec(0, -1), new Vec(1, 0), new Vec(-1, 0)}; // private static final Vec[] mVerticalDirs = {new Vec(0, 1), new Vec(0, -1)}; // private static final Vec[] mHorizontalDirs = {new Vec(1, 0), new Vec(-1, 0)}; // // public String toString() { // return "Vec(" + mX + ", " + mY + ")"; // } // } // Path: src/game/DataBattle.java import game.Agent.TurnState; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import util.Vec; package game; public class DataBattle { /////////////// board utility classes ///////////// //how to draw a tile public static enum TileOverlay { None, //no overlay Neg, //red - (neg)ative stuff Pos, //blue - (pos)itive stuff Mod, //green - (mod)ification to the tile Sel, //white - (sel)ection Move, //box - This is in movement range MoveTo, //arrow - (move to) here MoveToNorth, MoveToSouth, MoveToEast, MoveToWest } //board tile public static class Tile { boolean Upload = false; boolean Select = false; boolean Flood = false; boolean Data = false; int FloodNum = 0; boolean Filled = true; int Credit = 0; Agent Agent = null; TileOverlay Overlay = TileOverlay.None; } ///////////// signals for view ///////////// //signal agent damaged public static interface ListenerAgentDamage {
public void onAgentDamage(Vec sq);
fergusq/java-nightfall
src/game/DataBattle.java
// Path: src/game/Agent.java // public static enum TurnState { // Ready, //ready to move // Moved, //moved // Done, //used ability // } // // Path: src/util/Vec.java // public class Vec { // public Vec() { // mX = mY = 0; // } // public Vec(int x, int y) { // mX = x; // mY = y; // } // public int getX() { // return mX; // } // public int getY() { // return mY; // } // public Vec add(Vec other) { // return new Vec(mX + other.mX, mY + other.mY); // } // public Vec sub(Vec other) { // return new Vec(mX - other.mX, mY - other.mY); // } // public Vec mul(int other) { // return new Vec(mX*other, mY*other); // } // public Vec div(int other) { // return new Vec(mX/other, mY/other); // } // public Vec neg() { // return new Vec(-mX, -mY); // } // public boolean eq(Vec other) { // return mX == other.mX && mY == other.mY; // } // public boolean eq(int x, int y) { // return mX == x && mY == y; // } // public FVec fvec() { // return new FVec((float)mX, (float)mY); // } // public static Vec[] getDirs() { // return mDirs; // } // public static Vec[] getHorizontalDirs() { // return mHorizontalDirs; // } // public static Vec[] getVerticalDirs() { // return mVerticalDirs; // } // private int mX, mY; // private static final Vec[] mDirs = {new Vec(0, 1), new Vec(0, -1), new Vec(1, 0), new Vec(-1, 0)}; // private static final Vec[] mVerticalDirs = {new Vec(0, 1), new Vec(0, -1)}; // private static final Vec[] mHorizontalDirs = {new Vec(1, 0), new Vec(-1, 0)}; // // public String toString() { // return "Vec(" + mX + ", " + mY + ")"; // } // }
import game.Agent.TurnState; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import util.Vec;
} } private void moveFloodInternal(Agent a, Vec pos, int range, int dist) { Tile tl = getTile(pos); if (tl == null || (tl.Flood && tl.FloodNum >= dist) || !tl.Filled || (tl.Agent != null && tl.Agent != a)) return; if (tl.Agent == null || tl.Agent == a) tl.Overlay = TileOverlay.Move; tl.Flood = true; if (range > 0) //adjacent for (Vec v : Vec.getDirs()) moveFloodInternal(a, pos.add(v), range-1, dist+1); } public Team getTurn() { return mTeams.get(mTurn); } public void nextTurn() { mTurn++; if (mTurn >= mTeams.size()) mTurn = 0; //make all agents ready again for (Agent a : mAgents) { if (a.getTeam() == mTeams.get(mTurn)) {
// Path: src/game/Agent.java // public static enum TurnState { // Ready, //ready to move // Moved, //moved // Done, //used ability // } // // Path: src/util/Vec.java // public class Vec { // public Vec() { // mX = mY = 0; // } // public Vec(int x, int y) { // mX = x; // mY = y; // } // public int getX() { // return mX; // } // public int getY() { // return mY; // } // public Vec add(Vec other) { // return new Vec(mX + other.mX, mY + other.mY); // } // public Vec sub(Vec other) { // return new Vec(mX - other.mX, mY - other.mY); // } // public Vec mul(int other) { // return new Vec(mX*other, mY*other); // } // public Vec div(int other) { // return new Vec(mX/other, mY/other); // } // public Vec neg() { // return new Vec(-mX, -mY); // } // public boolean eq(Vec other) { // return mX == other.mX && mY == other.mY; // } // public boolean eq(int x, int y) { // return mX == x && mY == y; // } // public FVec fvec() { // return new FVec((float)mX, (float)mY); // } // public static Vec[] getDirs() { // return mDirs; // } // public static Vec[] getHorizontalDirs() { // return mHorizontalDirs; // } // public static Vec[] getVerticalDirs() { // return mVerticalDirs; // } // private int mX, mY; // private static final Vec[] mDirs = {new Vec(0, 1), new Vec(0, -1), new Vec(1, 0), new Vec(-1, 0)}; // private static final Vec[] mVerticalDirs = {new Vec(0, 1), new Vec(0, -1)}; // private static final Vec[] mHorizontalDirs = {new Vec(1, 0), new Vec(-1, 0)}; // // public String toString() { // return "Vec(" + mX + ", " + mY + ")"; // } // } // Path: src/game/DataBattle.java import game.Agent.TurnState; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import util.Vec; } } private void moveFloodInternal(Agent a, Vec pos, int range, int dist) { Tile tl = getTile(pos); if (tl == null || (tl.Flood && tl.FloodNum >= dist) || !tl.Filled || (tl.Agent != null && tl.Agent != a)) return; if (tl.Agent == null || tl.Agent == a) tl.Overlay = TileOverlay.Move; tl.Flood = true; if (range > 0) //adjacent for (Vec v : Vec.getDirs()) moveFloodInternal(a, pos.add(v), range-1, dist+1); } public Team getTurn() { return mTeams.get(mTurn); } public void nextTurn() { mTurn++; if (mTurn >= mTeams.size()) mTurn = 0; //make all agents ready again for (Agent a : mAgents) { if (a.getTeam() == mTeams.get(mTurn)) {
a.setTurnState(TurnState.Ready);
fergusq/java-nightfall
src/game/AgentInfo.java
// Path: src/game/DataBattle.java // public static enum TileOverlay { // None, //no overlay // Neg, //red - (neg)ative stuff // Pos, //blue - (pos)itive stuff // Mod, //green - (mod)ification to the tile // Sel, //white - (sel)ection // Move, //box - This is in movement range // MoveTo, //arrow - (move to) here // MoveToNorth, // MoveToSouth, // MoveToEast, // MoveToWest // }
import game.DataBattle.TileOverlay; import java.util.*; import util.*; import java.awt.Color; import java.awt.Image;
public abstract void select(Agent src); public abstract int range(); public abstract int damage(); public abstract int minSize(); public final String getName() { return mName; } public final String getDesc() { return mDesc; } public final void setName(String s) { mName = s; } public final void setDesc(String s) { mDesc = s; } private String mDesc = ""; private String mName = ""; } public static class AbilityDamageGeneric extends Ability { public AbilityDamageGeneric(String name, String desc, int range, int minsize, int dmg) { setName(name); setDesc(desc); mMinSize = minsize; mRange = range; mDamage = dmg; } public void select(Agent src) { if (src.getSize() >= mMinSize)
// Path: src/game/DataBattle.java // public static enum TileOverlay { // None, //no overlay // Neg, //red - (neg)ative stuff // Pos, //blue - (pos)itive stuff // Mod, //green - (mod)ification to the tile // Sel, //white - (sel)ection // Move, //box - This is in movement range // MoveTo, //arrow - (move to) here // MoveToNorth, // MoveToSouth, // MoveToEast, // MoveToWest // } // Path: src/game/AgentInfo.java import game.DataBattle.TileOverlay; import java.util.*; import util.*; import java.awt.Color; import java.awt.Image; public abstract void select(Agent src); public abstract int range(); public abstract int damage(); public abstract int minSize(); public final String getName() { return mName; } public final String getDesc() { return mDesc; } public final void setName(String s) { mName = s; } public final void setDesc(String s) { mDesc = s; } private String mDesc = ""; private String mName = ""; } public static class AbilityDamageGeneric extends Ability { public AbilityDamageGeneric(String name, String desc, int range, int minsize, int dmg) { setName(name); setDesc(desc); mMinSize = minsize; mRange = range; mDamage = dmg; } public void select(Agent src) { if (src.getSize() >= mMinSize)
src.getBoard().attackFlood(src.getPos(), mRange, TileOverlay.Neg);
fergusq/java-nightfall
src/game/DataBattleInfo.java
// Path: src/util/Vec.java // public class Vec { // public Vec() { // mX = mY = 0; // } // public Vec(int x, int y) { // mX = x; // mY = y; // } // public int getX() { // return mX; // } // public int getY() { // return mY; // } // public Vec add(Vec other) { // return new Vec(mX + other.mX, mY + other.mY); // } // public Vec sub(Vec other) { // return new Vec(mX - other.mX, mY - other.mY); // } // public Vec mul(int other) { // return new Vec(mX*other, mY*other); // } // public Vec div(int other) { // return new Vec(mX/other, mY/other); // } // public Vec neg() { // return new Vec(-mX, -mY); // } // public boolean eq(Vec other) { // return mX == other.mX && mY == other.mY; // } // public boolean eq(int x, int y) { // return mX == x && mY == y; // } // public FVec fvec() { // return new FVec((float)mX, (float)mY); // } // public static Vec[] getDirs() { // return mDirs; // } // public static Vec[] getHorizontalDirs() { // return mHorizontalDirs; // } // public static Vec[] getVerticalDirs() { // return mVerticalDirs; // } // private int mX, mY; // private static final Vec[] mDirs = {new Vec(0, 1), new Vec(0, -1), new Vec(1, 0), new Vec(-1, 0)}; // private static final Vec[] mVerticalDirs = {new Vec(0, 1), new Vec(0, -1)}; // private static final Vec[] mHorizontalDirs = {new Vec(1, 0), new Vec(-1, 0)}; // // public String toString() { // return "Vec(" + mX + ", " + mY + ")"; // } // }
import util.Vec;
package game; public class DataBattleInfo { public static class CreditEntry {
// Path: src/util/Vec.java // public class Vec { // public Vec() { // mX = mY = 0; // } // public Vec(int x, int y) { // mX = x; // mY = y; // } // public int getX() { // return mX; // } // public int getY() { // return mY; // } // public Vec add(Vec other) { // return new Vec(mX + other.mX, mY + other.mY); // } // public Vec sub(Vec other) { // return new Vec(mX - other.mX, mY - other.mY); // } // public Vec mul(int other) { // return new Vec(mX*other, mY*other); // } // public Vec div(int other) { // return new Vec(mX/other, mY/other); // } // public Vec neg() { // return new Vec(-mX, -mY); // } // public boolean eq(Vec other) { // return mX == other.mX && mY == other.mY; // } // public boolean eq(int x, int y) { // return mX == x && mY == y; // } // public FVec fvec() { // return new FVec((float)mX, (float)mY); // } // public static Vec[] getDirs() { // return mDirs; // } // public static Vec[] getHorizontalDirs() { // return mHorizontalDirs; // } // public static Vec[] getVerticalDirs() { // return mVerticalDirs; // } // private int mX, mY; // private static final Vec[] mDirs = {new Vec(0, 1), new Vec(0, -1), new Vec(1, 0), new Vec(-1, 0)}; // private static final Vec[] mVerticalDirs = {new Vec(0, 1), new Vec(0, -1)}; // private static final Vec[] mHorizontalDirs = {new Vec(1, 0), new Vec(-1, 0)}; // // public String toString() { // return "Vec(" + mX + ", " + mY + ")"; // } // } // Path: src/game/DataBattleInfo.java import util.Vec; package game; public class DataBattleInfo { public static class CreditEntry {
Vec Pos;
fergusq/java-nightfall
src/game/GameSession.java
// Path: src/util/UDim.java // public class UDim { // public UDim() { // this(0, 0, 0, 0); // } // public UDim(FVec offset) { // this(offset.getX(), offset.getY(), 0, 0); // } // public UDim(float offsetx, float offsety) { // this(offsetx, offsety, 0, 0); // } // public UDim(FVec offset, FVec scale) { // this(offset.getX(), offset.getY(), scale.getX(), scale.getY()); // } // public UDim(float offsetx, float offsety, float scalex, float scaley) { // mXOffset = offsetx; // mYOffset = offsety; // mXScale = scalex; // mYScale = scaley; // } // // public FVec getOffset() { // return new FVec(mXOffset, mYOffset); // } // // public float getXOffset() { // return mXOffset; // } // // public float getYOffset() { // return mYOffset; // } // // public FVec getScale() { // return new FVec(mXScale, mYScale); // } // // public float getXScale() { // return mXScale; // } // // public float getYScale() { // return mYScale; // } // // private float mXOffset, mYOffset, mXScale, mYScale; // } // // Path: src/game/Agent.java // public static enum TurnState { // Ready, //ready to move // Moved, //moved // Done, //used ability // } // // Path: src/game/AgentInfo.java // public static abstract class Ability { // public abstract void apply(Agent src, Agent target, Vec trg); // public abstract void select(Agent src); // public abstract int range(); // public abstract int damage(); // public abstract int minSize(); // public final String getName() { // return mName; // } // public final String getDesc() { // return mDesc; // } // public final void setName(String s) { // mName = s; // } // public final void setDesc(String s) { // mDesc = s; // } // private String mDesc = ""; // private String mName = ""; // } // // Path: src/game/NodeMap.java // public static class Node { // public static enum Type { // Warez, // Battle; // } // public static enum Status { // Unknown, // Visible, Open, // Defeated; // } // public void setDefeated() { // NStatus = Status.Defeated; // for (Node n : Adjacent) { // if (n.NStatus == Status.Unknown || n.NStatus == Status.Visible) // n.NStatus = Status.Open; // } // } // public void setVisible() { // NStatus = Status.Visible; // } // public void setOpen() { // NStatus = Status.Open; // } // public boolean isOpen() { // return NStatus == Status.Defeated || NStatus == Status.Open; // } // public String Name; // public DataBattleInfo DataBattle; // public List<WarezItem> Warez; // public Type NType; // public Status NStatus; // public String Title; // public String Desc; // public Image Image; // public Image DarkImage; // public Vec Pos; // public ArrayList<Node> Adjacent = new ArrayList<Node>(); // public int GroupId; // } // // Path: src/gui/WidgetRoot.java // public class WidgetRoot extends Widget { // public void invokeLayout(Vec windowsize) { // setSize(new UDim(windowsize.fvec())); // internalOnLayout(true); // } // // public void invokeRender(RenderTarget t) { // internalOnRender(t); // } // // public void invokeEvent(Event e) { // Input in = e.getInput(); // in.setPrevMouseTarget(); // // // if (e.getEventType() == EventType.Key) { // if (in.getKeyTarget() == null) { // internalOnEvent(e); // } else { // KeyEvent ke = (KeyEvent)e; // switch (ke.getKeyEventType()) { // case Press: // in.getKeyTarget().onKeyDown.fire(ke); // break; // case Release: // in.getKeyTarget().onKeyUp.fire(ke); // break; // } // } // } else { // internalOnEvent(e); // } // // // if (in.getMouseTarget() != in.getPrevMouseTarget()) { // if (in.getPrevMouseTarget() != null) // in.getPrevMouseTarget().onMouseLeave.fire(new MouseEvent(MouseEventType.Leave, in)); // if (in.getMouseTarget() != null) // in.getMouseTarget().onMouseEnter.fire(new MouseEvent(MouseEventType.Enter, in)); // } // } // }
import java.awt.Color; import java.util.ArrayList; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.FileNotFoundException; import util.UDim; import game.Agent.TurnState; import game.AgentInfo.Ability; import game.NodeMap.Node; import gui.WidgetRoot; import json.*;
package game; public class GameSession { public GameSession() { try { //// load the agent library mAgentLibrary.addAbilitySource("BasicAttack", new AgentLibrary.AbilitySource() {
// Path: src/util/UDim.java // public class UDim { // public UDim() { // this(0, 0, 0, 0); // } // public UDim(FVec offset) { // this(offset.getX(), offset.getY(), 0, 0); // } // public UDim(float offsetx, float offsety) { // this(offsetx, offsety, 0, 0); // } // public UDim(FVec offset, FVec scale) { // this(offset.getX(), offset.getY(), scale.getX(), scale.getY()); // } // public UDim(float offsetx, float offsety, float scalex, float scaley) { // mXOffset = offsetx; // mYOffset = offsety; // mXScale = scalex; // mYScale = scaley; // } // // public FVec getOffset() { // return new FVec(mXOffset, mYOffset); // } // // public float getXOffset() { // return mXOffset; // } // // public float getYOffset() { // return mYOffset; // } // // public FVec getScale() { // return new FVec(mXScale, mYScale); // } // // public float getXScale() { // return mXScale; // } // // public float getYScale() { // return mYScale; // } // // private float mXOffset, mYOffset, mXScale, mYScale; // } // // Path: src/game/Agent.java // public static enum TurnState { // Ready, //ready to move // Moved, //moved // Done, //used ability // } // // Path: src/game/AgentInfo.java // public static abstract class Ability { // public abstract void apply(Agent src, Agent target, Vec trg); // public abstract void select(Agent src); // public abstract int range(); // public abstract int damage(); // public abstract int minSize(); // public final String getName() { // return mName; // } // public final String getDesc() { // return mDesc; // } // public final void setName(String s) { // mName = s; // } // public final void setDesc(String s) { // mDesc = s; // } // private String mDesc = ""; // private String mName = ""; // } // // Path: src/game/NodeMap.java // public static class Node { // public static enum Type { // Warez, // Battle; // } // public static enum Status { // Unknown, // Visible, Open, // Defeated; // } // public void setDefeated() { // NStatus = Status.Defeated; // for (Node n : Adjacent) { // if (n.NStatus == Status.Unknown || n.NStatus == Status.Visible) // n.NStatus = Status.Open; // } // } // public void setVisible() { // NStatus = Status.Visible; // } // public void setOpen() { // NStatus = Status.Open; // } // public boolean isOpen() { // return NStatus == Status.Defeated || NStatus == Status.Open; // } // public String Name; // public DataBattleInfo DataBattle; // public List<WarezItem> Warez; // public Type NType; // public Status NStatus; // public String Title; // public String Desc; // public Image Image; // public Image DarkImage; // public Vec Pos; // public ArrayList<Node> Adjacent = new ArrayList<Node>(); // public int GroupId; // } // // Path: src/gui/WidgetRoot.java // public class WidgetRoot extends Widget { // public void invokeLayout(Vec windowsize) { // setSize(new UDim(windowsize.fvec())); // internalOnLayout(true); // } // // public void invokeRender(RenderTarget t) { // internalOnRender(t); // } // // public void invokeEvent(Event e) { // Input in = e.getInput(); // in.setPrevMouseTarget(); // // // if (e.getEventType() == EventType.Key) { // if (in.getKeyTarget() == null) { // internalOnEvent(e); // } else { // KeyEvent ke = (KeyEvent)e; // switch (ke.getKeyEventType()) { // case Press: // in.getKeyTarget().onKeyDown.fire(ke); // break; // case Release: // in.getKeyTarget().onKeyUp.fire(ke); // break; // } // } // } else { // internalOnEvent(e); // } // // // if (in.getMouseTarget() != in.getPrevMouseTarget()) { // if (in.getPrevMouseTarget() != null) // in.getPrevMouseTarget().onMouseLeave.fire(new MouseEvent(MouseEventType.Leave, in)); // if (in.getMouseTarget() != null) // in.getMouseTarget().onMouseEnter.fire(new MouseEvent(MouseEventType.Enter, in)); // } // } // } // Path: src/game/GameSession.java import java.awt.Color; import java.util.ArrayList; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.FileNotFoundException; import util.UDim; import game.Agent.TurnState; import game.AgentInfo.Ability; import game.NodeMap.Node; import gui.WidgetRoot; import json.*; package game; public class GameSession { public GameSession() { try { //// load the agent library mAgentLibrary.addAbilitySource("BasicAttack", new AgentLibrary.AbilitySource() {
public Ability loadAbility(JSNode nd) {
fergusq/java-nightfall
src/game/GameSession.java
// Path: src/util/UDim.java // public class UDim { // public UDim() { // this(0, 0, 0, 0); // } // public UDim(FVec offset) { // this(offset.getX(), offset.getY(), 0, 0); // } // public UDim(float offsetx, float offsety) { // this(offsetx, offsety, 0, 0); // } // public UDim(FVec offset, FVec scale) { // this(offset.getX(), offset.getY(), scale.getX(), scale.getY()); // } // public UDim(float offsetx, float offsety, float scalex, float scaley) { // mXOffset = offsetx; // mYOffset = offsety; // mXScale = scalex; // mYScale = scaley; // } // // public FVec getOffset() { // return new FVec(mXOffset, mYOffset); // } // // public float getXOffset() { // return mXOffset; // } // // public float getYOffset() { // return mYOffset; // } // // public FVec getScale() { // return new FVec(mXScale, mYScale); // } // // public float getXScale() { // return mXScale; // } // // public float getYScale() { // return mYScale; // } // // private float mXOffset, mYOffset, mXScale, mYScale; // } // // Path: src/game/Agent.java // public static enum TurnState { // Ready, //ready to move // Moved, //moved // Done, //used ability // } // // Path: src/game/AgentInfo.java // public static abstract class Ability { // public abstract void apply(Agent src, Agent target, Vec trg); // public abstract void select(Agent src); // public abstract int range(); // public abstract int damage(); // public abstract int minSize(); // public final String getName() { // return mName; // } // public final String getDesc() { // return mDesc; // } // public final void setName(String s) { // mName = s; // } // public final void setDesc(String s) { // mDesc = s; // } // private String mDesc = ""; // private String mName = ""; // } // // Path: src/game/NodeMap.java // public static class Node { // public static enum Type { // Warez, // Battle; // } // public static enum Status { // Unknown, // Visible, Open, // Defeated; // } // public void setDefeated() { // NStatus = Status.Defeated; // for (Node n : Adjacent) { // if (n.NStatus == Status.Unknown || n.NStatus == Status.Visible) // n.NStatus = Status.Open; // } // } // public void setVisible() { // NStatus = Status.Visible; // } // public void setOpen() { // NStatus = Status.Open; // } // public boolean isOpen() { // return NStatus == Status.Defeated || NStatus == Status.Open; // } // public String Name; // public DataBattleInfo DataBattle; // public List<WarezItem> Warez; // public Type NType; // public Status NStatus; // public String Title; // public String Desc; // public Image Image; // public Image DarkImage; // public Vec Pos; // public ArrayList<Node> Adjacent = new ArrayList<Node>(); // public int GroupId; // } // // Path: src/gui/WidgetRoot.java // public class WidgetRoot extends Widget { // public void invokeLayout(Vec windowsize) { // setSize(new UDim(windowsize.fvec())); // internalOnLayout(true); // } // // public void invokeRender(RenderTarget t) { // internalOnRender(t); // } // // public void invokeEvent(Event e) { // Input in = e.getInput(); // in.setPrevMouseTarget(); // // // if (e.getEventType() == EventType.Key) { // if (in.getKeyTarget() == null) { // internalOnEvent(e); // } else { // KeyEvent ke = (KeyEvent)e; // switch (ke.getKeyEventType()) { // case Press: // in.getKeyTarget().onKeyDown.fire(ke); // break; // case Release: // in.getKeyTarget().onKeyUp.fire(ke); // break; // } // } // } else { // internalOnEvent(e); // } // // // if (in.getMouseTarget() != in.getPrevMouseTarget()) { // if (in.getPrevMouseTarget() != null) // in.getPrevMouseTarget().onMouseLeave.fire(new MouseEvent(MouseEventType.Leave, in)); // if (in.getMouseTarget() != null) // in.getMouseTarget().onMouseEnter.fire(new MouseEvent(MouseEventType.Enter, in)); // } // } // }
import java.awt.Color; import java.util.ArrayList; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.FileNotFoundException; import util.UDim; import game.Agent.TurnState; import game.AgentInfo.Ability; import game.NodeMap.Node; import gui.WidgetRoot; import json.*;
MessageInfo msg = getMessageLibrary().getMessageToShowOnEvent("defeat", battle.getInfo().getName()); if (msg != null) { newMessage(msg); } } public void newMessage(MessageInfo msg) { mNewMessages.add(msg); } public Inventory getInventory() { return mInventory; } public AgentLibrary getAgentLibrary() { return mAgentLibrary; } public DataBattleLibrary getDataBattleLibrary() { return mDataBattleLibrary; } public MessageLibrary getMessageLibrary() { return mMessageLibrary; } public ArrayList<MessageInfo> getNewMessages() { return mNewMessages; }
// Path: src/util/UDim.java // public class UDim { // public UDim() { // this(0, 0, 0, 0); // } // public UDim(FVec offset) { // this(offset.getX(), offset.getY(), 0, 0); // } // public UDim(float offsetx, float offsety) { // this(offsetx, offsety, 0, 0); // } // public UDim(FVec offset, FVec scale) { // this(offset.getX(), offset.getY(), scale.getX(), scale.getY()); // } // public UDim(float offsetx, float offsety, float scalex, float scaley) { // mXOffset = offsetx; // mYOffset = offsety; // mXScale = scalex; // mYScale = scaley; // } // // public FVec getOffset() { // return new FVec(mXOffset, mYOffset); // } // // public float getXOffset() { // return mXOffset; // } // // public float getYOffset() { // return mYOffset; // } // // public FVec getScale() { // return new FVec(mXScale, mYScale); // } // // public float getXScale() { // return mXScale; // } // // public float getYScale() { // return mYScale; // } // // private float mXOffset, mYOffset, mXScale, mYScale; // } // // Path: src/game/Agent.java // public static enum TurnState { // Ready, //ready to move // Moved, //moved // Done, //used ability // } // // Path: src/game/AgentInfo.java // public static abstract class Ability { // public abstract void apply(Agent src, Agent target, Vec trg); // public abstract void select(Agent src); // public abstract int range(); // public abstract int damage(); // public abstract int minSize(); // public final String getName() { // return mName; // } // public final String getDesc() { // return mDesc; // } // public final void setName(String s) { // mName = s; // } // public final void setDesc(String s) { // mDesc = s; // } // private String mDesc = ""; // private String mName = ""; // } // // Path: src/game/NodeMap.java // public static class Node { // public static enum Type { // Warez, // Battle; // } // public static enum Status { // Unknown, // Visible, Open, // Defeated; // } // public void setDefeated() { // NStatus = Status.Defeated; // for (Node n : Adjacent) { // if (n.NStatus == Status.Unknown || n.NStatus == Status.Visible) // n.NStatus = Status.Open; // } // } // public void setVisible() { // NStatus = Status.Visible; // } // public void setOpen() { // NStatus = Status.Open; // } // public boolean isOpen() { // return NStatus == Status.Defeated || NStatus == Status.Open; // } // public String Name; // public DataBattleInfo DataBattle; // public List<WarezItem> Warez; // public Type NType; // public Status NStatus; // public String Title; // public String Desc; // public Image Image; // public Image DarkImage; // public Vec Pos; // public ArrayList<Node> Adjacent = new ArrayList<Node>(); // public int GroupId; // } // // Path: src/gui/WidgetRoot.java // public class WidgetRoot extends Widget { // public void invokeLayout(Vec windowsize) { // setSize(new UDim(windowsize.fvec())); // internalOnLayout(true); // } // // public void invokeRender(RenderTarget t) { // internalOnRender(t); // } // // public void invokeEvent(Event e) { // Input in = e.getInput(); // in.setPrevMouseTarget(); // // // if (e.getEventType() == EventType.Key) { // if (in.getKeyTarget() == null) { // internalOnEvent(e); // } else { // KeyEvent ke = (KeyEvent)e; // switch (ke.getKeyEventType()) { // case Press: // in.getKeyTarget().onKeyDown.fire(ke); // break; // case Release: // in.getKeyTarget().onKeyUp.fire(ke); // break; // } // } // } else { // internalOnEvent(e); // } // // // if (in.getMouseTarget() != in.getPrevMouseTarget()) { // if (in.getPrevMouseTarget() != null) // in.getPrevMouseTarget().onMouseLeave.fire(new MouseEvent(MouseEventType.Leave, in)); // if (in.getMouseTarget() != null) // in.getMouseTarget().onMouseEnter.fire(new MouseEvent(MouseEventType.Enter, in)); // } // } // } // Path: src/game/GameSession.java import java.awt.Color; import java.util.ArrayList; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.FileNotFoundException; import util.UDim; import game.Agent.TurnState; import game.AgentInfo.Ability; import game.NodeMap.Node; import gui.WidgetRoot; import json.*; MessageInfo msg = getMessageLibrary().getMessageToShowOnEvent("defeat", battle.getInfo().getName()); if (msg != null) { newMessage(msg); } } public void newMessage(MessageInfo msg) { mNewMessages.add(msg); } public Inventory getInventory() { return mInventory; } public AgentLibrary getAgentLibrary() { return mAgentLibrary; } public DataBattleLibrary getDataBattleLibrary() { return mDataBattleLibrary; } public MessageLibrary getMessageLibrary() { return mMessageLibrary; } public ArrayList<MessageInfo> getNewMessages() { return mNewMessages; }
public void setGuiRoot(WidgetRoot r) {
fergusq/java-nightfall
src/gui/CoreApplet.java
// Path: src/util/Vec.java // public class Vec { // public Vec() { // mX = mY = 0; // } // public Vec(int x, int y) { // mX = x; // mY = y; // } // public int getX() { // return mX; // } // public int getY() { // return mY; // } // public Vec add(Vec other) { // return new Vec(mX + other.mX, mY + other.mY); // } // public Vec sub(Vec other) { // return new Vec(mX - other.mX, mY - other.mY); // } // public Vec mul(int other) { // return new Vec(mX*other, mY*other); // } // public Vec div(int other) { // return new Vec(mX/other, mY/other); // } // public Vec neg() { // return new Vec(-mX, -mY); // } // public boolean eq(Vec other) { // return mX == other.mX && mY == other.mY; // } // public boolean eq(int x, int y) { // return mX == x && mY == y; // } // public FVec fvec() { // return new FVec((float)mX, (float)mY); // } // public static Vec[] getDirs() { // return mDirs; // } // public static Vec[] getHorizontalDirs() { // return mHorizontalDirs; // } // public static Vec[] getVerticalDirs() { // return mVerticalDirs; // } // private int mX, mY; // private static final Vec[] mDirs = {new Vec(0, 1), new Vec(0, -1), new Vec(1, 0), new Vec(-1, 0)}; // private static final Vec[] mVerticalDirs = {new Vec(0, 1), new Vec(0, -1)}; // private static final Vec[] mHorizontalDirs = {new Vec(1, 0), new Vec(-1, 0)}; // // public String toString() { // return "Vec(" + mX + ", " + mY + ")"; // } // }
import java.applet.Applet; import java.awt.Graphics; import java.awt.Image; import java.awt.event.KeyListener; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelListener; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import util.Vec; import input.*;
package gui; public class CoreApplet extends Applet implements CoreApp, MouseListener, MouseMotionListener, MouseWheelListener, KeyListener { //CoreApp methods public RenderTarget getRenderTarget() { return mRenderTarget; } public Input getInput() { return mInput; } public final void render() { repaint(); } public final void terminate() { mRunning = false; } public final void setFPS(float fps) { mFPS = fps; }
// Path: src/util/Vec.java // public class Vec { // public Vec() { // mX = mY = 0; // } // public Vec(int x, int y) { // mX = x; // mY = y; // } // public int getX() { // return mX; // } // public int getY() { // return mY; // } // public Vec add(Vec other) { // return new Vec(mX + other.mX, mY + other.mY); // } // public Vec sub(Vec other) { // return new Vec(mX - other.mX, mY - other.mY); // } // public Vec mul(int other) { // return new Vec(mX*other, mY*other); // } // public Vec div(int other) { // return new Vec(mX/other, mY/other); // } // public Vec neg() { // return new Vec(-mX, -mY); // } // public boolean eq(Vec other) { // return mX == other.mX && mY == other.mY; // } // public boolean eq(int x, int y) { // return mX == x && mY == y; // } // public FVec fvec() { // return new FVec((float)mX, (float)mY); // } // public static Vec[] getDirs() { // return mDirs; // } // public static Vec[] getHorizontalDirs() { // return mHorizontalDirs; // } // public static Vec[] getVerticalDirs() { // return mVerticalDirs; // } // private int mX, mY; // private static final Vec[] mDirs = {new Vec(0, 1), new Vec(0, -1), new Vec(1, 0), new Vec(-1, 0)}; // private static final Vec[] mVerticalDirs = {new Vec(0, 1), new Vec(0, -1)}; // private static final Vec[] mHorizontalDirs = {new Vec(1, 0), new Vec(-1, 0)}; // // public String toString() { // return "Vec(" + mX + ", " + mY + ")"; // } // } // Path: src/gui/CoreApplet.java import java.applet.Applet; import java.awt.Graphics; import java.awt.Image; import java.awt.event.KeyListener; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelListener; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import util.Vec; import input.*; package gui; public class CoreApplet extends Applet implements CoreApp, MouseListener, MouseMotionListener, MouseWheelListener, KeyListener { //CoreApp methods public RenderTarget getRenderTarget() { return mRenderTarget; } public Input getInput() { return mInput; } public final void render() { repaint(); } public final void terminate() { mRunning = false; } public final void setFPS(float fps) { mFPS = fps; }
public final void setRenderSize(Vec v) {
fergusq/java-nightfall
src/main/TestApp.java
// Path: src/input/Event.java // public class Event { // public static enum EventType { // Key(1<<0), // Mouse(1<<1), // Custom(1<<2); // // private EventType(int mask) { // mMask = mask; // } // // public int getMask() { // return mMask; // } // // private int mMask; // } // // public static abstract class Listener { // public Listener(int mask) {mMask = mask;} // public int getMask() {return mMask;} //accepted event types // public abstract void onEvent(Event e); // private int mMask; // } // // public static class Signal { // public void connect(Listener l) { // mListeners.add(l); // } // // public void fire(Event e) { // for (Listener l : mListeners) // if ((e.getEventMask() & l.getMask()) != 0) { // l.onEvent(e); // if (e.consumed()) // break; // } // } // // private ArrayList<Listener> mListeners = new ArrayList<Listener>(); // } // // public Event(EventType type, Input input) { // mEventType = type; // mInput = input; // } // // public EventType getEventType() { // return mEventType; // } // // public int getEventMask() { // return mEventType.getMask(); // } // // public boolean consumed() { // return mConsumed; // } // // public void consume() { // mConsumed = true; // } // // public Input getInput() { // return mInput; // } // // private Input mInput; // private boolean mConsumed = false; // private EventType mEventType; // }
import java.awt.*; import gui.*; import input.*; import input.Event; import util.*;
public void onMouseEvent(MouseEvent e) { mSq.setColor(Color.yellow); } }); mSq.onMouseLeave.connect(new MouseEvent.Listener() { public void onMouseEvent(MouseEvent e) { mSq.setColor(Color.red); } }); mSq.onMouseMove.connect(new MouseEvent.Listener() { public void onMouseEvent(MouseEvent e) { if (e.getInput().getButton(MouseEvent.MouseButton.Left)) mSq.setPos(new UDim(e.getInput().getMousePos().fvec().sub(new FVec(50, 50)))); } }); // mRoot.invokeLayout(new Vec(300, 300)); } public void onStep() { //System.out.println("Step..\n"); mRoot.invokeRender(getRenderTarget()); render(); int h = getInput().getKeyState(KeyEvent.Key.Right) ? 3 : 0; h += getInput().getKeyState(KeyEvent.Key.Left) ? -3 : 0; int v = getInput().getKeyState(KeyEvent.Key.Down) ? 3 : 0; v += getInput().getKeyState(KeyEvent.Key.Up) ? -3 : 0; mSq.setPos(new UDim(mSq.getPos().getOffset().add(new FVec(h, v)))); }
// Path: src/input/Event.java // public class Event { // public static enum EventType { // Key(1<<0), // Mouse(1<<1), // Custom(1<<2); // // private EventType(int mask) { // mMask = mask; // } // // public int getMask() { // return mMask; // } // // private int mMask; // } // // public static abstract class Listener { // public Listener(int mask) {mMask = mask;} // public int getMask() {return mMask;} //accepted event types // public abstract void onEvent(Event e); // private int mMask; // } // // public static class Signal { // public void connect(Listener l) { // mListeners.add(l); // } // // public void fire(Event e) { // for (Listener l : mListeners) // if ((e.getEventMask() & l.getMask()) != 0) { // l.onEvent(e); // if (e.consumed()) // break; // } // } // // private ArrayList<Listener> mListeners = new ArrayList<Listener>(); // } // // public Event(EventType type, Input input) { // mEventType = type; // mInput = input; // } // // public EventType getEventType() { // return mEventType; // } // // public int getEventMask() { // return mEventType.getMask(); // } // // public boolean consumed() { // return mConsumed; // } // // public void consume() { // mConsumed = true; // } // // public Input getInput() { // return mInput; // } // // private Input mInput; // private boolean mConsumed = false; // private EventType mEventType; // } // Path: src/main/TestApp.java import java.awt.*; import gui.*; import input.*; import input.Event; import util.*; public void onMouseEvent(MouseEvent e) { mSq.setColor(Color.yellow); } }); mSq.onMouseLeave.connect(new MouseEvent.Listener() { public void onMouseEvent(MouseEvent e) { mSq.setColor(Color.red); } }); mSq.onMouseMove.connect(new MouseEvent.Listener() { public void onMouseEvent(MouseEvent e) { if (e.getInput().getButton(MouseEvent.MouseButton.Left)) mSq.setPos(new UDim(e.getInput().getMousePos().fvec().sub(new FVec(50, 50)))); } }); // mRoot.invokeLayout(new Vec(300, 300)); } public void onStep() { //System.out.println("Step..\n"); mRoot.invokeRender(getRenderTarget()); render(); int h = getInput().getKeyState(KeyEvent.Key.Right) ? 3 : 0; h += getInput().getKeyState(KeyEvent.Key.Left) ? -3 : 0; int v = getInput().getKeyState(KeyEvent.Key.Down) ? 3 : 0; v += getInput().getKeyState(KeyEvent.Key.Up) ? -3 : 0; mSq.setPos(new UDim(mSq.getPos().getOffset().add(new FVec(h, v)))); }
public void onEvent(Event e) {
fergusq/java-nightfall
src/game/AIAction.java
// Path: src/game/Agent.java // public static enum TurnState { // Ready, //ready to move // Moved, //moved // Done, //used ability // } // // Path: src/game/DataBattle.java // public static enum TileOverlay { // None, //no overlay // Neg, //red - (neg)ative stuff // Pos, //blue - (pos)itive stuff // Mod, //green - (mod)ification to the tile // Sel, //white - (sel)ection // Move, //box - This is in movement range // MoveTo, //arrow - (move to) here // MoveToNorth, // MoveToSouth, // MoveToEast, // MoveToWest // }
import util.*; import game.Agent.TurnState; import game.DataBattle.TileOverlay; import java.util.LinkedList;
package game; public class AIAction { private abstract class IAction { public IAction(int steps) { mStepsLeft = steps; } public void act(Agent a) { onAct(a); mStepsLeft--; } public abstract void onAct(Agent a); public boolean done() { return mStepsLeft == 0; } public int getStep() { return mStepsLeft; } private int mStepsLeft; } public void addSelect() { mActions.addLast(new IAction(10) { public void onAct(Agent a) { if (getStep() == 10) { a.getBoard().clear(true, true, true); //for (Vec v : mMoves) // a.getBoard().getTile(v).Overlay = TileOverlay.Mod;
// Path: src/game/Agent.java // public static enum TurnState { // Ready, //ready to move // Moved, //moved // Done, //used ability // } // // Path: src/game/DataBattle.java // public static enum TileOverlay { // None, //no overlay // Neg, //red - (neg)ative stuff // Pos, //blue - (pos)itive stuff // Mod, //green - (mod)ification to the tile // Sel, //white - (sel)ection // Move, //box - This is in movement range // MoveTo, //arrow - (move to) here // MoveToNorth, // MoveToSouth, // MoveToEast, // MoveToWest // } // Path: src/game/AIAction.java import util.*; import game.Agent.TurnState; import game.DataBattle.TileOverlay; import java.util.LinkedList; package game; public class AIAction { private abstract class IAction { public IAction(int steps) { mStepsLeft = steps; } public void act(Agent a) { onAct(a); mStepsLeft--; } public abstract void onAct(Agent a); public boolean done() { return mStepsLeft == 0; } public int getStep() { return mStepsLeft; } private int mStepsLeft; } public void addSelect() { mActions.addLast(new IAction(10) { public void onAct(Agent a) { if (getStep() == 10) { a.getBoard().clear(true, true, true); //for (Vec v : mMoves) // a.getBoard().getTile(v).Overlay = TileOverlay.Mod;
a.getBoard().getTile(a.getPos()).Overlay = TileOverlay.Sel;
fergusq/java-nightfall
src/game/AIAction.java
// Path: src/game/Agent.java // public static enum TurnState { // Ready, //ready to move // Moved, //moved // Done, //used ability // } // // Path: src/game/DataBattle.java // public static enum TileOverlay { // None, //no overlay // Neg, //red - (neg)ative stuff // Pos, //blue - (pos)itive stuff // Mod, //green - (mod)ification to the tile // Sel, //white - (sel)ection // Move, //box - This is in movement range // MoveTo, //arrow - (move to) here // MoveToNorth, // MoveToSouth, // MoveToEast, // MoveToWest // }
import util.*; import game.Agent.TurnState; import game.DataBattle.TileOverlay; import java.util.LinkedList;
switch (getStep()) { case 10: a.getBoard().clear(true, true, true); ability.select(a); break; case 1: ability.apply(a, a.getBoard().getTile(pos).Agent, pos); a.getBoard().clear(true, true, true); break; } } }); } public void addShowAttack(final AgentInfo.Ability ability) { mActions.addLast(new IAction(10) { public void onAct(Agent a) { if (getStep() == 10) { a.getBoard().clear(true, true, true); ability.select(a); } } }); } public void addDone() { mActions.addLast(new IAction(1) { public void onAct(Agent a) { if (getStep() == 1) { a.getBoard().clear(true, true, true);
// Path: src/game/Agent.java // public static enum TurnState { // Ready, //ready to move // Moved, //moved // Done, //used ability // } // // Path: src/game/DataBattle.java // public static enum TileOverlay { // None, //no overlay // Neg, //red - (neg)ative stuff // Pos, //blue - (pos)itive stuff // Mod, //green - (mod)ification to the tile // Sel, //white - (sel)ection // Move, //box - This is in movement range // MoveTo, //arrow - (move to) here // MoveToNorth, // MoveToSouth, // MoveToEast, // MoveToWest // } // Path: src/game/AIAction.java import util.*; import game.Agent.TurnState; import game.DataBattle.TileOverlay; import java.util.LinkedList; switch (getStep()) { case 10: a.getBoard().clear(true, true, true); ability.select(a); break; case 1: ability.apply(a, a.getBoard().getTile(pos).Agent, pos); a.getBoard().clear(true, true, true); break; } } }); } public void addShowAttack(final AgentInfo.Ability ability) { mActions.addLast(new IAction(10) { public void onAct(Agent a) { if (getStep() == 10) { a.getBoard().clear(true, true, true); ability.select(a); } } }); } public void addDone() { mActions.addLast(new IAction(1) { public void onAct(Agent a) { if (getStep() == 1) { a.getBoard().clear(true, true, true);
a.setTurnState(TurnState.Done);
fergusq/java-nightfall
src/gui/CoreFrame.java
// Path: src/util/Vec.java // public class Vec { // public Vec() { // mX = mY = 0; // } // public Vec(int x, int y) { // mX = x; // mY = y; // } // public int getX() { // return mX; // } // public int getY() { // return mY; // } // public Vec add(Vec other) { // return new Vec(mX + other.mX, mY + other.mY); // } // public Vec sub(Vec other) { // return new Vec(mX - other.mX, mY - other.mY); // } // public Vec mul(int other) { // return new Vec(mX*other, mY*other); // } // public Vec div(int other) { // return new Vec(mX/other, mY/other); // } // public Vec neg() { // return new Vec(-mX, -mY); // } // public boolean eq(Vec other) { // return mX == other.mX && mY == other.mY; // } // public boolean eq(int x, int y) { // return mX == x && mY == y; // } // public FVec fvec() { // return new FVec((float)mX, (float)mY); // } // public static Vec[] getDirs() { // return mDirs; // } // public static Vec[] getHorizontalDirs() { // return mHorizontalDirs; // } // public static Vec[] getVerticalDirs() { // return mVerticalDirs; // } // private int mX, mY; // private static final Vec[] mDirs = {new Vec(0, 1), new Vec(0, -1), new Vec(1, 0), new Vec(-1, 0)}; // private static final Vec[] mVerticalDirs = {new Vec(0, 1), new Vec(0, -1)}; // private static final Vec[] mHorizontalDirs = {new Vec(1, 0), new Vec(-1, 0)}; // // public String toString() { // return "Vec(" + mX + ", " + mY + ")"; // } // }
import java.awt.Panel; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import java.awt.event.KeyListener; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelListener; import java.awt.event.WindowListener; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import util.Vec; import input.*;
package gui; public class CoreFrame extends Panel implements CoreApp, MouseListener, MouseMotionListener, MouseWheelListener, KeyListener { //CoreApp methods public RenderTarget getRenderTarget() { return mRenderTarget; } public Input getInput() { return mInput; } public final void render() { repaint(); } public final void terminate() { mRunning = false; } public final void setFPS(float fps) { mFPS = fps; }
// Path: src/util/Vec.java // public class Vec { // public Vec() { // mX = mY = 0; // } // public Vec(int x, int y) { // mX = x; // mY = y; // } // public int getX() { // return mX; // } // public int getY() { // return mY; // } // public Vec add(Vec other) { // return new Vec(mX + other.mX, mY + other.mY); // } // public Vec sub(Vec other) { // return new Vec(mX - other.mX, mY - other.mY); // } // public Vec mul(int other) { // return new Vec(mX*other, mY*other); // } // public Vec div(int other) { // return new Vec(mX/other, mY/other); // } // public Vec neg() { // return new Vec(-mX, -mY); // } // public boolean eq(Vec other) { // return mX == other.mX && mY == other.mY; // } // public boolean eq(int x, int y) { // return mX == x && mY == y; // } // public FVec fvec() { // return new FVec((float)mX, (float)mY); // } // public static Vec[] getDirs() { // return mDirs; // } // public static Vec[] getHorizontalDirs() { // return mHorizontalDirs; // } // public static Vec[] getVerticalDirs() { // return mVerticalDirs; // } // private int mX, mY; // private static final Vec[] mDirs = {new Vec(0, 1), new Vec(0, -1), new Vec(1, 0), new Vec(-1, 0)}; // private static final Vec[] mVerticalDirs = {new Vec(0, 1), new Vec(0, -1)}; // private static final Vec[] mHorizontalDirs = {new Vec(1, 0), new Vec(-1, 0)}; // // public String toString() { // return "Vec(" + mX + ", " + mY + ")"; // } // } // Path: src/gui/CoreFrame.java import java.awt.Panel; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import java.awt.event.KeyListener; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelListener; import java.awt.event.WindowListener; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import util.Vec; import input.*; package gui; public class CoreFrame extends Panel implements CoreApp, MouseListener, MouseMotionListener, MouseWheelListener, KeyListener { //CoreApp methods public RenderTarget getRenderTarget() { return mRenderTarget; } public Input getInput() { return mInput; } public final void render() { repaint(); } public final void terminate() { mRunning = false; } public final void setFPS(float fps) { mFPS = fps; }
public final void setRenderSize(Vec v) {
fergusq/java-nightfall
src/game/NodeMapView.java
// Path: src/game/NodeMap.java // public static enum Status { // Unknown, // Visible, Open, // Defeated; // } // // Path: src/gui/WidgetText.java // public enum TextAlign { // Right, // Left, // Center; // }
import java.awt.Color; import java.awt.Graphics; import game.NodeMap.Node.Status; import gui.*; import gui.WidgetText.TextAlign; import util.*; import input.*; import java.util.List; import java.util.Collections; import java.util.Comparator; import java.util.ArrayList;
package game; public class NodeMapView extends WidgetRect { private interface IAction { public void onSelect(); public void onDeselect(); public void onClick(NodeMap.Node nd); } /***************************************/ /***************************************/ /***************************************/ private class CutoffCornerWidget extends WidgetRect { // a---b // | | // c---d public CutoffCornerWidget(int a, int b, int c, int d) { mA = a; mB = b; mC = c; mD = d; } public void onRender(RenderTarget t) { Rect r = getRect(); Graphics g = t.getContext(); int h = r.getHeight(); int[] xs = {r.getX()+h*mA, r.getX()+r.getWidth()-h*mB, r.getX()+r.getWidth()-h*mD, r.getX()+h*mC}; int[] ys = {r.getY(), r.getY(), r.getY()+h, r.getY()+h}; g.setColor(getColor()); g.fillPolygon(xs, ys, 4); } private int mA, mB, mC, mD; } private class ActionPanOrSelectNode implements IAction { private void scrollify(Widget w, final Vec dir) { w.onMouseDown.connect(new MouseEvent.Listener() { public void onMouseEvent(MouseEvent e) { mScroll = dir; } }); w.onMouseUp.connect(new MouseEvent.Listener() { public void onMouseEvent(MouseEvent e) { mScroll = new Vec(0, 0); } }); } public ActionPanOrSelectNode() { mWidget = new Widget() { public void onRender(RenderTarget t) { mOriginOffset = mOriginOffset.add(mScroll); } }; mWidget.setSize(new UDim(0, 0, 1, 1)); mWidget.setActive(false); mWidget.setParent(NodeMapView.this); mWidget.setVisible(false); // WidgetImage scrollRight = new WidgetImage(); scrollRight.setPos(new UDim(-64, -64, 1, 0.5f)); scrollRight.setSize(new UDim(64, 128)); scrollRight.setParent(mWidget); scrollRight.setImage(ResourceLoader.LoadImage("scroll-right.png")); scrollify(scrollRight, new Vec(-MAP_SCROLL_SPEED, 0)); // WidgetImage scrollLeft = new WidgetImage(); scrollLeft.setPos(new UDim(0, -64, 0, 0.5f)); scrollLeft.setSize(new UDim(64, 128)); scrollLeft.setParent(mWidget); scrollLeft.setImage(ResourceLoader.LoadImage("scroll-left.png")); scrollify(scrollLeft, new Vec(MAP_SCROLL_SPEED, 0)); // WidgetImage scrollDown = new WidgetImage(); scrollDown.setPos(new UDim(-64, -64, 0.5f, 1)); scrollDown.setSize(new UDim(128, 64)); scrollDown.setParent(mWidget); scrollDown.setImage(ResourceLoader.LoadImage("scroll-down.png")); scrollify(scrollDown, new Vec(0, -MAP_SCROLL_SPEED)); // WidgetImage scrollup = new WidgetImage(); scrollup.setPos(new UDim(-64, 0, 0.5f, 0)); scrollup.setSize(new UDim(128, 64)); scrollup.setParent(mWidget); scrollup.setImage(ResourceLoader.LoadImage("scroll-up.png")); scrollify(scrollup, new Vec(0, MAP_SCROLL_SPEED)); //inv button // CutoffCornerWidget inventoryButton = new CutoffCornerWidget(0, 0, 1, 0); inventoryButton.setSize(new UDim(150, 30)); inventoryButton.setPos(new UDim(-150, 0, 1, 0)); inventoryButton.setColor(HEADER_COLOR); inventoryButton.setParent(NodeMapView.this); WidgetLabel invtext = new WidgetLabel(); invtext.setSize(new UDim(0, 0, 1, 1)); invtext.setBackground(false); invtext.setActive(false); invtext.setTextColor(HEADER_TEXT_COLOR); invtext.setText("INVENTORY"); invtext.setParent(inventoryButton); inventoryButton.onMouseDown.connect(new MouseEvent.Listener() { public void onMouseEvent(MouseEvent e) { setAction(mActionInventory); } }); } public void onSelect() { showGui(); } public void onDeselect() { hideGui(); } public void onClick(NodeMap.Node nd) {
// Path: src/game/NodeMap.java // public static enum Status { // Unknown, // Visible, Open, // Defeated; // } // // Path: src/gui/WidgetText.java // public enum TextAlign { // Right, // Left, // Center; // } // Path: src/game/NodeMapView.java import java.awt.Color; import java.awt.Graphics; import game.NodeMap.Node.Status; import gui.*; import gui.WidgetText.TextAlign; import util.*; import input.*; import java.util.List; import java.util.Collections; import java.util.Comparator; import java.util.ArrayList; package game; public class NodeMapView extends WidgetRect { private interface IAction { public void onSelect(); public void onDeselect(); public void onClick(NodeMap.Node nd); } /***************************************/ /***************************************/ /***************************************/ private class CutoffCornerWidget extends WidgetRect { // a---b // | | // c---d public CutoffCornerWidget(int a, int b, int c, int d) { mA = a; mB = b; mC = c; mD = d; } public void onRender(RenderTarget t) { Rect r = getRect(); Graphics g = t.getContext(); int h = r.getHeight(); int[] xs = {r.getX()+h*mA, r.getX()+r.getWidth()-h*mB, r.getX()+r.getWidth()-h*mD, r.getX()+h*mC}; int[] ys = {r.getY(), r.getY(), r.getY()+h, r.getY()+h}; g.setColor(getColor()); g.fillPolygon(xs, ys, 4); } private int mA, mB, mC, mD; } private class ActionPanOrSelectNode implements IAction { private void scrollify(Widget w, final Vec dir) { w.onMouseDown.connect(new MouseEvent.Listener() { public void onMouseEvent(MouseEvent e) { mScroll = dir; } }); w.onMouseUp.connect(new MouseEvent.Listener() { public void onMouseEvent(MouseEvent e) { mScroll = new Vec(0, 0); } }); } public ActionPanOrSelectNode() { mWidget = new Widget() { public void onRender(RenderTarget t) { mOriginOffset = mOriginOffset.add(mScroll); } }; mWidget.setSize(new UDim(0, 0, 1, 1)); mWidget.setActive(false); mWidget.setParent(NodeMapView.this); mWidget.setVisible(false); // WidgetImage scrollRight = new WidgetImage(); scrollRight.setPos(new UDim(-64, -64, 1, 0.5f)); scrollRight.setSize(new UDim(64, 128)); scrollRight.setParent(mWidget); scrollRight.setImage(ResourceLoader.LoadImage("scroll-right.png")); scrollify(scrollRight, new Vec(-MAP_SCROLL_SPEED, 0)); // WidgetImage scrollLeft = new WidgetImage(); scrollLeft.setPos(new UDim(0, -64, 0, 0.5f)); scrollLeft.setSize(new UDim(64, 128)); scrollLeft.setParent(mWidget); scrollLeft.setImage(ResourceLoader.LoadImage("scroll-left.png")); scrollify(scrollLeft, new Vec(MAP_SCROLL_SPEED, 0)); // WidgetImage scrollDown = new WidgetImage(); scrollDown.setPos(new UDim(-64, -64, 0.5f, 1)); scrollDown.setSize(new UDim(128, 64)); scrollDown.setParent(mWidget); scrollDown.setImage(ResourceLoader.LoadImage("scroll-down.png")); scrollify(scrollDown, new Vec(0, -MAP_SCROLL_SPEED)); // WidgetImage scrollup = new WidgetImage(); scrollup.setPos(new UDim(-64, 0, 0.5f, 0)); scrollup.setSize(new UDim(128, 64)); scrollup.setParent(mWidget); scrollup.setImage(ResourceLoader.LoadImage("scroll-up.png")); scrollify(scrollup, new Vec(0, MAP_SCROLL_SPEED)); //inv button // CutoffCornerWidget inventoryButton = new CutoffCornerWidget(0, 0, 1, 0); inventoryButton.setSize(new UDim(150, 30)); inventoryButton.setPos(new UDim(-150, 0, 1, 0)); inventoryButton.setColor(HEADER_COLOR); inventoryButton.setParent(NodeMapView.this); WidgetLabel invtext = new WidgetLabel(); invtext.setSize(new UDim(0, 0, 1, 1)); invtext.setBackground(false); invtext.setActive(false); invtext.setTextColor(HEADER_TEXT_COLOR); invtext.setText("INVENTORY"); invtext.setParent(inventoryButton); inventoryButton.onMouseDown.connect(new MouseEvent.Listener() { public void onMouseEvent(MouseEvent e) { setAction(mActionInventory); } }); } public void onSelect() { showGui(); } public void onDeselect() { hideGui(); } public void onClick(NodeMap.Node nd) {
if (nd.NStatus != NodeMap.Node.Status.Unknown) {
mojohaus/mrm
mrm-api/src/main/java/org/codehaus/mojo/mrm/plugin/FileSystemFactory.java
// Path: mrm-api/src/main/java/org/codehaus/mojo/mrm/api/FileSystem.java // public interface FileSystem // extends Serializable // { // /** // * Lists the entries in the specified directory. Some implementations may be lazy caching // * implementations, in which case it is permitted to return either an empty array, or only those entries which // * have been loaded into the cache, so consumers should not assume that a missing entry implies non-existence. // * The only way to be sure that an artifact does not exist is to call the {@link FileEntry#getInputStream()} method, // * although {@link #get(String)} returning <code>null</code> is also definitive, a non-null does not prove // * existence). // * // * @param directory the directory to list the entries of. // * @return a copy of the known entries in the specified directory, never <code>null</code>. The caller can safely // * modify the returned array. // * @since 1.0 // */ // Entry[] listEntries( DirectoryEntry directory ); // // /** // * Returns the root directory entry. // * // * @return the root directory entry. // * @since 1.0 // */ // DirectoryEntry getRoot(); // // /** // * Returns the entry at the specified path. A <code>null</code> result proves the path does not exist, however // * very lazy caching implementations may return a non-null entry for paths which do not exist. // * // * @param path the path to retrieve the {@link Entry} of. // * @return the {@link Entry} or <code>null</code> if the path definitely does not exist. // * @since 1.0 // */ // Entry get( String path ); // // /** // * Returns the time that the specified directory entry was last modified. Note: // * {@link DefaultDirectoryEntry#getLastModified()} delegates to this method. // * // * @param entry the directory entry. // * @return A <code>long</code> value representing the time the directory was // * last modified, measured in milliseconds since the epoch // * (00:00:00 GMT, January 1, 1970), or <code>0L</code> if the // * the time is unknown. // * @throws IOException if an I/O error occurs. // * @since 1.0 // */ // long getLastModified( DirectoryEntry entry ) // throws IOException; // // /** // * Makes the specified child directory. // * // * @param parent the directory in which the child is to be created. // * @param name the name of the child directory. // * @return the child directory entry. // * @throws UnsupportedOperationException if the repository is read-only. // * @since 1.0 // */ // DirectoryEntry mkdir( DirectoryEntry parent, String name ); // // /** // * Puts the specified content into a the specified directory. // * // * @param parent the directory in which the content is to be created/updated. // * @param name the name of the file. // * @param content the content (implementer is responsible for closing). // * @return the {@link FileEntry} that was created/updated. // * @throws UnsupportedOperationException if the repository is read-only. // * @throws java.io.IOException if the content could not be read/written. // * @since 1.0 // */ // FileEntry put( DirectoryEntry parent, String name, InputStream content ) // throws IOException; // // /** // * Puts the specified content into a the specified directory. // * // * @param parent the directory in which the content is to be created/updated. // * @param name the name of the file. // * @param content the content. // * @return the {@link FileEntry} that was created/updated. // * @throws UnsupportedOperationException if the repository is read-only. // * @throws java.io.IOException if the content could not be read/written. // * @since 1.0 // */ // FileEntry put( DirectoryEntry parent, String name, byte[] content ) // throws IOException; // // /** // * Removes the specified entry (and if the entry is a directory, all its children). // * // * @param entry the entry to remove. // * @throws UnsupportedOperationException if the repository is read-only. // * @since 1.0 // */ // void remove( Entry entry ); // }
import org.codehaus.mojo.mrm.api.FileSystem;
/* * Copyright 2011 Stephen Connolly * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.mojo.mrm.plugin; /** * Something that produces new {@link FileSystem} instances. * * @see FactoryHelperRequired * @since 1.0 */ public interface FileSystemFactory { /** * Creates a new {@link FileSystem} instance, note that implementations are free to create a singleton and always * return that instance. * * @return the {@link FileSystem} instance. * @since 1.0 */
// Path: mrm-api/src/main/java/org/codehaus/mojo/mrm/api/FileSystem.java // public interface FileSystem // extends Serializable // { // /** // * Lists the entries in the specified directory. Some implementations may be lazy caching // * implementations, in which case it is permitted to return either an empty array, or only those entries which // * have been loaded into the cache, so consumers should not assume that a missing entry implies non-existence. // * The only way to be sure that an artifact does not exist is to call the {@link FileEntry#getInputStream()} method, // * although {@link #get(String)} returning <code>null</code> is also definitive, a non-null does not prove // * existence). // * // * @param directory the directory to list the entries of. // * @return a copy of the known entries in the specified directory, never <code>null</code>. The caller can safely // * modify the returned array. // * @since 1.0 // */ // Entry[] listEntries( DirectoryEntry directory ); // // /** // * Returns the root directory entry. // * // * @return the root directory entry. // * @since 1.0 // */ // DirectoryEntry getRoot(); // // /** // * Returns the entry at the specified path. A <code>null</code> result proves the path does not exist, however // * very lazy caching implementations may return a non-null entry for paths which do not exist. // * // * @param path the path to retrieve the {@link Entry} of. // * @return the {@link Entry} or <code>null</code> if the path definitely does not exist. // * @since 1.0 // */ // Entry get( String path ); // // /** // * Returns the time that the specified directory entry was last modified. Note: // * {@link DefaultDirectoryEntry#getLastModified()} delegates to this method. // * // * @param entry the directory entry. // * @return A <code>long</code> value representing the time the directory was // * last modified, measured in milliseconds since the epoch // * (00:00:00 GMT, January 1, 1970), or <code>0L</code> if the // * the time is unknown. // * @throws IOException if an I/O error occurs. // * @since 1.0 // */ // long getLastModified( DirectoryEntry entry ) // throws IOException; // // /** // * Makes the specified child directory. // * // * @param parent the directory in which the child is to be created. // * @param name the name of the child directory. // * @return the child directory entry. // * @throws UnsupportedOperationException if the repository is read-only. // * @since 1.0 // */ // DirectoryEntry mkdir( DirectoryEntry parent, String name ); // // /** // * Puts the specified content into a the specified directory. // * // * @param parent the directory in which the content is to be created/updated. // * @param name the name of the file. // * @param content the content (implementer is responsible for closing). // * @return the {@link FileEntry} that was created/updated. // * @throws UnsupportedOperationException if the repository is read-only. // * @throws java.io.IOException if the content could not be read/written. // * @since 1.0 // */ // FileEntry put( DirectoryEntry parent, String name, InputStream content ) // throws IOException; // // /** // * Puts the specified content into a the specified directory. // * // * @param parent the directory in which the content is to be created/updated. // * @param name the name of the file. // * @param content the content. // * @return the {@link FileEntry} that was created/updated. // * @throws UnsupportedOperationException if the repository is read-only. // * @throws java.io.IOException if the content could not be read/written. // * @since 1.0 // */ // FileEntry put( DirectoryEntry parent, String name, byte[] content ) // throws IOException; // // /** // * Removes the specified entry (and if the entry is a directory, all its children). // * // * @param entry the entry to remove. // * @throws UnsupportedOperationException if the repository is read-only. // * @since 1.0 // */ // void remove( Entry entry ); // } // Path: mrm-api/src/main/java/org/codehaus/mojo/mrm/plugin/FileSystemFactory.java import org.codehaus.mojo.mrm.api.FileSystem; /* * Copyright 2011 Stephen Connolly * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.mojo.mrm.plugin; /** * Something that produces new {@link FileSystem} instances. * * @see FactoryHelperRequired * @since 1.0 */ public interface FileSystemFactory { /** * Creates a new {@link FileSystem} instance, note that implementations are free to create a singleton and always * return that instance. * * @return the {@link FileSystem} instance. * @since 1.0 */
FileSystem newInstance();
GamingMesh/Jobs
src/main/java/com/gamingmesh/jobs/dao/JobsDAOMySQL.java
// Path: src/main/java/com/gamingmesh/jobs/util/UUIDFetcher.java // public class UUIDFetcher implements Callable<Map<String, UUID>> { // private static final double PROFILES_PER_REQUEST = 100; // private static final String PROFILE_URL = "https://api.mojang.com/profiles/minecraft"; // private final JSONParser jsonParser = new JSONParser(); // private final List<String> names; // private final boolean rateLimiting; // // public UUIDFetcher(List<String> names, boolean rateLimiting) { // this.names = ImmutableList.copyOf(names); // this.rateLimiting = rateLimiting; // } // // public UUIDFetcher(List<String> names) { // this(names, true); // } // // public Map<String, UUID> call() throws Exception { // Map<String, UUID> uuidMap = new HashMap<String, UUID>(); // int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST); // for (int i = 0; i < requests; i++) { // HttpURLConnection connection = createConnection(); // String body = JSONArray.toJSONString(names.subList(i * 100, Math.min((i + 1) * 100, names.size()))); // writeBody(connection, body); // JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream())); // for (Object profile : array) { // JSONObject jsonProfile = (JSONObject) profile; // String id = (String) jsonProfile.get("id"); // String name = (String) jsonProfile.get("name"); // UUID uuid = UUIDFetcher.getUUID(id); // uuidMap.put(name, uuid); // } // if (rateLimiting && i != requests - 1) { // Thread.sleep(100L); // } // } // return uuidMap; // } // // private static void writeBody(HttpURLConnection connection, String body) throws Exception { // OutputStream stream = connection.getOutputStream(); // stream.write(body.getBytes()); // stream.flush(); // stream.close(); // } // // private static HttpURLConnection createConnection() throws Exception { // URL url = new URL(PROFILE_URL); // HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // connection.setRequestMethod("POST"); // connection.setRequestProperty("Content-Type", "application/json"); // connection.setUseCaches(false); // connection.setDoInput(true); // connection.setDoOutput(true); // return connection; // } // // private static UUID getUUID(String id) { // return UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" +id.substring(20, 32)); // } // // public static byte[] toBytes(UUID uuid) { // ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]); // byteBuffer.putLong(uuid.getMostSignificantBits()); // byteBuffer.putLong(uuid.getLeastSignificantBits()); // return byteBuffer.array(); // } // // public static UUID fromBytes(byte[] array) { // if (array.length != 16) { // throw new IllegalArgumentException("Illegal byte array length: " + array.length); // } // ByteBuffer byteBuffer = ByteBuffer.wrap(array); // long mostSignificant = byteBuffer.getLong(); // long leastSignificant = byteBuffer.getLong(); // return new UUID(mostSignificant, leastSignificant); // } // // public static UUID getUUIDOf(String name) throws Exception { // return new UUIDFetcher(Arrays.asList(name)).call().get(name); // } // } // // Path: src/main/java/com/gamingmesh/jobs/util/UUIDUtil.java // public class UUIDUtil { // public static byte[] toBytes(UUID uuid) { // ByteBuffer bb = ByteBuffer.allocate(16); // bb.putLong(uuid.getMostSignificantBits()); // bb.putLong(uuid.getLeastSignificantBits()); // return bb.array(); // } // // public static UUID fromBytes(byte[] array) { // ByteBuffer bb = ByteBuffer.wrap(array); // long most = bb.getLong(); // long least = bb.getLong(); // return new UUID(most, least); // } // }
import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Map; import java.util.UUID; import com.gamingmesh.jobs.Jobs; import com.gamingmesh.jobs.util.UUIDFetcher; import com.gamingmesh.jobs.util.UUIDUtil;
prest.setString(2, getPrefix()+"jobs"); ResultSet res = prest.executeQuery(); if (res.next()) { rows = res.getInt(1); } } finally { if (prest != null) { try { prest.close(); } catch (SQLException e) {} } } PreparedStatement pst1 = null; PreparedStatement pst2 = null; try { if (rows == 0) { executeSQL("CREATE TABLE `" + getPrefix() + "jobs` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `player_uuid` binary(16) NOT NULL, `username` varchar(20), `job` varchar(20), `experience` int, `level` int);"); } else { Jobs.getPluginLogger().info("Converting existing usernames to Mojang UUIDs. This could take a long time!"); executeSQL("ALTER TABLE `" + getPrefix() + "jobs` ADD COLUMN `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;"); executeSQL("ALTER TABLE `" + getPrefix() + "jobs` ADD COLUMN `player_uuid` binary(16) DEFAULT NULL AFTER `id`;"); pst1 = conn.prepareStatement("SELECT DISTINCT `username` FROM `" + getPrefix() + "jobs` WHERE `player_uuid` IS NULL;"); ResultSet rs = pst1.executeQuery(); ArrayList<String> usernames = new ArrayList<String>(); while (rs.next()) { usernames.add(rs.getString(1)); }
// Path: src/main/java/com/gamingmesh/jobs/util/UUIDFetcher.java // public class UUIDFetcher implements Callable<Map<String, UUID>> { // private static final double PROFILES_PER_REQUEST = 100; // private static final String PROFILE_URL = "https://api.mojang.com/profiles/minecraft"; // private final JSONParser jsonParser = new JSONParser(); // private final List<String> names; // private final boolean rateLimiting; // // public UUIDFetcher(List<String> names, boolean rateLimiting) { // this.names = ImmutableList.copyOf(names); // this.rateLimiting = rateLimiting; // } // // public UUIDFetcher(List<String> names) { // this(names, true); // } // // public Map<String, UUID> call() throws Exception { // Map<String, UUID> uuidMap = new HashMap<String, UUID>(); // int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST); // for (int i = 0; i < requests; i++) { // HttpURLConnection connection = createConnection(); // String body = JSONArray.toJSONString(names.subList(i * 100, Math.min((i + 1) * 100, names.size()))); // writeBody(connection, body); // JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream())); // for (Object profile : array) { // JSONObject jsonProfile = (JSONObject) profile; // String id = (String) jsonProfile.get("id"); // String name = (String) jsonProfile.get("name"); // UUID uuid = UUIDFetcher.getUUID(id); // uuidMap.put(name, uuid); // } // if (rateLimiting && i != requests - 1) { // Thread.sleep(100L); // } // } // return uuidMap; // } // // private static void writeBody(HttpURLConnection connection, String body) throws Exception { // OutputStream stream = connection.getOutputStream(); // stream.write(body.getBytes()); // stream.flush(); // stream.close(); // } // // private static HttpURLConnection createConnection() throws Exception { // URL url = new URL(PROFILE_URL); // HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // connection.setRequestMethod("POST"); // connection.setRequestProperty("Content-Type", "application/json"); // connection.setUseCaches(false); // connection.setDoInput(true); // connection.setDoOutput(true); // return connection; // } // // private static UUID getUUID(String id) { // return UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" +id.substring(20, 32)); // } // // public static byte[] toBytes(UUID uuid) { // ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]); // byteBuffer.putLong(uuid.getMostSignificantBits()); // byteBuffer.putLong(uuid.getLeastSignificantBits()); // return byteBuffer.array(); // } // // public static UUID fromBytes(byte[] array) { // if (array.length != 16) { // throw new IllegalArgumentException("Illegal byte array length: " + array.length); // } // ByteBuffer byteBuffer = ByteBuffer.wrap(array); // long mostSignificant = byteBuffer.getLong(); // long leastSignificant = byteBuffer.getLong(); // return new UUID(mostSignificant, leastSignificant); // } // // public static UUID getUUIDOf(String name) throws Exception { // return new UUIDFetcher(Arrays.asList(name)).call().get(name); // } // } // // Path: src/main/java/com/gamingmesh/jobs/util/UUIDUtil.java // public class UUIDUtil { // public static byte[] toBytes(UUID uuid) { // ByteBuffer bb = ByteBuffer.allocate(16); // bb.putLong(uuid.getMostSignificantBits()); // bb.putLong(uuid.getLeastSignificantBits()); // return bb.array(); // } // // public static UUID fromBytes(byte[] array) { // ByteBuffer bb = ByteBuffer.wrap(array); // long most = bb.getLong(); // long least = bb.getLong(); // return new UUID(most, least); // } // } // Path: src/main/java/com/gamingmesh/jobs/dao/JobsDAOMySQL.java import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Map; import java.util.UUID; import com.gamingmesh.jobs.Jobs; import com.gamingmesh.jobs.util.UUIDFetcher; import com.gamingmesh.jobs.util.UUIDUtil; prest.setString(2, getPrefix()+"jobs"); ResultSet res = prest.executeQuery(); if (res.next()) { rows = res.getInt(1); } } finally { if (prest != null) { try { prest.close(); } catch (SQLException e) {} } } PreparedStatement pst1 = null; PreparedStatement pst2 = null; try { if (rows == 0) { executeSQL("CREATE TABLE `" + getPrefix() + "jobs` (`id` int NOT NULL AUTO_INCREMENT PRIMARY KEY, `player_uuid` binary(16) NOT NULL, `username` varchar(20), `job` varchar(20), `experience` int, `level` int);"); } else { Jobs.getPluginLogger().info("Converting existing usernames to Mojang UUIDs. This could take a long time!"); executeSQL("ALTER TABLE `" + getPrefix() + "jobs` ADD COLUMN `id` int NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;"); executeSQL("ALTER TABLE `" + getPrefix() + "jobs` ADD COLUMN `player_uuid` binary(16) DEFAULT NULL AFTER `id`;"); pst1 = conn.prepareStatement("SELECT DISTINCT `username` FROM `" + getPrefix() + "jobs` WHERE `player_uuid` IS NULL;"); ResultSet rs = pst1.executeQuery(); ArrayList<String> usernames = new ArrayList<String>(); while (rs.next()) { usernames.add(rs.getString(1)); }
UUIDFetcher uuidFetcher = new UUIDFetcher(usernames);
GamingMesh/Jobs
src/main/java/com/gamingmesh/jobs/container/Title.java
// Path: src/main/java/com/gamingmesh/jobs/util/ChatColor.java // public enum ChatColor { // BLACK('0', 0), // DARK_BLUE('1', 1), // DARK_GREEN('2', 2), // DARK_AQUA('3', 3), // DARK_RED('4', 4), // DARK_PURPLE('5', 5), // GOLD('6', 6), // GRAY('7', 7), // DARK_GRAY('8', 8), // BLUE('9', 9), // GREEN('a', 10), // AQUA('b', 11), // RED('c', 12), // LIGHT_PURPLE('d', 13), // YELLOW('e', 14), // WHITE('f', 15); // // private static final char COLOR_CHAR = '\u00A7'; // private final char code; // private final int intCode; // private final String toString; // private final static Map<Integer, ChatColor> intMap = new HashMap<Integer, ChatColor>(); // private final static Map<Character, ChatColor> charMap = new HashMap<Character, ChatColor>(); // private final static Map<String, ChatColor> stringMap = new HashMap<String, ChatColor>(); // // private ChatColor(char code, int intCode) { // this.code = code; // this.intCode = intCode; // this.toString = new String(new char[] { COLOR_CHAR, code }); // } // // public char getChar() { // return code; // } // // @Override // public String toString() { // return toString; // } // // public static ChatColor matchColor(char code) { // return charMap.get(code); // } // // public static ChatColor matchColor(int code) { // return intMap.get(code); // } // // public static ChatColor matchColor(String name) { // return stringMap.get(name.toLowerCase()); // } // // static { // for (ChatColor color : values()) { // intMap.put(color.intCode, color); // charMap.put(color.code, color); // stringMap.put(color.name().toLowerCase(), color); // } // } // }
import com.gamingmesh.jobs.util.ChatColor;
/** * Jobs Plugin for Bukkit * Copyright (C) 2011 Zak Ford <zak.j.ford@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.gamingmesh.jobs.container; /** * Container class for titles * @author Alex * */ public class Title { private String name = null; private String shortName = null;
// Path: src/main/java/com/gamingmesh/jobs/util/ChatColor.java // public enum ChatColor { // BLACK('0', 0), // DARK_BLUE('1', 1), // DARK_GREEN('2', 2), // DARK_AQUA('3', 3), // DARK_RED('4', 4), // DARK_PURPLE('5', 5), // GOLD('6', 6), // GRAY('7', 7), // DARK_GRAY('8', 8), // BLUE('9', 9), // GREEN('a', 10), // AQUA('b', 11), // RED('c', 12), // LIGHT_PURPLE('d', 13), // YELLOW('e', 14), // WHITE('f', 15); // // private static final char COLOR_CHAR = '\u00A7'; // private final char code; // private final int intCode; // private final String toString; // private final static Map<Integer, ChatColor> intMap = new HashMap<Integer, ChatColor>(); // private final static Map<Character, ChatColor> charMap = new HashMap<Character, ChatColor>(); // private final static Map<String, ChatColor> stringMap = new HashMap<String, ChatColor>(); // // private ChatColor(char code, int intCode) { // this.code = code; // this.intCode = intCode; // this.toString = new String(new char[] { COLOR_CHAR, code }); // } // // public char getChar() { // return code; // } // // @Override // public String toString() { // return toString; // } // // public static ChatColor matchColor(char code) { // return charMap.get(code); // } // // public static ChatColor matchColor(int code) { // return intMap.get(code); // } // // public static ChatColor matchColor(String name) { // return stringMap.get(name.toLowerCase()); // } // // static { // for (ChatColor color : values()) { // intMap.put(color.intCode, color); // charMap.put(color.code, color); // stringMap.put(color.name().toLowerCase(), color); // } // } // } // Path: src/main/java/com/gamingmesh/jobs/container/Title.java import com.gamingmesh.jobs.util.ChatColor; /** * Jobs Plugin for Bukkit * Copyright (C) 2011 Zak Ford <zak.j.ford@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.gamingmesh.jobs.container; /** * Container class for titles * @author Alex * */ public class Title { private String name = null; private String shortName = null;
private ChatColor color = null;
GamingMesh/Jobs
src/main/java/com/gamingmesh/jobs/tasks/BufferedPaymentTask.java
// Path: src/main/java/com/gamingmesh/jobs/economy/Economy.java // public interface Economy { // public boolean depositPlayer(OfflinePlayer offlinePlayer, double money); // public boolean withdrawPlayer(OfflinePlayer offlinePlayer, double money); // public String format(double money); // }
import com.gamingmesh.jobs.economy.BufferedEconomy; import com.gamingmesh.jobs.economy.BufferedPayment; import com.gamingmesh.jobs.economy.Economy;
/** * Jobs Plugin for Bukkit * Copyright (C) 2011 Zak Ford <zak.j.ford@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.gamingmesh.jobs.tasks; public class BufferedPaymentTask implements Runnable { private BufferedEconomy bufferedEconomy;
// Path: src/main/java/com/gamingmesh/jobs/economy/Economy.java // public interface Economy { // public boolean depositPlayer(OfflinePlayer offlinePlayer, double money); // public boolean withdrawPlayer(OfflinePlayer offlinePlayer, double money); // public String format(double money); // } // Path: src/main/java/com/gamingmesh/jobs/tasks/BufferedPaymentTask.java import com.gamingmesh.jobs.economy.BufferedEconomy; import com.gamingmesh.jobs.economy.BufferedPayment; import com.gamingmesh.jobs.economy.Economy; /** * Jobs Plugin for Bukkit * Copyright (C) 2011 Zak Ford <zak.j.ford@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.gamingmesh.jobs.tasks; public class BufferedPaymentTask implements Runnable { private BufferedEconomy bufferedEconomy;
private Economy economy;
FRC2832/Robot_2016
src/org/usfirst/frc2832/Robot_2016/commands/ClimbStop.java
// Path: src/org/usfirst/frc2832/Robot_2016/Climber.java // public class Climber extends Subsystem { // // static CANTalon climbingWinch; //the motor that actually drives the climber // static Servo release; //the servo that latches onto the gear and holds it in one direction when actually climbing // static Servo motorLatch; // static double releaseHoldAngle = 0; //the angle the release servo is for the duration of match // static double releaseLetGoAngle = 0.5; //the angle the release servo is for letting go when about to climb // static double motorLatchNotTouchingAngle = 0; //the angle the latch is for the duration of the match // static double motorLatchTouchingAngle = 0.5; //the angle the latch is for touching the gear when actually moving up // static final double CLIMBER_UP_SPEED = 0.7; // static final double CLIMBER_DOWN_SPEED = -0.7; // static boolean isReleased = false; //this is true when the release servo is released // // @Override // protected void initDefaultCommand() { // // TODO Auto-generated method stub // // } // // public static void initialize(){ // climbingWinch = new CANTalon(8); //this value is guessed as of 3/21 // release = new Servo(2); //this value is guessed as of 3/21 // motorLatch = new Servo(3); //this value is guessed as of 3/21 // climbingWinch.changeControlMode(CANTalon.TalonControlMode.PercentVbus); // climbingWinch.enableBrakeMode(true); // } // // public static void releaseLatch() // { // motorLatch.set(motorLatchTouchingAngle); // } // // public static void resetLatch() // { // motorLatch.set(motorLatchNotTouchingAngle); // } // // public static void releaseRelease() // { // release.set(releaseLetGoAngle); // } // // public static void resetRelease() // { // release.set(releaseHoldAngle); // } // // public static void moveClimberUp() // { // climbingWinch.set(CLIMBER_UP_SPEED); // } // // public static void moveClimberDown() // { // climbingWinch.set(CLIMBER_DOWN_SPEED); // } // // public static void stopClimber() // { // climbingWinch.set(0.0); // } // // }
import org.usfirst.frc2832.Robot_2016.Climber; import edu.wpi.first.wpilibj.command.Command;
package org.usfirst.frc2832.Robot_2016.commands; public class ClimbStop extends Command { @Override protected void initialize() { // TODO Auto-generated method stub
// Path: src/org/usfirst/frc2832/Robot_2016/Climber.java // public class Climber extends Subsystem { // // static CANTalon climbingWinch; //the motor that actually drives the climber // static Servo release; //the servo that latches onto the gear and holds it in one direction when actually climbing // static Servo motorLatch; // static double releaseHoldAngle = 0; //the angle the release servo is for the duration of match // static double releaseLetGoAngle = 0.5; //the angle the release servo is for letting go when about to climb // static double motorLatchNotTouchingAngle = 0; //the angle the latch is for the duration of the match // static double motorLatchTouchingAngle = 0.5; //the angle the latch is for touching the gear when actually moving up // static final double CLIMBER_UP_SPEED = 0.7; // static final double CLIMBER_DOWN_SPEED = -0.7; // static boolean isReleased = false; //this is true when the release servo is released // // @Override // protected void initDefaultCommand() { // // TODO Auto-generated method stub // // } // // public static void initialize(){ // climbingWinch = new CANTalon(8); //this value is guessed as of 3/21 // release = new Servo(2); //this value is guessed as of 3/21 // motorLatch = new Servo(3); //this value is guessed as of 3/21 // climbingWinch.changeControlMode(CANTalon.TalonControlMode.PercentVbus); // climbingWinch.enableBrakeMode(true); // } // // public static void releaseLatch() // { // motorLatch.set(motorLatchTouchingAngle); // } // // public static void resetLatch() // { // motorLatch.set(motorLatchNotTouchingAngle); // } // // public static void releaseRelease() // { // release.set(releaseLetGoAngle); // } // // public static void resetRelease() // { // release.set(releaseHoldAngle); // } // // public static void moveClimberUp() // { // climbingWinch.set(CLIMBER_UP_SPEED); // } // // public static void moveClimberDown() // { // climbingWinch.set(CLIMBER_DOWN_SPEED); // } // // public static void stopClimber() // { // climbingWinch.set(0.0); // } // // } // Path: src/org/usfirst/frc2832/Robot_2016/commands/ClimbStop.java import org.usfirst.frc2832.Robot_2016.Climber; import edu.wpi.first.wpilibj.command.Command; package org.usfirst.frc2832.Robot_2016.commands; public class ClimbStop extends Command { @Override protected void initialize() { // TODO Auto-generated method stub
Climber.stopClimber();
FRC2832/Robot_2016
src/org/usfirst/frc2832/Robot_2016/commands/SmartRotate.java
// Path: src/org/usfirst/frc2832/Robot_2016/RobotMap.java // public class RobotMap { // // public static CANTalon frontLeftMotor; // public static CANTalon frontRightMotor; // public static CANTalon backLeftMotor; // public static CANTalon backRightMotor; // // public static CANTalon winchMotor; // // public static CANTalon ballIngestLeft; // public static CANTalon ballIngestRight; // // public static CANTalon tail; // // public static Relay lightRing; // // public static AnalogInput laser; // public static AnalogInput proxSensor; // // public static Servo kicker; // // public static RobotDrive driveTrain; // // public static IMUAdvanced imu; // // private static AnalogGyro gyro; // public static DeltaPID gyroPID; // // public static final double ENCODER_PULSE_PER_METER = 2800; // // // // public static void init() { // // // Doug MacKenzie: Switch from CANTalonLoggable back to CANTalon to remove the logging thread // // Trying to fix very high CPU utilization on the roboRIO that is causing lagging. // // frontLeftMotor = new CANTalonLoggable(1); // frontLeftMotor = new CANTalon(1); // LiveWindow.addActuator("Drivetrain", "frontLeft", frontLeftMotor); // // // frontRightMotor = new CANTalonLoggable(3); // frontRightMotor = new CANTalon(3); // LiveWindow.addActuator("Drivetrain", "frontRight", frontRightMotor); // // //the following code sets the back motors as slaves/followers to the front // // backLeftMotor = new CANTalonLoggable(2); // backLeftMotor = new CANTalon(2); // backLeftMotor.changeControlMode(CANTalon.TalonControlMode.Follower); // backLeftMotor.set(1); // // backRightMotor = new CANTalonLoggable(4); // backRightMotor = new CANTalon(4); // backRightMotor.changeControlMode(CANTalon.TalonControlMode.Follower); // backRightMotor.set(3); // // driveTrain = new RobotDrive(frontLeftMotor, frontRightMotor); // // driveTrain.setSafetyEnabled(true); // driveTrain.setExpiration(0.1); // driveTrain.setSensitivity(0.5); // driveTrain.setMaxOutput(1.0); // // frontLeftMotor.enableBrakeMode(true); // frontRightMotor.enableBrakeMode(true); // backLeftMotor.enableBrakeMode(true); // backRightMotor.enableBrakeMode(true); // // // Doug MacKenzie : Attempt to reproduce the code added by Brendan to reduce current usage by the drive train. // // Removed brownout problems // frontLeftMotor.setVoltageRampRate( 41 ); // frontRightMotor.setVoltageRampRate( 41 ); // backLeftMotor.setVoltageRampRate( 41 ); // backRightMotor.setVoltageRampRate( 41 ); // // // frontLeftMotor.setInverted(true); // frontRightMotor.setInverted(true); // // winchMotor = new CANTalonCurrentSafety(7); // winchMotor.enableBrakeMode(false); // winchMotor.configPeakOutputVoltage(12, -12); // winchMotor.enableLimitSwitch(true, true); // // winchMotor.setInverted(false); // winchMotor.reverseOutput(false); // // ballIngestLeft = new CANTalon(5); // LiveWindow.addActuator("Ball Handler", "ingestLeft",ballIngestLeft); // ballIngestRight = new CANTalon(6); // LiveWindow.addActuator("Ball Handler", "ingestRight", ballIngestRight); // // ballIngestLeft.setInverted(true); // ballIngestRight.setInverted(true); // // //tail = new CANTalon(21); // TODO: Might have to change. // //tail.changeControlMode(CANTalon.TalonControlMode.Speed); // //tail.enableLimitSwitch(true, true); // //tail.setInverted(false);//Use this to switch up and down // // // laser = new AnalogInput(0); // proxSensor = new AnalogInput(1); // kicker = new Servo(1); // // kicker.setPosition(Kicker.NEUTRAL_ANGLE); // // byte update_rate_hz = 50; // imu = new IMUAdvanced(new SerialPort(57600,SerialPort.Port.kMXP), update_rate_hz); // // try // { // gyro = new AnalogGyro(2); // } // catch (Exception e) // { // //e.printStackTrace(); // } // // lightRing = new Relay(0); // lightRing.set(Relay.Value.kOff); // } // }
import org.usfirst.frc2832.Robot_2016.RobotMap; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
package org.usfirst.frc2832.Robot_2016.commands; /** * */ public class SmartRotate extends Command { private static double MAX_OUTPUT=0.8; private static double MIN_OUTPUT=0.5; private static double MAX_INPUT=30; private static double MIN_INPUT=1; private static final int TIMEOUT = 5000; private double theta; private boolean finished; private int zeroCount; public SmartRotate(double angle) { theta = angle; } // Called just before this Command runs the first time protected void initialize() { finished = false;
// Path: src/org/usfirst/frc2832/Robot_2016/RobotMap.java // public class RobotMap { // // public static CANTalon frontLeftMotor; // public static CANTalon frontRightMotor; // public static CANTalon backLeftMotor; // public static CANTalon backRightMotor; // // public static CANTalon winchMotor; // // public static CANTalon ballIngestLeft; // public static CANTalon ballIngestRight; // // public static CANTalon tail; // // public static Relay lightRing; // // public static AnalogInput laser; // public static AnalogInput proxSensor; // // public static Servo kicker; // // public static RobotDrive driveTrain; // // public static IMUAdvanced imu; // // private static AnalogGyro gyro; // public static DeltaPID gyroPID; // // public static final double ENCODER_PULSE_PER_METER = 2800; // // // // public static void init() { // // // Doug MacKenzie: Switch from CANTalonLoggable back to CANTalon to remove the logging thread // // Trying to fix very high CPU utilization on the roboRIO that is causing lagging. // // frontLeftMotor = new CANTalonLoggable(1); // frontLeftMotor = new CANTalon(1); // LiveWindow.addActuator("Drivetrain", "frontLeft", frontLeftMotor); // // // frontRightMotor = new CANTalonLoggable(3); // frontRightMotor = new CANTalon(3); // LiveWindow.addActuator("Drivetrain", "frontRight", frontRightMotor); // // //the following code sets the back motors as slaves/followers to the front // // backLeftMotor = new CANTalonLoggable(2); // backLeftMotor = new CANTalon(2); // backLeftMotor.changeControlMode(CANTalon.TalonControlMode.Follower); // backLeftMotor.set(1); // // backRightMotor = new CANTalonLoggable(4); // backRightMotor = new CANTalon(4); // backRightMotor.changeControlMode(CANTalon.TalonControlMode.Follower); // backRightMotor.set(3); // // driveTrain = new RobotDrive(frontLeftMotor, frontRightMotor); // // driveTrain.setSafetyEnabled(true); // driveTrain.setExpiration(0.1); // driveTrain.setSensitivity(0.5); // driveTrain.setMaxOutput(1.0); // // frontLeftMotor.enableBrakeMode(true); // frontRightMotor.enableBrakeMode(true); // backLeftMotor.enableBrakeMode(true); // backRightMotor.enableBrakeMode(true); // // // Doug MacKenzie : Attempt to reproduce the code added by Brendan to reduce current usage by the drive train. // // Removed brownout problems // frontLeftMotor.setVoltageRampRate( 41 ); // frontRightMotor.setVoltageRampRate( 41 ); // backLeftMotor.setVoltageRampRate( 41 ); // backRightMotor.setVoltageRampRate( 41 ); // // // frontLeftMotor.setInverted(true); // frontRightMotor.setInverted(true); // // winchMotor = new CANTalonCurrentSafety(7); // winchMotor.enableBrakeMode(false); // winchMotor.configPeakOutputVoltage(12, -12); // winchMotor.enableLimitSwitch(true, true); // // winchMotor.setInverted(false); // winchMotor.reverseOutput(false); // // ballIngestLeft = new CANTalon(5); // LiveWindow.addActuator("Ball Handler", "ingestLeft",ballIngestLeft); // ballIngestRight = new CANTalon(6); // LiveWindow.addActuator("Ball Handler", "ingestRight", ballIngestRight); // // ballIngestLeft.setInverted(true); // ballIngestRight.setInverted(true); // // //tail = new CANTalon(21); // TODO: Might have to change. // //tail.changeControlMode(CANTalon.TalonControlMode.Speed); // //tail.enableLimitSwitch(true, true); // //tail.setInverted(false);//Use this to switch up and down // // // laser = new AnalogInput(0); // proxSensor = new AnalogInput(1); // kicker = new Servo(1); // // kicker.setPosition(Kicker.NEUTRAL_ANGLE); // // byte update_rate_hz = 50; // imu = new IMUAdvanced(new SerialPort(57600,SerialPort.Port.kMXP), update_rate_hz); // // try // { // gyro = new AnalogGyro(2); // } // catch (Exception e) // { // //e.printStackTrace(); // } // // lightRing = new Relay(0); // lightRing.set(Relay.Value.kOff); // } // } // Path: src/org/usfirst/frc2832/Robot_2016/commands/SmartRotate.java import org.usfirst.frc2832.Robot_2016.RobotMap; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; package org.usfirst.frc2832.Robot_2016.commands; /** * */ public class SmartRotate extends Command { private static double MAX_OUTPUT=0.8; private static double MIN_OUTPUT=0.5; private static double MAX_INPUT=30; private static double MIN_INPUT=1; private static final int TIMEOUT = 5000; private double theta; private boolean finished; private int zeroCount; public SmartRotate(double angle) { theta = angle; } // Called just before this Command runs the first time protected void initialize() { finished = false;
RobotMap.imu.zeroYaw();
FRC2832/Robot_2016
src/org/usfirst/frc2832/Robot_2016/commands/ClimbUp.java
// Path: src/org/usfirst/frc2832/Robot_2016/Climber.java // public class Climber extends Subsystem { // // static CANTalon climbingWinch; //the motor that actually drives the climber // static Servo release; //the servo that latches onto the gear and holds it in one direction when actually climbing // static Servo motorLatch; // static double releaseHoldAngle = 0; //the angle the release servo is for the duration of match // static double releaseLetGoAngle = 0.5; //the angle the release servo is for letting go when about to climb // static double motorLatchNotTouchingAngle = 0; //the angle the latch is for the duration of the match // static double motorLatchTouchingAngle = 0.5; //the angle the latch is for touching the gear when actually moving up // static final double CLIMBER_UP_SPEED = 0.7; // static final double CLIMBER_DOWN_SPEED = -0.7; // static boolean isReleased = false; //this is true when the release servo is released // // @Override // protected void initDefaultCommand() { // // TODO Auto-generated method stub // // } // // public static void initialize(){ // climbingWinch = new CANTalon(8); //this value is guessed as of 3/21 // release = new Servo(2); //this value is guessed as of 3/21 // motorLatch = new Servo(3); //this value is guessed as of 3/21 // climbingWinch.changeControlMode(CANTalon.TalonControlMode.PercentVbus); // climbingWinch.enableBrakeMode(true); // } // // public static void releaseLatch() // { // motorLatch.set(motorLatchTouchingAngle); // } // // public static void resetLatch() // { // motorLatch.set(motorLatchNotTouchingAngle); // } // // public static void releaseRelease() // { // release.set(releaseLetGoAngle); // } // // public static void resetRelease() // { // release.set(releaseHoldAngle); // } // // public static void moveClimberUp() // { // climbingWinch.set(CLIMBER_UP_SPEED); // } // // public static void moveClimberDown() // { // climbingWinch.set(CLIMBER_DOWN_SPEED); // } // // public static void stopClimber() // { // climbingWinch.set(0.0); // } // // }
import org.usfirst.frc2832.Robot_2016.Climber; import edu.wpi.first.wpilibj.command.Command;
package org.usfirst.frc2832.Robot_2016.commands; public class ClimbUp extends Command { @Override protected void initialize() { // TODO Auto-generated method stub
// Path: src/org/usfirst/frc2832/Robot_2016/Climber.java // public class Climber extends Subsystem { // // static CANTalon climbingWinch; //the motor that actually drives the climber // static Servo release; //the servo that latches onto the gear and holds it in one direction when actually climbing // static Servo motorLatch; // static double releaseHoldAngle = 0; //the angle the release servo is for the duration of match // static double releaseLetGoAngle = 0.5; //the angle the release servo is for letting go when about to climb // static double motorLatchNotTouchingAngle = 0; //the angle the latch is for the duration of the match // static double motorLatchTouchingAngle = 0.5; //the angle the latch is for touching the gear when actually moving up // static final double CLIMBER_UP_SPEED = 0.7; // static final double CLIMBER_DOWN_SPEED = -0.7; // static boolean isReleased = false; //this is true when the release servo is released // // @Override // protected void initDefaultCommand() { // // TODO Auto-generated method stub // // } // // public static void initialize(){ // climbingWinch = new CANTalon(8); //this value is guessed as of 3/21 // release = new Servo(2); //this value is guessed as of 3/21 // motorLatch = new Servo(3); //this value is guessed as of 3/21 // climbingWinch.changeControlMode(CANTalon.TalonControlMode.PercentVbus); // climbingWinch.enableBrakeMode(true); // } // // public static void releaseLatch() // { // motorLatch.set(motorLatchTouchingAngle); // } // // public static void resetLatch() // { // motorLatch.set(motorLatchNotTouchingAngle); // } // // public static void releaseRelease() // { // release.set(releaseLetGoAngle); // } // // public static void resetRelease() // { // release.set(releaseHoldAngle); // } // // public static void moveClimberUp() // { // climbingWinch.set(CLIMBER_UP_SPEED); // } // // public static void moveClimberDown() // { // climbingWinch.set(CLIMBER_DOWN_SPEED); // } // // public static void stopClimber() // { // climbingWinch.set(0.0); // } // // } // Path: src/org/usfirst/frc2832/Robot_2016/commands/ClimbUp.java import org.usfirst.frc2832.Robot_2016.Climber; import edu.wpi.first.wpilibj.command.Command; package org.usfirst.frc2832.Robot_2016.commands; public class ClimbUp extends Command { @Override protected void initialize() { // TODO Auto-generated method stub
Climber.moveClimberUp();
FRC2832/Robot_2016
src/org/usfirst/frc2832/Robot_2016/commands/ClimbDown.java
// Path: src/org/usfirst/frc2832/Robot_2016/Climber.java // public class Climber extends Subsystem { // // static CANTalon climbingWinch; //the motor that actually drives the climber // static Servo release; //the servo that latches onto the gear and holds it in one direction when actually climbing // static Servo motorLatch; // static double releaseHoldAngle = 0; //the angle the release servo is for the duration of match // static double releaseLetGoAngle = 0.5; //the angle the release servo is for letting go when about to climb // static double motorLatchNotTouchingAngle = 0; //the angle the latch is for the duration of the match // static double motorLatchTouchingAngle = 0.5; //the angle the latch is for touching the gear when actually moving up // static final double CLIMBER_UP_SPEED = 0.7; // static final double CLIMBER_DOWN_SPEED = -0.7; // static boolean isReleased = false; //this is true when the release servo is released // // @Override // protected void initDefaultCommand() { // // TODO Auto-generated method stub // // } // // public static void initialize(){ // climbingWinch = new CANTalon(8); //this value is guessed as of 3/21 // release = new Servo(2); //this value is guessed as of 3/21 // motorLatch = new Servo(3); //this value is guessed as of 3/21 // climbingWinch.changeControlMode(CANTalon.TalonControlMode.PercentVbus); // climbingWinch.enableBrakeMode(true); // } // // public static void releaseLatch() // { // motorLatch.set(motorLatchTouchingAngle); // } // // public static void resetLatch() // { // motorLatch.set(motorLatchNotTouchingAngle); // } // // public static void releaseRelease() // { // release.set(releaseLetGoAngle); // } // // public static void resetRelease() // { // release.set(releaseHoldAngle); // } // // public static void moveClimberUp() // { // climbingWinch.set(CLIMBER_UP_SPEED); // } // // public static void moveClimberDown() // { // climbingWinch.set(CLIMBER_DOWN_SPEED); // } // // public static void stopClimber() // { // climbingWinch.set(0.0); // } // // }
import org.usfirst.frc2832.Robot_2016.Climber; import edu.wpi.first.wpilibj.command.Command;
package org.usfirst.frc2832.Robot_2016.commands; public class ClimbDown extends Command { @Override protected void initialize() { // TODO Auto-generated method stub
// Path: src/org/usfirst/frc2832/Robot_2016/Climber.java // public class Climber extends Subsystem { // // static CANTalon climbingWinch; //the motor that actually drives the climber // static Servo release; //the servo that latches onto the gear and holds it in one direction when actually climbing // static Servo motorLatch; // static double releaseHoldAngle = 0; //the angle the release servo is for the duration of match // static double releaseLetGoAngle = 0.5; //the angle the release servo is for letting go when about to climb // static double motorLatchNotTouchingAngle = 0; //the angle the latch is for the duration of the match // static double motorLatchTouchingAngle = 0.5; //the angle the latch is for touching the gear when actually moving up // static final double CLIMBER_UP_SPEED = 0.7; // static final double CLIMBER_DOWN_SPEED = -0.7; // static boolean isReleased = false; //this is true when the release servo is released // // @Override // protected void initDefaultCommand() { // // TODO Auto-generated method stub // // } // // public static void initialize(){ // climbingWinch = new CANTalon(8); //this value is guessed as of 3/21 // release = new Servo(2); //this value is guessed as of 3/21 // motorLatch = new Servo(3); //this value is guessed as of 3/21 // climbingWinch.changeControlMode(CANTalon.TalonControlMode.PercentVbus); // climbingWinch.enableBrakeMode(true); // } // // public static void releaseLatch() // { // motorLatch.set(motorLatchTouchingAngle); // } // // public static void resetLatch() // { // motorLatch.set(motorLatchNotTouchingAngle); // } // // public static void releaseRelease() // { // release.set(releaseLetGoAngle); // } // // public static void resetRelease() // { // release.set(releaseHoldAngle); // } // // public static void moveClimberUp() // { // climbingWinch.set(CLIMBER_UP_SPEED); // } // // public static void moveClimberDown() // { // climbingWinch.set(CLIMBER_DOWN_SPEED); // } // // public static void stopClimber() // { // climbingWinch.set(0.0); // } // // } // Path: src/org/usfirst/frc2832/Robot_2016/commands/ClimbDown.java import org.usfirst.frc2832.Robot_2016.Climber; import edu.wpi.first.wpilibj.command.Command; package org.usfirst.frc2832.Robot_2016.commands; public class ClimbDown extends Command { @Override protected void initialize() { // TODO Auto-generated method stub
Climber.moveClimberDown();
FRC2832/Robot_2016
src/org/usfirst/frc2832/Robot_2016/commands/LockClimber.java
// Path: src/org/usfirst/frc2832/Robot_2016/Climber.java // public class Climber extends Subsystem { // // static CANTalon climbingWinch; //the motor that actually drives the climber // static Servo release; //the servo that latches onto the gear and holds it in one direction when actually climbing // static Servo motorLatch; // static double releaseHoldAngle = 0; //the angle the release servo is for the duration of match // static double releaseLetGoAngle = 0.5; //the angle the release servo is for letting go when about to climb // static double motorLatchNotTouchingAngle = 0; //the angle the latch is for the duration of the match // static double motorLatchTouchingAngle = 0.5; //the angle the latch is for touching the gear when actually moving up // static final double CLIMBER_UP_SPEED = 0.7; // static final double CLIMBER_DOWN_SPEED = -0.7; // static boolean isReleased = false; //this is true when the release servo is released // // @Override // protected void initDefaultCommand() { // // TODO Auto-generated method stub // // } // // public static void initialize(){ // climbingWinch = new CANTalon(8); //this value is guessed as of 3/21 // release = new Servo(2); //this value is guessed as of 3/21 // motorLatch = new Servo(3); //this value is guessed as of 3/21 // climbingWinch.changeControlMode(CANTalon.TalonControlMode.PercentVbus); // climbingWinch.enableBrakeMode(true); // } // // public static void releaseLatch() // { // motorLatch.set(motorLatchTouchingAngle); // } // // public static void resetLatch() // { // motorLatch.set(motorLatchNotTouchingAngle); // } // // public static void releaseRelease() // { // release.set(releaseLetGoAngle); // } // // public static void resetRelease() // { // release.set(releaseHoldAngle); // } // // public static void moveClimberUp() // { // climbingWinch.set(CLIMBER_UP_SPEED); // } // // public static void moveClimberDown() // { // climbingWinch.set(CLIMBER_DOWN_SPEED); // } // // public static void stopClimber() // { // climbingWinch.set(0.0); // } // // }
import org.usfirst.frc2832.Robot_2016.Climber; import edu.wpi.first.wpilibj.command.Command;
package org.usfirst.frc2832.Robot_2016.commands; public class LockClimber extends Command { @Override protected void initialize() { // TODO Auto-generated method stub
// Path: src/org/usfirst/frc2832/Robot_2016/Climber.java // public class Climber extends Subsystem { // // static CANTalon climbingWinch; //the motor that actually drives the climber // static Servo release; //the servo that latches onto the gear and holds it in one direction when actually climbing // static Servo motorLatch; // static double releaseHoldAngle = 0; //the angle the release servo is for the duration of match // static double releaseLetGoAngle = 0.5; //the angle the release servo is for letting go when about to climb // static double motorLatchNotTouchingAngle = 0; //the angle the latch is for the duration of the match // static double motorLatchTouchingAngle = 0.5; //the angle the latch is for touching the gear when actually moving up // static final double CLIMBER_UP_SPEED = 0.7; // static final double CLIMBER_DOWN_SPEED = -0.7; // static boolean isReleased = false; //this is true when the release servo is released // // @Override // protected void initDefaultCommand() { // // TODO Auto-generated method stub // // } // // public static void initialize(){ // climbingWinch = new CANTalon(8); //this value is guessed as of 3/21 // release = new Servo(2); //this value is guessed as of 3/21 // motorLatch = new Servo(3); //this value is guessed as of 3/21 // climbingWinch.changeControlMode(CANTalon.TalonControlMode.PercentVbus); // climbingWinch.enableBrakeMode(true); // } // // public static void releaseLatch() // { // motorLatch.set(motorLatchTouchingAngle); // } // // public static void resetLatch() // { // motorLatch.set(motorLatchNotTouchingAngle); // } // // public static void releaseRelease() // { // release.set(releaseLetGoAngle); // } // // public static void resetRelease() // { // release.set(releaseHoldAngle); // } // // public static void moveClimberUp() // { // climbingWinch.set(CLIMBER_UP_SPEED); // } // // public static void moveClimberDown() // { // climbingWinch.set(CLIMBER_DOWN_SPEED); // } // // public static void stopClimber() // { // climbingWinch.set(0.0); // } // // } // Path: src/org/usfirst/frc2832/Robot_2016/commands/LockClimber.java import org.usfirst.frc2832.Robot_2016.Climber; import edu.wpi.first.wpilibj.command.Command; package org.usfirst.frc2832.Robot_2016.commands; public class LockClimber extends Command { @Override protected void initialize() { // TODO Auto-generated method stub
Climber.releaseLatch();
FRC2832/Robot_2016
src/org/usfirst/frc2832/Robot_2016/commands/ReleaseClimber.java
// Path: src/org/usfirst/frc2832/Robot_2016/Climber.java // public class Climber extends Subsystem { // // static CANTalon climbingWinch; //the motor that actually drives the climber // static Servo release; //the servo that latches onto the gear and holds it in one direction when actually climbing // static Servo motorLatch; // static double releaseHoldAngle = 0; //the angle the release servo is for the duration of match // static double releaseLetGoAngle = 0.5; //the angle the release servo is for letting go when about to climb // static double motorLatchNotTouchingAngle = 0; //the angle the latch is for the duration of the match // static double motorLatchTouchingAngle = 0.5; //the angle the latch is for touching the gear when actually moving up // static final double CLIMBER_UP_SPEED = 0.7; // static final double CLIMBER_DOWN_SPEED = -0.7; // static boolean isReleased = false; //this is true when the release servo is released // // @Override // protected void initDefaultCommand() { // // TODO Auto-generated method stub // // } // // public static void initialize(){ // climbingWinch = new CANTalon(8); //this value is guessed as of 3/21 // release = new Servo(2); //this value is guessed as of 3/21 // motorLatch = new Servo(3); //this value is guessed as of 3/21 // climbingWinch.changeControlMode(CANTalon.TalonControlMode.PercentVbus); // climbingWinch.enableBrakeMode(true); // } // // public static void releaseLatch() // { // motorLatch.set(motorLatchTouchingAngle); // } // // public static void resetLatch() // { // motorLatch.set(motorLatchNotTouchingAngle); // } // // public static void releaseRelease() // { // release.set(releaseLetGoAngle); // } // // public static void resetRelease() // { // release.set(releaseHoldAngle); // } // // public static void moveClimberUp() // { // climbingWinch.set(CLIMBER_UP_SPEED); // } // // public static void moveClimberDown() // { // climbingWinch.set(CLIMBER_DOWN_SPEED); // } // // public static void stopClimber() // { // climbingWinch.set(0.0); // } // // }
import org.usfirst.frc2832.Robot_2016.Climber; import edu.wpi.first.wpilibj.command.Command;
package org.usfirst.frc2832.Robot_2016.commands; public class ReleaseClimber extends Command { @Override protected void initialize() { // TODO Auto-generated method stub
// Path: src/org/usfirst/frc2832/Robot_2016/Climber.java // public class Climber extends Subsystem { // // static CANTalon climbingWinch; //the motor that actually drives the climber // static Servo release; //the servo that latches onto the gear and holds it in one direction when actually climbing // static Servo motorLatch; // static double releaseHoldAngle = 0; //the angle the release servo is for the duration of match // static double releaseLetGoAngle = 0.5; //the angle the release servo is for letting go when about to climb // static double motorLatchNotTouchingAngle = 0; //the angle the latch is for the duration of the match // static double motorLatchTouchingAngle = 0.5; //the angle the latch is for touching the gear when actually moving up // static final double CLIMBER_UP_SPEED = 0.7; // static final double CLIMBER_DOWN_SPEED = -0.7; // static boolean isReleased = false; //this is true when the release servo is released // // @Override // protected void initDefaultCommand() { // // TODO Auto-generated method stub // // } // // public static void initialize(){ // climbingWinch = new CANTalon(8); //this value is guessed as of 3/21 // release = new Servo(2); //this value is guessed as of 3/21 // motorLatch = new Servo(3); //this value is guessed as of 3/21 // climbingWinch.changeControlMode(CANTalon.TalonControlMode.PercentVbus); // climbingWinch.enableBrakeMode(true); // } // // public static void releaseLatch() // { // motorLatch.set(motorLatchTouchingAngle); // } // // public static void resetLatch() // { // motorLatch.set(motorLatchNotTouchingAngle); // } // // public static void releaseRelease() // { // release.set(releaseLetGoAngle); // } // // public static void resetRelease() // { // release.set(releaseHoldAngle); // } // // public static void moveClimberUp() // { // climbingWinch.set(CLIMBER_UP_SPEED); // } // // public static void moveClimberDown() // { // climbingWinch.set(CLIMBER_DOWN_SPEED); // } // // public static void stopClimber() // { // climbingWinch.set(0.0); // } // // } // Path: src/org/usfirst/frc2832/Robot_2016/commands/ReleaseClimber.java import org.usfirst.frc2832.Robot_2016.Climber; import edu.wpi.first.wpilibj.command.Command; package org.usfirst.frc2832.Robot_2016.commands; public class ReleaseClimber extends Command { @Override protected void initialize() { // TODO Auto-generated method stub
Climber.releaseRelease();
FRC2832/Robot_2016
src/org/usfirst/frc2832/Robot_2016/HID/GamepadDeadzoned.java
// Path: src/org/usfirst/frc2832/Robot_2016/Coordinate.java // public class Coordinate // { // private final double x, y; // // public Coordinate(double x, double y) // { // this.x = x; // this.y = y; // } // // public double getX() // { // return x; // } // // public double getY() // { // return y; // } // }
import org.usfirst.frc2832.Robot_2016.Coordinate; import edu.wpi.first.wpilibj.Joystick;
package org.usfirst.frc2832.Robot_2016.HID; public class GamepadDeadzoned extends Joystick { private double range = 0.15; private int[] leftstickAxis = {0, 1}; private int[] rightstickAxis = {4, 5}; public GamepadDeadzoned(int port) { super(port); } private double deadzone(double in) { return Math.abs(in) < range ? 0 : in; } private static boolean arrContains(int[] arr, int x) { for(int a : arr) { if (a == x) return true; } return false; } /** * Use getRawAxis with your axis ID instead of this method * 0 and 1 for left stick * 2 and 3 for triggers * 4 and 5 for right stick */ @Deprecated @Override public double getAxis(AxisType axis) { return getRawAxis(axis.value); } /** * Radial deadzoning helper method * @param x * @param y * @return */
// Path: src/org/usfirst/frc2832/Robot_2016/Coordinate.java // public class Coordinate // { // private final double x, y; // // public Coordinate(double x, double y) // { // this.x = x; // this.y = y; // } // // public double getX() // { // return x; // } // // public double getY() // { // return y; // } // } // Path: src/org/usfirst/frc2832/Robot_2016/HID/GamepadDeadzoned.java import org.usfirst.frc2832.Robot_2016.Coordinate; import edu.wpi.first.wpilibj.Joystick; package org.usfirst.frc2832.Robot_2016.HID; public class GamepadDeadzoned extends Joystick { private double range = 0.15; private int[] leftstickAxis = {0, 1}; private int[] rightstickAxis = {4, 5}; public GamepadDeadzoned(int port) { super(port); } private double deadzone(double in) { return Math.abs(in) < range ? 0 : in; } private static boolean arrContains(int[] arr, int x) { for(int a : arr) { if (a == x) return true; } return false; } /** * Use getRawAxis with your axis ID instead of this method * 0 and 1 for left stick * 2 and 3 for triggers * 4 and 5 for right stick */ @Deprecated @Override public double getAxis(AxisType axis) { return getRawAxis(axis.value); } /** * Radial deadzoning helper method * @param x * @param y * @return */
private Coordinate deadzone2D(double x, double y) {
erning/myrrix-recommender
online/src/net/myrrix/online/MostPopularItemsIterator.java
// Path: common/src/net/myrrix/common/LangUtils.java // public final class LangUtils { // // private LangUtils() { // } // // /** // * Parses a {@code float} from a {@link String} as if by {@link Float#valueOf(String)}, but disallows special // * values like {@link Float#NaN}, {@link Float#POSITIVE_INFINITY} and {@link Float#NEGATIVE_INFINITY}. // * // * @param s {@link String} to parse // * @return floating-point value in the {@link String} // * @throws NumberFormatException if input does not parse as a floating-point value // * @throws IllegalArgumentException if input is infinite or {@link Float#NaN} // * @see #parseDouble(String) // */ // public static float parseFloat(String s) { // float value = Float.parseFloat(s); // Preconditions.checkArgument(isFinite(value), "Bad value: %s", value); // return value; // } // // /** // * @return true if argument is not {@link Float#NaN}, {@link Float#POSITIVE_INFINITY} or // * {@link Float#NEGATIVE_INFINITY} // */ // public static boolean isFinite(float f) { // return !(Float.isNaN(f) || Float.isInfinite(f)); // } // // /** // * @see #parseFloat(String) // */ // public static double parseDouble(String s) { // double value = Double.parseDouble(s); // Preconditions.checkArgument(isFinite(value), "Bad value: %s", value); // return value; // } // // /** // * @return true if argument is not {@link Double#NaN}, {@link Double#POSITIVE_INFINITY} or // * {@link Double#NEGATIVE_INFINITY} // */ // public static boolean isFinite(double d) { // return !(Double.isNaN(d) || Double.isInfinite(d)); // } // // // /** // * Computes {@code l mod m}, such that the result is always in [0,m-1], for any {@code long} // * value including negative values. // * // * @param l long value // * @param m modulus // * @return {@code l mod m} if l is nonnegative, {@code (l mod m) + m} otherwise // */ // public static int mod(long l, int m) { // return ((int) (l % m) + m) % m; // } // // }
import java.util.Iterator; import org.apache.mahout.cf.taste.recommender.IDRescorer; import org.apache.mahout.cf.taste.recommender.RecommendedItem; import net.myrrix.common.LangUtils; import net.myrrix.common.MutableRecommendedItem; import net.myrrix.common.collection.FastByIDFloatMap;
/* * Copyright Myrrix Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.myrrix.online; /** * Used by {@link net.myrrix.common.MyrrixRecommender#mostPopularItems(int)}. * * @author Sean Owen */ final class MostPopularItemsIterator implements Iterator<RecommendedItem> { private final MutableRecommendedItem delegate; private final Iterator<FastByIDFloatMap.MapEntry> countsIterator; private final IDRescorer rescorer; MostPopularItemsIterator(Iterator<FastByIDFloatMap.MapEntry> countsIterator, IDRescorer rescorer) { delegate = new MutableRecommendedItem(); this.countsIterator = countsIterator; this.rescorer = rescorer; } @Override public boolean hasNext() { return countsIterator.hasNext(); } @Override public RecommendedItem next() { FastByIDFloatMap.MapEntry entry = countsIterator.next(); long id = entry.getKey(); float value = entry.getValue(); IDRescorer theRescorer = rescorer; if (theRescorer != null) { if (theRescorer.isFiltered(id)) { return null; } value = (float) theRescorer.rescore(id, value);
// Path: common/src/net/myrrix/common/LangUtils.java // public final class LangUtils { // // private LangUtils() { // } // // /** // * Parses a {@code float} from a {@link String} as if by {@link Float#valueOf(String)}, but disallows special // * values like {@link Float#NaN}, {@link Float#POSITIVE_INFINITY} and {@link Float#NEGATIVE_INFINITY}. // * // * @param s {@link String} to parse // * @return floating-point value in the {@link String} // * @throws NumberFormatException if input does not parse as a floating-point value // * @throws IllegalArgumentException if input is infinite or {@link Float#NaN} // * @see #parseDouble(String) // */ // public static float parseFloat(String s) { // float value = Float.parseFloat(s); // Preconditions.checkArgument(isFinite(value), "Bad value: %s", value); // return value; // } // // /** // * @return true if argument is not {@link Float#NaN}, {@link Float#POSITIVE_INFINITY} or // * {@link Float#NEGATIVE_INFINITY} // */ // public static boolean isFinite(float f) { // return !(Float.isNaN(f) || Float.isInfinite(f)); // } // // /** // * @see #parseFloat(String) // */ // public static double parseDouble(String s) { // double value = Double.parseDouble(s); // Preconditions.checkArgument(isFinite(value), "Bad value: %s", value); // return value; // } // // /** // * @return true if argument is not {@link Double#NaN}, {@link Double#POSITIVE_INFINITY} or // * {@link Double#NEGATIVE_INFINITY} // */ // public static boolean isFinite(double d) { // return !(Double.isNaN(d) || Double.isInfinite(d)); // } // // // /** // * Computes {@code l mod m}, such that the result is always in [0,m-1], for any {@code long} // * value including negative values. // * // * @param l long value // * @param m modulus // * @return {@code l mod m} if l is nonnegative, {@code (l mod m) + m} otherwise // */ // public static int mod(long l, int m) { // return ((int) (l % m) + m) % m; // } // // } // Path: online/src/net/myrrix/online/MostPopularItemsIterator.java import java.util.Iterator; import org.apache.mahout.cf.taste.recommender.IDRescorer; import org.apache.mahout.cf.taste.recommender.RecommendedItem; import net.myrrix.common.LangUtils; import net.myrrix.common.MutableRecommendedItem; import net.myrrix.common.collection.FastByIDFloatMap; /* * Copyright Myrrix Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.myrrix.online; /** * Used by {@link net.myrrix.common.MyrrixRecommender#mostPopularItems(int)}. * * @author Sean Owen */ final class MostPopularItemsIterator implements Iterator<RecommendedItem> { private final MutableRecommendedItem delegate; private final Iterator<FastByIDFloatMap.MapEntry> countsIterator; private final IDRescorer rescorer; MostPopularItemsIterator(Iterator<FastByIDFloatMap.MapEntry> countsIterator, IDRescorer rescorer) { delegate = new MutableRecommendedItem(); this.countsIterator = countsIterator; this.rescorer = rescorer; } @Override public boolean hasNext() { return countsIterator.hasNext(); } @Override public RecommendedItem next() { FastByIDFloatMap.MapEntry entry = countsIterator.next(); long id = entry.getKey(); float value = entry.getValue(); IDRescorer theRescorer = rescorer; if (theRescorer != null) { if (theRescorer.isFiltered(id)) { return null; } value = (float) theRescorer.rescore(id, value);
if (!LangUtils.isFinite(value)) {
erning/myrrix-recommender
online/src/net/myrrix/online/eval/AUCEvaluator.java
// Path: online/src/net/myrrix/online/RescorerProvider.java // public interface RescorerProvider { // // /** // * @param userIDs user(s) for which recommendations are being made, which may be needed in the rescoring logic. // * @param recommender the recommender instance that is rescoring results // * @param args arguments, if any, that should be used when making the {@link IDRescorer}. This is additional // * information from the request that may be necessary to its logic, like current location. What it means // * is up to the implementation. // * @return {@link IDRescorer} to use with {@link ServerRecommender#recommend(long, int, IDRescorer)} // * or {@code null} if none should be used. The resulting {@link IDRescorer} will be passed each candidate // * item ID to {@link IDRescorer#isFiltered(long)}, and each non-filtered candidate with its original score // * to {@link IDRescorer#rescore(long, double)} // */ // IDRescorer getRecommendRescorer(long[] userIDs, MyrrixRecommender recommender, String... args); // // /** // * @param itemIDs items that the anonymous user is associated to // * @param recommender the recommender instance that is rescoring results // * @param args arguments, if any, that should be used when making the {@link IDRescorer}. This is additional // * information from the request that may be necessary to its logic, like current location. What it means // * is up to the implementation. // * @return {@link IDRescorer} to use with {@link ServerRecommender#recommendToAnonymous(long[], int, IDRescorer)} // * or {@code null} if none should be used. The resulting {@link IDRescorer} will be passed each candidate // * item ID to {@link IDRescorer#isFiltered(long)}, and each non-filtered candidate with its original score // * to {@link IDRescorer#rescore(long, double)} // */ // IDRescorer getRecommendToAnonymousRescorer(long[] itemIDs, MyrrixRecommender recommender, String... args); // // /** // * @param recommender the recommender instance that is rescoring results // * @param args arguments, if any, that should be used when making the {@link IDRescorer}. This is additional // * information from the request that may be necessary to its logic, like current location. What it means // * is up to the implementation. // * @return {@link IDRescorer} to use with {@link ServerRecommender#mostPopularItems(int, IDRescorer)} // * or {@code null} if none should be used. // */ // IDRescorer getMostPopularItemsRescorer(MyrrixRecommender recommender, String... args); // // /** // * @param recommender the recommender instance that is rescoring results // * @param args arguments, if any, that should be used when making the {@link IDRescorer}. This is additional // * information from the request that may be necessary to its logic, like current location. What it means // * is up to the implementation. // * @return {@link Rescorer} to use with {@link ServerRecommender#mostSimilarItems(long[], int, Rescorer)} // * or {@code null} if none should be used. The {@link Rescorer} will be passed, to its // * {@link Rescorer#isFiltered(Object)} method, a {@link LongPair} containing the candidate item ID // * as its first element, and the item ID passed in the user query as its second element. // * Each non-filtered {@link LongPair} is passed with its original score to // * {@link Rescorer#rescore(Object, double)} // */ // Rescorer<LongPair> getMostSimilarItemsRescorer(MyrrixRecommender recommender, String... args); // // }
import java.io.File; import java.util.Collection; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import com.google.common.collect.Multimap; import org.apache.commons.math3.random.RandomGenerator; import org.apache.mahout.cf.taste.common.NoSuchItemException; import org.apache.mahout.cf.taste.common.NoSuchUserException; import org.apache.mahout.cf.taste.common.TasteException; import org.apache.mahout.cf.taste.recommender.RecommendedItem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.myrrix.common.MyrrixRecommender; import net.myrrix.common.collection.FastByIDMap; import net.myrrix.common.collection.FastIDSet; import net.myrrix.common.parallel.Paralleler; import net.myrrix.common.parallel.Processor; import net.myrrix.common.random.RandomManager; import net.myrrix.common.random.RandomUtils; import net.myrrix.online.RescorerProvider;
/* * Copyright Myrrix Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.myrrix.online.eval; /** * <p>This implementation calculates Area under curve (AUC), which may be understood as the probability * that a random "good" recommendation is ranked higher than a random "bad" recommendation.</p> * * <p>This class can be run as a Java program; the single argument is a directory containing test data. * The {@link EvaluationResult} is printed to standard out.</p> * * @author Sean Owen * @since 1.0 */ public final class AUCEvaluator extends AbstractEvaluator { private static final Logger log = LoggerFactory.getLogger(AUCEvaluator.class); @Override protected boolean isSplitTestByPrefValue() { return true; } @Override public EvaluationResult evaluate(MyrrixRecommender recommender,
// Path: online/src/net/myrrix/online/RescorerProvider.java // public interface RescorerProvider { // // /** // * @param userIDs user(s) for which recommendations are being made, which may be needed in the rescoring logic. // * @param recommender the recommender instance that is rescoring results // * @param args arguments, if any, that should be used when making the {@link IDRescorer}. This is additional // * information from the request that may be necessary to its logic, like current location. What it means // * is up to the implementation. // * @return {@link IDRescorer} to use with {@link ServerRecommender#recommend(long, int, IDRescorer)} // * or {@code null} if none should be used. The resulting {@link IDRescorer} will be passed each candidate // * item ID to {@link IDRescorer#isFiltered(long)}, and each non-filtered candidate with its original score // * to {@link IDRescorer#rescore(long, double)} // */ // IDRescorer getRecommendRescorer(long[] userIDs, MyrrixRecommender recommender, String... args); // // /** // * @param itemIDs items that the anonymous user is associated to // * @param recommender the recommender instance that is rescoring results // * @param args arguments, if any, that should be used when making the {@link IDRescorer}. This is additional // * information from the request that may be necessary to its logic, like current location. What it means // * is up to the implementation. // * @return {@link IDRescorer} to use with {@link ServerRecommender#recommendToAnonymous(long[], int, IDRescorer)} // * or {@code null} if none should be used. The resulting {@link IDRescorer} will be passed each candidate // * item ID to {@link IDRescorer#isFiltered(long)}, and each non-filtered candidate with its original score // * to {@link IDRescorer#rescore(long, double)} // */ // IDRescorer getRecommendToAnonymousRescorer(long[] itemIDs, MyrrixRecommender recommender, String... args); // // /** // * @param recommender the recommender instance that is rescoring results // * @param args arguments, if any, that should be used when making the {@link IDRescorer}. This is additional // * information from the request that may be necessary to its logic, like current location. What it means // * is up to the implementation. // * @return {@link IDRescorer} to use with {@link ServerRecommender#mostPopularItems(int, IDRescorer)} // * or {@code null} if none should be used. // */ // IDRescorer getMostPopularItemsRescorer(MyrrixRecommender recommender, String... args); // // /** // * @param recommender the recommender instance that is rescoring results // * @param args arguments, if any, that should be used when making the {@link IDRescorer}. This is additional // * information from the request that may be necessary to its logic, like current location. What it means // * is up to the implementation. // * @return {@link Rescorer} to use with {@link ServerRecommender#mostSimilarItems(long[], int, Rescorer)} // * or {@code null} if none should be used. The {@link Rescorer} will be passed, to its // * {@link Rescorer#isFiltered(Object)} method, a {@link LongPair} containing the candidate item ID // * as its first element, and the item ID passed in the user query as its second element. // * Each non-filtered {@link LongPair} is passed with its original score to // * {@link Rescorer#rescore(Object, double)} // */ // Rescorer<LongPair> getMostSimilarItemsRescorer(MyrrixRecommender recommender, String... args); // // } // Path: online/src/net/myrrix/online/eval/AUCEvaluator.java import java.io.File; import java.util.Collection; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import com.google.common.collect.Multimap; import org.apache.commons.math3.random.RandomGenerator; import org.apache.mahout.cf.taste.common.NoSuchItemException; import org.apache.mahout.cf.taste.common.NoSuchUserException; import org.apache.mahout.cf.taste.common.TasteException; import org.apache.mahout.cf.taste.recommender.RecommendedItem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.myrrix.common.MyrrixRecommender; import net.myrrix.common.collection.FastByIDMap; import net.myrrix.common.collection.FastIDSet; import net.myrrix.common.parallel.Paralleler; import net.myrrix.common.parallel.Processor; import net.myrrix.common.random.RandomManager; import net.myrrix.common.random.RandomUtils; import net.myrrix.online.RescorerProvider; /* * Copyright Myrrix Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.myrrix.online.eval; /** * <p>This implementation calculates Area under curve (AUC), which may be understood as the probability * that a random "good" recommendation is ranked higher than a random "bad" recommendation.</p> * * <p>This class can be run as a Java program; the single argument is a directory containing test data. * The {@link EvaluationResult} is printed to standard out.</p> * * @author Sean Owen * @since 1.0 */ public final class AUCEvaluator extends AbstractEvaluator { private static final Logger log = LoggerFactory.getLogger(AUCEvaluator.class); @Override protected boolean isSplitTestByPrefValue() { return true; } @Override public EvaluationResult evaluate(MyrrixRecommender recommender,
RescorerProvider provider, // ignored
erning/myrrix-recommender
client/src/net/myrrix/client/translating/GenericTranslatedRecommendedItem.java
// Path: common/src/net/myrrix/common/LangUtils.java // public final class LangUtils { // // private LangUtils() { // } // // /** // * Parses a {@code float} from a {@link String} as if by {@link Float#valueOf(String)}, but disallows special // * values like {@link Float#NaN}, {@link Float#POSITIVE_INFINITY} and {@link Float#NEGATIVE_INFINITY}. // * // * @param s {@link String} to parse // * @return floating-point value in the {@link String} // * @throws NumberFormatException if input does not parse as a floating-point value // * @throws IllegalArgumentException if input is infinite or {@link Float#NaN} // * @see #parseDouble(String) // */ // public static float parseFloat(String s) { // float value = Float.parseFloat(s); // Preconditions.checkArgument(isFinite(value), "Bad value: %s", value); // return value; // } // // /** // * @return true if argument is not {@link Float#NaN}, {@link Float#POSITIVE_INFINITY} or // * {@link Float#NEGATIVE_INFINITY} // */ // public static boolean isFinite(float f) { // return !(Float.isNaN(f) || Float.isInfinite(f)); // } // // /** // * @see #parseFloat(String) // */ // public static double parseDouble(String s) { // double value = Double.parseDouble(s); // Preconditions.checkArgument(isFinite(value), "Bad value: %s", value); // return value; // } // // /** // * @return true if argument is not {@link Double#NaN}, {@link Double#POSITIVE_INFINITY} or // * {@link Double#NEGATIVE_INFINITY} // */ // public static boolean isFinite(double d) { // return !(Double.isNaN(d) || Double.isInfinite(d)); // } // // // /** // * Computes {@code l mod m}, such that the result is always in [0,m-1], for any {@code long} // * value including negative values. // * // * @param l long value // * @param m modulus // * @return {@code l mod m} if l is nonnegative, {@code (l mod m) + m} otherwise // */ // public static int mod(long l, int m) { // return ((int) (l % m) + m) % m; // } // // }
import java.io.Serializable; import com.google.common.base.Preconditions; import com.google.common.primitives.Floats; import net.myrrix.common.LangUtils;
/* * Copyright Myrrix Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.myrrix.client.translating; /** * <p>A simple implementation of {@link TranslatedRecommendedItem}.</p> * * @author Sean Owen * @since 1.0 */ public final class GenericTranslatedRecommendedItem implements TranslatedRecommendedItem, Serializable { private final String itemID; private final float value; /** * @throws IllegalArgumentException if item is null or value is NaN or infinite */ public GenericTranslatedRecommendedItem(String itemID, float value) { Preconditions.checkNotNull(itemID);
// Path: common/src/net/myrrix/common/LangUtils.java // public final class LangUtils { // // private LangUtils() { // } // // /** // * Parses a {@code float} from a {@link String} as if by {@link Float#valueOf(String)}, but disallows special // * values like {@link Float#NaN}, {@link Float#POSITIVE_INFINITY} and {@link Float#NEGATIVE_INFINITY}. // * // * @param s {@link String} to parse // * @return floating-point value in the {@link String} // * @throws NumberFormatException if input does not parse as a floating-point value // * @throws IllegalArgumentException if input is infinite or {@link Float#NaN} // * @see #parseDouble(String) // */ // public static float parseFloat(String s) { // float value = Float.parseFloat(s); // Preconditions.checkArgument(isFinite(value), "Bad value: %s", value); // return value; // } // // /** // * @return true if argument is not {@link Float#NaN}, {@link Float#POSITIVE_INFINITY} or // * {@link Float#NEGATIVE_INFINITY} // */ // public static boolean isFinite(float f) { // return !(Float.isNaN(f) || Float.isInfinite(f)); // } // // /** // * @see #parseFloat(String) // */ // public static double parseDouble(String s) { // double value = Double.parseDouble(s); // Preconditions.checkArgument(isFinite(value), "Bad value: %s", value); // return value; // } // // /** // * @return true if argument is not {@link Double#NaN}, {@link Double#POSITIVE_INFINITY} or // * {@link Double#NEGATIVE_INFINITY} // */ // public static boolean isFinite(double d) { // return !(Double.isNaN(d) || Double.isInfinite(d)); // } // // // /** // * Computes {@code l mod m}, such that the result is always in [0,m-1], for any {@code long} // * value including negative values. // * // * @param l long value // * @param m modulus // * @return {@code l mod m} if l is nonnegative, {@code (l mod m) + m} otherwise // */ // public static int mod(long l, int m) { // return ((int) (l % m) + m) % m; // } // // } // Path: client/src/net/myrrix/client/translating/GenericTranslatedRecommendedItem.java import java.io.Serializable; import com.google.common.base.Preconditions; import com.google.common.primitives.Floats; import net.myrrix.common.LangUtils; /* * Copyright Myrrix Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.myrrix.client.translating; /** * <p>A simple implementation of {@link TranslatedRecommendedItem}.</p> * * @author Sean Owen * @since 1.0 */ public final class GenericTranslatedRecommendedItem implements TranslatedRecommendedItem, Serializable { private final String itemID; private final float value; /** * @throws IllegalArgumentException if item is null or value is NaN or infinite */ public GenericTranslatedRecommendedItem(String itemID, float value) { Preconditions.checkNotNull(itemID);
Preconditions.checkArgument(LangUtils.isFinite(value));
JackWink/tweakable
tweakable/src/main/java/com/jackwink/tweakable/builders/ActionPreferenceBuilder.java
// Path: tweakable/src/main/java/com/jackwink/tweakable/controls/ActionPreference.java // public class ActionPreference extends DialogPreference { // private int mCalled; // // public ActionPreference(Context context) { // super(context, null); // } // // @Override // protected void onSetInitialValue(final boolean restoreValue, final Object defaultValue) { // mCalled = getPersistedInt(0); // } // // @Override // protected Object onGetDefaultValue(final TypedArray a, final int index) { // return a.getInteger(index, 0); // } // // @Override // protected void onPrepareDialogBuilder(final AlertDialog.Builder builder) { // super.onPrepareDialogBuilder(builder); // // builder.setTitle(getTitle()); // builder.setMessage("Are you sure you want to " + getTitle().toString().toLowerCase() + "?"); // builder.setPositiveButton("yes", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // ++mCalled; // // We just need to cause a value to change on this key for the method to be called // // {@see com.jackwink.tweakable.Tweakable} // persistInt(mCalled); // } // }); // } // }
import android.preference.Preference; import com.jackwink.tweakable.controls.ActionPreference; import java.lang.reflect.Method;
package com.jackwink.tweakable.builders; /** * */ @SuppressWarnings({ "rawtypes" }) public class ActionPreferenceBuilder extends BasePreferenceBuilder<Preference> { @Override public Class[] getHandledTypes() { return new Class[] {Method.class }; } @Override public Preference build() {
// Path: tweakable/src/main/java/com/jackwink/tweakable/controls/ActionPreference.java // public class ActionPreference extends DialogPreference { // private int mCalled; // // public ActionPreference(Context context) { // super(context, null); // } // // @Override // protected void onSetInitialValue(final boolean restoreValue, final Object defaultValue) { // mCalled = getPersistedInt(0); // } // // @Override // protected Object onGetDefaultValue(final TypedArray a, final int index) { // return a.getInteger(index, 0); // } // // @Override // protected void onPrepareDialogBuilder(final AlertDialog.Builder builder) { // super.onPrepareDialogBuilder(builder); // // builder.setTitle(getTitle()); // builder.setMessage("Are you sure you want to " + getTitle().toString().toLowerCase() + "?"); // builder.setPositiveButton("yes", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // ++mCalled; // // We just need to cause a value to change on this key for the method to be called // // {@see com.jackwink.tweakable.Tweakable} // persistInt(mCalled); // } // }); // } // } // Path: tweakable/src/main/java/com/jackwink/tweakable/builders/ActionPreferenceBuilder.java import android.preference.Preference; import com.jackwink.tweakable.controls.ActionPreference; import java.lang.reflect.Method; package com.jackwink.tweakable.builders; /** * */ @SuppressWarnings({ "rawtypes" }) public class ActionPreferenceBuilder extends BasePreferenceBuilder<Preference> { @Override public Class[] getHandledTypes() { return new Class[] {Method.class }; } @Override public Preference build() {
return build(ActionPreference.class, true);
JackWink/tweakable
tweakable/src/main/java/com/jackwink/tweakable/binders/StringValueBinder.java
// Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/exceptions/FailedToBuildPreferenceException.java // public class FailedToBuildPreferenceException extends RuntimeException { // public static final long serialVersionUID = 0L; // // public FailedToBuildPreferenceException(String reason) { // super(reason); // } // // public FailedToBuildPreferenceException(String reason, Throwable rootCause) { // super(reason, rootCause); // } // }
import android.content.SharedPreferences; import com.jackwink.tweakable.exceptions.FailedToBuildPreferenceException; import java.lang.reflect.Field;
package com.jackwink.tweakable.binders; /** * Binds a String value to a given {@link Field}. */ public class StringValueBinder extends AbstractValueBinder<String> { public StringValueBinder(Field field) { mField = field; } @Override public Class<String> getType() { return String.class; } @Override public String getValue() { try { if (mField.getType().equals(String.class)) { return (String) mField.get(null); }
// Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/exceptions/FailedToBuildPreferenceException.java // public class FailedToBuildPreferenceException extends RuntimeException { // public static final long serialVersionUID = 0L; // // public FailedToBuildPreferenceException(String reason) { // super(reason); // } // // public FailedToBuildPreferenceException(String reason, Throwable rootCause) { // super(reason, rootCause); // } // } // Path: tweakable/src/main/java/com/jackwink/tweakable/binders/StringValueBinder.java import android.content.SharedPreferences; import com.jackwink.tweakable.exceptions.FailedToBuildPreferenceException; import java.lang.reflect.Field; package com.jackwink.tweakable.binders; /** * Binds a String value to a given {@link Field}. */ public class StringValueBinder extends AbstractValueBinder<String> { public StringValueBinder(Field field) { mField = field; } @Override public Class<String> getType() { return String.class; } @Override public String getValue() { try { if (mField.getType().equals(String.class)) { return (String) mField.get(null); }
throw new FailedToBuildPreferenceException(
JackWink/tweakable
tweakable/src/main/java/com/jackwink/tweakable/builders/FloatPreferenceBuilder.java
// Path: tweakable/src/main/java/com/jackwink/tweakable/controls/SliderPreference.java // public class SliderPreference extends DialogPreference { // private static final String TAG = SliderPreference.class.getSimpleName(); // // private static final int MAX_VALUE = 100; // // private SeekBar mSlider; // private int mSelectedValue; // // // private float mOriginalValue; // private float mValue; // private float mMinValue; // private float mMaxValue; // private float mRange; // // public SliderPreference(Context context) { // super(context, null); // } // // public void setMaxValue(float maxValue) { // mMaxValue = maxValue; // mRange = mMaxValue - mMinValue; // } // // public void setMinValue(float minValue) { // mMinValue = minValue; // mRange = mMaxValue - mMinValue; // } // // @Override // protected void onSetInitialValue(final boolean restoreValue, final Object defaultValue) { // setValue(restoreValue ? getPersistedFloat(0f) : (Float) defaultValue, false); // mOriginalValue = mValue; // } // // @Override // protected Object onGetDefaultValue(final TypedArray a, final int index) { // return a.getFloat(index, 0f); // } // // @Override // protected void onPrepareDialogBuilder(final AlertDialog.Builder builder) { // super.onPrepareDialogBuilder(builder); // mSlider = new SeekBar(getContext()); // mSlider.setMax(MAX_VALUE); // mSlider.setProgress(mSelectedValue); // mSlider.setOnSeekBarChangeListener(new ValueChangeListener()); // mSlider.setLayoutParams(new LinearLayout.LayoutParams( // ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); // // // final LinearLayout linearLayout = new LinearLayout(getContext()); // linearLayout.setLayoutParams(new LinearLayout.LayoutParams( // ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); // linearLayout.setGravity(Gravity.CENTER); // linearLayout.addView(mSlider); // builder.setView(linearLayout); // } // // @Override // protected void onDialogClosed(final boolean positiveResult) { // if (positiveResult && shouldPersist()) { // setSelectedValue(mSlider.getProgress(), true); // } else { // setValue(getPersistedFloat(mOriginalValue), false); // } // } // // private void setSelectedValue(int value, boolean persist) { // mSelectedValue = value; // mValue = mMinValue + ((((float) mSelectedValue / (float) MAX_VALUE)) * mRange); // if (mValue > mMaxValue) { // mValue = mMaxValue; // } // // if (persist) { // persistFloat(mValue); // } // updateSummary(); // } // // private void setValue(float value, boolean persist) { // mValue = value; // mSelectedValue = (int) (((mValue - mMinValue) * 100) / mRange); // if (mSelectedValue > MAX_VALUE) { // mSelectedValue = MAX_VALUE; // } // // if (persist) { // persistFloat(mValue); // } // updateSummary(); // } // // private void updateSummary() { // this.setSummary(Float.toString(mValue)); // } // // private class ValueChangeListener implements SeekBar.OnSeekBarChangeListener { // @Override // public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // SliderPreference.this.setSelectedValue(progress, false); // } // // @Override // public void onStartTrackingTouch(SeekBar seekBar) { // // } // // @Override // public void onStopTrackingTouch(SeekBar seekBar) { // // } // } // } // // Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/types/TweakableFloat.java // public class TweakableFloat extends AbstractTweakableValue<Float> { // // public static final String BUNDLE_MIN_VALUE_KEY = "min_value"; // public static final String BUNDLE_MAX_VALUE_KEY = "max_value"; // // private TwkFloat mParsedAnnotation; // // public Float getMaxValue() { // return mParsedAnnotation.maxValue(); // } // // public Float getMinValue() { // return mParsedAnnotation.minValue(); // } // // @Override // public Class<Float> getType() { // return Float.class; // } // // public static TweakableFloat parse(String className, String fieldName, TwkFloat annotation) { // TweakableFloat returnValue = new TweakableFloat(); // // /* Abstract Tweakable Values */ // returnValue.mKey = className + "." + fieldName; // returnValue.mTitle = getDefaultString(annotation.title(), fieldName); // returnValue.mSummary = annotation.summary(); // returnValue.mCategory = getDefaultString(annotation.category(), null); // returnValue.mScreen = getDefaultString(annotation.screen(), null); // // /* TweakableFloat */ // returnValue.mParsedAnnotation = annotation; // return returnValue; // } // }
import android.preference.Preference; import com.jackwink.tweakable.controls.SliderPreference; import com.jackwink.tweakable.types.TweakableFloat;
package com.jackwink.tweakable.builders; /** * */ @SuppressWarnings({ "rawtypes" }) public class FloatPreferenceBuilder extends BasePreferenceBuilder<Preference> { @Override public Class[] getHandledTypes() { return new Class[] {Float.class, float.class }; } @Override public Preference build() {
// Path: tweakable/src/main/java/com/jackwink/tweakable/controls/SliderPreference.java // public class SliderPreference extends DialogPreference { // private static final String TAG = SliderPreference.class.getSimpleName(); // // private static final int MAX_VALUE = 100; // // private SeekBar mSlider; // private int mSelectedValue; // // // private float mOriginalValue; // private float mValue; // private float mMinValue; // private float mMaxValue; // private float mRange; // // public SliderPreference(Context context) { // super(context, null); // } // // public void setMaxValue(float maxValue) { // mMaxValue = maxValue; // mRange = mMaxValue - mMinValue; // } // // public void setMinValue(float minValue) { // mMinValue = minValue; // mRange = mMaxValue - mMinValue; // } // // @Override // protected void onSetInitialValue(final boolean restoreValue, final Object defaultValue) { // setValue(restoreValue ? getPersistedFloat(0f) : (Float) defaultValue, false); // mOriginalValue = mValue; // } // // @Override // protected Object onGetDefaultValue(final TypedArray a, final int index) { // return a.getFloat(index, 0f); // } // // @Override // protected void onPrepareDialogBuilder(final AlertDialog.Builder builder) { // super.onPrepareDialogBuilder(builder); // mSlider = new SeekBar(getContext()); // mSlider.setMax(MAX_VALUE); // mSlider.setProgress(mSelectedValue); // mSlider.setOnSeekBarChangeListener(new ValueChangeListener()); // mSlider.setLayoutParams(new LinearLayout.LayoutParams( // ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); // // // final LinearLayout linearLayout = new LinearLayout(getContext()); // linearLayout.setLayoutParams(new LinearLayout.LayoutParams( // ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); // linearLayout.setGravity(Gravity.CENTER); // linearLayout.addView(mSlider); // builder.setView(linearLayout); // } // // @Override // protected void onDialogClosed(final boolean positiveResult) { // if (positiveResult && shouldPersist()) { // setSelectedValue(mSlider.getProgress(), true); // } else { // setValue(getPersistedFloat(mOriginalValue), false); // } // } // // private void setSelectedValue(int value, boolean persist) { // mSelectedValue = value; // mValue = mMinValue + ((((float) mSelectedValue / (float) MAX_VALUE)) * mRange); // if (mValue > mMaxValue) { // mValue = mMaxValue; // } // // if (persist) { // persistFloat(mValue); // } // updateSummary(); // } // // private void setValue(float value, boolean persist) { // mValue = value; // mSelectedValue = (int) (((mValue - mMinValue) * 100) / mRange); // if (mSelectedValue > MAX_VALUE) { // mSelectedValue = MAX_VALUE; // } // // if (persist) { // persistFloat(mValue); // } // updateSummary(); // } // // private void updateSummary() { // this.setSummary(Float.toString(mValue)); // } // // private class ValueChangeListener implements SeekBar.OnSeekBarChangeListener { // @Override // public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // SliderPreference.this.setSelectedValue(progress, false); // } // // @Override // public void onStartTrackingTouch(SeekBar seekBar) { // // } // // @Override // public void onStopTrackingTouch(SeekBar seekBar) { // // } // } // } // // Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/types/TweakableFloat.java // public class TweakableFloat extends AbstractTweakableValue<Float> { // // public static final String BUNDLE_MIN_VALUE_KEY = "min_value"; // public static final String BUNDLE_MAX_VALUE_KEY = "max_value"; // // private TwkFloat mParsedAnnotation; // // public Float getMaxValue() { // return mParsedAnnotation.maxValue(); // } // // public Float getMinValue() { // return mParsedAnnotation.minValue(); // } // // @Override // public Class<Float> getType() { // return Float.class; // } // // public static TweakableFloat parse(String className, String fieldName, TwkFloat annotation) { // TweakableFloat returnValue = new TweakableFloat(); // // /* Abstract Tweakable Values */ // returnValue.mKey = className + "." + fieldName; // returnValue.mTitle = getDefaultString(annotation.title(), fieldName); // returnValue.mSummary = annotation.summary(); // returnValue.mCategory = getDefaultString(annotation.category(), null); // returnValue.mScreen = getDefaultString(annotation.screen(), null); // // /* TweakableFloat */ // returnValue.mParsedAnnotation = annotation; // return returnValue; // } // } // Path: tweakable/src/main/java/com/jackwink/tweakable/builders/FloatPreferenceBuilder.java import android.preference.Preference; import com.jackwink.tweakable.controls.SliderPreference; import com.jackwink.tweakable.types.TweakableFloat; package com.jackwink.tweakable.builders; /** * */ @SuppressWarnings({ "rawtypes" }) public class FloatPreferenceBuilder extends BasePreferenceBuilder<Preference> { @Override public Class[] getHandledTypes() { return new Class[] {Float.class, float.class }; } @Override public Preference build() {
SliderPreference preference = build(SliderPreference.class, true);
JackWink/tweakable
tweakable/src/main/java/com/jackwink/tweakable/builders/FloatPreferenceBuilder.java
// Path: tweakable/src/main/java/com/jackwink/tweakable/controls/SliderPreference.java // public class SliderPreference extends DialogPreference { // private static final String TAG = SliderPreference.class.getSimpleName(); // // private static final int MAX_VALUE = 100; // // private SeekBar mSlider; // private int mSelectedValue; // // // private float mOriginalValue; // private float mValue; // private float mMinValue; // private float mMaxValue; // private float mRange; // // public SliderPreference(Context context) { // super(context, null); // } // // public void setMaxValue(float maxValue) { // mMaxValue = maxValue; // mRange = mMaxValue - mMinValue; // } // // public void setMinValue(float minValue) { // mMinValue = minValue; // mRange = mMaxValue - mMinValue; // } // // @Override // protected void onSetInitialValue(final boolean restoreValue, final Object defaultValue) { // setValue(restoreValue ? getPersistedFloat(0f) : (Float) defaultValue, false); // mOriginalValue = mValue; // } // // @Override // protected Object onGetDefaultValue(final TypedArray a, final int index) { // return a.getFloat(index, 0f); // } // // @Override // protected void onPrepareDialogBuilder(final AlertDialog.Builder builder) { // super.onPrepareDialogBuilder(builder); // mSlider = new SeekBar(getContext()); // mSlider.setMax(MAX_VALUE); // mSlider.setProgress(mSelectedValue); // mSlider.setOnSeekBarChangeListener(new ValueChangeListener()); // mSlider.setLayoutParams(new LinearLayout.LayoutParams( // ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); // // // final LinearLayout linearLayout = new LinearLayout(getContext()); // linearLayout.setLayoutParams(new LinearLayout.LayoutParams( // ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); // linearLayout.setGravity(Gravity.CENTER); // linearLayout.addView(mSlider); // builder.setView(linearLayout); // } // // @Override // protected void onDialogClosed(final boolean positiveResult) { // if (positiveResult && shouldPersist()) { // setSelectedValue(mSlider.getProgress(), true); // } else { // setValue(getPersistedFloat(mOriginalValue), false); // } // } // // private void setSelectedValue(int value, boolean persist) { // mSelectedValue = value; // mValue = mMinValue + ((((float) mSelectedValue / (float) MAX_VALUE)) * mRange); // if (mValue > mMaxValue) { // mValue = mMaxValue; // } // // if (persist) { // persistFloat(mValue); // } // updateSummary(); // } // // private void setValue(float value, boolean persist) { // mValue = value; // mSelectedValue = (int) (((mValue - mMinValue) * 100) / mRange); // if (mSelectedValue > MAX_VALUE) { // mSelectedValue = MAX_VALUE; // } // // if (persist) { // persistFloat(mValue); // } // updateSummary(); // } // // private void updateSummary() { // this.setSummary(Float.toString(mValue)); // } // // private class ValueChangeListener implements SeekBar.OnSeekBarChangeListener { // @Override // public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // SliderPreference.this.setSelectedValue(progress, false); // } // // @Override // public void onStartTrackingTouch(SeekBar seekBar) { // // } // // @Override // public void onStopTrackingTouch(SeekBar seekBar) { // // } // } // } // // Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/types/TweakableFloat.java // public class TweakableFloat extends AbstractTweakableValue<Float> { // // public static final String BUNDLE_MIN_VALUE_KEY = "min_value"; // public static final String BUNDLE_MAX_VALUE_KEY = "max_value"; // // private TwkFloat mParsedAnnotation; // // public Float getMaxValue() { // return mParsedAnnotation.maxValue(); // } // // public Float getMinValue() { // return mParsedAnnotation.minValue(); // } // // @Override // public Class<Float> getType() { // return Float.class; // } // // public static TweakableFloat parse(String className, String fieldName, TwkFloat annotation) { // TweakableFloat returnValue = new TweakableFloat(); // // /* Abstract Tweakable Values */ // returnValue.mKey = className + "." + fieldName; // returnValue.mTitle = getDefaultString(annotation.title(), fieldName); // returnValue.mSummary = annotation.summary(); // returnValue.mCategory = getDefaultString(annotation.category(), null); // returnValue.mScreen = getDefaultString(annotation.screen(), null); // // /* TweakableFloat */ // returnValue.mParsedAnnotation = annotation; // return returnValue; // } // }
import android.preference.Preference; import com.jackwink.tweakable.controls.SliderPreference; import com.jackwink.tweakable.types.TweakableFloat;
package com.jackwink.tweakable.builders; /** * */ @SuppressWarnings({ "rawtypes" }) public class FloatPreferenceBuilder extends BasePreferenceBuilder<Preference> { @Override public Class[] getHandledTypes() { return new Class[] {Float.class, float.class }; } @Override public Preference build() { SliderPreference preference = build(SliderPreference.class, true); preference.setDialogMessage((String) getRequiredAttribute(BUNDLE_SUMMARY_KEY)); preference.setMaxValue((Float)
// Path: tweakable/src/main/java/com/jackwink/tweakable/controls/SliderPreference.java // public class SliderPreference extends DialogPreference { // private static final String TAG = SliderPreference.class.getSimpleName(); // // private static final int MAX_VALUE = 100; // // private SeekBar mSlider; // private int mSelectedValue; // // // private float mOriginalValue; // private float mValue; // private float mMinValue; // private float mMaxValue; // private float mRange; // // public SliderPreference(Context context) { // super(context, null); // } // // public void setMaxValue(float maxValue) { // mMaxValue = maxValue; // mRange = mMaxValue - mMinValue; // } // // public void setMinValue(float minValue) { // mMinValue = minValue; // mRange = mMaxValue - mMinValue; // } // // @Override // protected void onSetInitialValue(final boolean restoreValue, final Object defaultValue) { // setValue(restoreValue ? getPersistedFloat(0f) : (Float) defaultValue, false); // mOriginalValue = mValue; // } // // @Override // protected Object onGetDefaultValue(final TypedArray a, final int index) { // return a.getFloat(index, 0f); // } // // @Override // protected void onPrepareDialogBuilder(final AlertDialog.Builder builder) { // super.onPrepareDialogBuilder(builder); // mSlider = new SeekBar(getContext()); // mSlider.setMax(MAX_VALUE); // mSlider.setProgress(mSelectedValue); // mSlider.setOnSeekBarChangeListener(new ValueChangeListener()); // mSlider.setLayoutParams(new LinearLayout.LayoutParams( // ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); // // // final LinearLayout linearLayout = new LinearLayout(getContext()); // linearLayout.setLayoutParams(new LinearLayout.LayoutParams( // ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); // linearLayout.setGravity(Gravity.CENTER); // linearLayout.addView(mSlider); // builder.setView(linearLayout); // } // // @Override // protected void onDialogClosed(final boolean positiveResult) { // if (positiveResult && shouldPersist()) { // setSelectedValue(mSlider.getProgress(), true); // } else { // setValue(getPersistedFloat(mOriginalValue), false); // } // } // // private void setSelectedValue(int value, boolean persist) { // mSelectedValue = value; // mValue = mMinValue + ((((float) mSelectedValue / (float) MAX_VALUE)) * mRange); // if (mValue > mMaxValue) { // mValue = mMaxValue; // } // // if (persist) { // persistFloat(mValue); // } // updateSummary(); // } // // private void setValue(float value, boolean persist) { // mValue = value; // mSelectedValue = (int) (((mValue - mMinValue) * 100) / mRange); // if (mSelectedValue > MAX_VALUE) { // mSelectedValue = MAX_VALUE; // } // // if (persist) { // persistFloat(mValue); // } // updateSummary(); // } // // private void updateSummary() { // this.setSummary(Float.toString(mValue)); // } // // private class ValueChangeListener implements SeekBar.OnSeekBarChangeListener { // @Override // public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // SliderPreference.this.setSelectedValue(progress, false); // } // // @Override // public void onStartTrackingTouch(SeekBar seekBar) { // // } // // @Override // public void onStopTrackingTouch(SeekBar seekBar) { // // } // } // } // // Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/types/TweakableFloat.java // public class TweakableFloat extends AbstractTweakableValue<Float> { // // public static final String BUNDLE_MIN_VALUE_KEY = "min_value"; // public static final String BUNDLE_MAX_VALUE_KEY = "max_value"; // // private TwkFloat mParsedAnnotation; // // public Float getMaxValue() { // return mParsedAnnotation.maxValue(); // } // // public Float getMinValue() { // return mParsedAnnotation.minValue(); // } // // @Override // public Class<Float> getType() { // return Float.class; // } // // public static TweakableFloat parse(String className, String fieldName, TwkFloat annotation) { // TweakableFloat returnValue = new TweakableFloat(); // // /* Abstract Tweakable Values */ // returnValue.mKey = className + "." + fieldName; // returnValue.mTitle = getDefaultString(annotation.title(), fieldName); // returnValue.mSummary = annotation.summary(); // returnValue.mCategory = getDefaultString(annotation.category(), null); // returnValue.mScreen = getDefaultString(annotation.screen(), null); // // /* TweakableFloat */ // returnValue.mParsedAnnotation = annotation; // return returnValue; // } // } // Path: tweakable/src/main/java/com/jackwink/tweakable/builders/FloatPreferenceBuilder.java import android.preference.Preference; import com.jackwink.tweakable.controls.SliderPreference; import com.jackwink.tweakable.types.TweakableFloat; package com.jackwink.tweakable.builders; /** * */ @SuppressWarnings({ "rawtypes" }) public class FloatPreferenceBuilder extends BasePreferenceBuilder<Preference> { @Override public Class[] getHandledTypes() { return new Class[] {Float.class, float.class }; } @Override public Preference build() { SliderPreference preference = build(SliderPreference.class, true); preference.setDialogMessage((String) getRequiredAttribute(BUNDLE_SUMMARY_KEY)); preference.setMaxValue((Float)
getRequiredAttribute(TweakableFloat.BUNDLE_MAX_VALUE_KEY));
JackWink/tweakable
tweakable/src/main/java/com/jackwink/tweakable/Tweakable.java
// Path: tweakable/src/main/java/com/jackwink/tweakable/binders/ActionBinder.java // public class ActionBinder extends AbstractValueBinder<Method> { // // protected Method mMethod; // // public ActionBinder(Method method) { // mMethod = method; // } // // @Override // public Class<Method> getType() { // return Method.class; // } // // @Override // public void bindValue(SharedPreferences preferences, String key) { // try { // mMethod.invoke(null); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public Method getValue() { // return mMethod; // } // } // // Path: tweakable/src/main/java/com/jackwink/tweakable/binders/ValueBinder.java // public interface ValueBinder<T> { // // void bindValue(SharedPreferences preferences, String key); // // Class<T> getType(); // // T getValue(); // // @SuppressWarnings({ "rawtypes" }) // enum DeclaredTypes { // BOOL(new Class[] {Boolean.class, boolean.class }), // INT(new Class[] {Integer.class, int.class }), // FLOAT(new Class[] {Float.class, float.class }), // STRING(new Class[] {String.class }), // ACTION(new Class[] {Method.class }); // // private Class[] mHandledTypes; // // DeclaredTypes(Class[] types) { // mHandledTypes = types; // } // // public boolean contains(Class cls) { // for (Class clazz : mHandledTypes) { // if (clazz.equals(cls)) { // return true; // } // } // return false; // } // // public ValueBinder getBinder(Object fieldOrMethod) { // switch (this) { // case BOOL: // return new BooleanValueBinder((Field) fieldOrMethod); // case INT: // return new IntegerValueBinder((Field) fieldOrMethod); // case FLOAT: // return new FloatValueBinder((Field) fieldOrMethod); // case STRING: // return new StringValueBinder((Field) fieldOrMethod); // case ACTION: // return new ActionBinder((Method) fieldOrMethod); // default: // return null; // } // } // } // } // // Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/exceptions/FailedToBuildPreferenceException.java // public class FailedToBuildPreferenceException extends RuntimeException { // public static final long serialVersionUID = 0L; // // public FailedToBuildPreferenceException(String reason) { // super(reason); // } // // public FailedToBuildPreferenceException(String reason, Throwable rootCause) { // super(reason, rootCause); // } // } // // Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/types/AbstractTweakableValue.java // public abstract class AbstractTweakableValue<T> implements TweakableValue<T> { // public static final String BUNDLE_KEYATTR_KEY = "key"; // public static final String BUNDLE_TITLE_KEY = "title"; // public static final String BUNDLE_SUMMARY_KEY = "summary"; // // public static final String BUNDLE_CATEGORY_KEY = "category"; // public static final String BUNDLE_SCREEN_KEY = "screen"; // // public static final String ROOT_SCREEN_KEY = "tweakable-values-root-screen"; // public static final String ROOT_CATEGORY_KEY = "tweakable-values-root-category"; // // // protected String mTitle; // protected String mKey; // protected String mSummary; // protected String mCategory; // protected String mScreen; // // @Override // public String getKey() { // return mKey; // } // // @Override // public String getTitle() { // return mTitle == null ? "ERROR" : mTitle; // } // // @Override // public String getSummary() { // return mSummary; // } // // @Override // public String getCategory() { // return mCategory; // } // // @Override // public String getScreen() { // return mScreen; // } // // public static String getDefaultString(String value, String defaultValue) { // if (value == null || value.isEmpty()) { // return defaultValue; // } // return value; // } // }
import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import com.jackwink.tweakable.binders.ActionBinder; import com.jackwink.tweakable.binders.ValueBinder; import com.jackwink.tweakable.exceptions.FailedToBuildPreferenceException; import com.jackwink.tweakable.types.AbstractTweakableValue; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.util.LinkedHashMap; import java.util.Map;
package com.jackwink.tweakable; /** * Tweakable values and Feature Flags for Android. * * <h2>Usage Instructions</h2> * * <p>Call {@link Tweakable#init(Context)} to inject the default values * (or saved values from Preferences) on the start of your application or main activity.</p> * * <p>Shake your phone to pull up the generated settings!</p> */ @SuppressWarnings({ "rawtypes", "unchecked" }) public class Tweakable { private static final String TAG = Tweakable.class.getSimpleName(); private static String mSharedPreferencesName; private static SharedPreferences mSharedPreferences; private static TweakableShakeDetector mShakeDetector; private static boolean mOnShakeEnabled;
// Path: tweakable/src/main/java/com/jackwink/tweakable/binders/ActionBinder.java // public class ActionBinder extends AbstractValueBinder<Method> { // // protected Method mMethod; // // public ActionBinder(Method method) { // mMethod = method; // } // // @Override // public Class<Method> getType() { // return Method.class; // } // // @Override // public void bindValue(SharedPreferences preferences, String key) { // try { // mMethod.invoke(null); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public Method getValue() { // return mMethod; // } // } // // Path: tweakable/src/main/java/com/jackwink/tweakable/binders/ValueBinder.java // public interface ValueBinder<T> { // // void bindValue(SharedPreferences preferences, String key); // // Class<T> getType(); // // T getValue(); // // @SuppressWarnings({ "rawtypes" }) // enum DeclaredTypes { // BOOL(new Class[] {Boolean.class, boolean.class }), // INT(new Class[] {Integer.class, int.class }), // FLOAT(new Class[] {Float.class, float.class }), // STRING(new Class[] {String.class }), // ACTION(new Class[] {Method.class }); // // private Class[] mHandledTypes; // // DeclaredTypes(Class[] types) { // mHandledTypes = types; // } // // public boolean contains(Class cls) { // for (Class clazz : mHandledTypes) { // if (clazz.equals(cls)) { // return true; // } // } // return false; // } // // public ValueBinder getBinder(Object fieldOrMethod) { // switch (this) { // case BOOL: // return new BooleanValueBinder((Field) fieldOrMethod); // case INT: // return new IntegerValueBinder((Field) fieldOrMethod); // case FLOAT: // return new FloatValueBinder((Field) fieldOrMethod); // case STRING: // return new StringValueBinder((Field) fieldOrMethod); // case ACTION: // return new ActionBinder((Method) fieldOrMethod); // default: // return null; // } // } // } // } // // Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/exceptions/FailedToBuildPreferenceException.java // public class FailedToBuildPreferenceException extends RuntimeException { // public static final long serialVersionUID = 0L; // // public FailedToBuildPreferenceException(String reason) { // super(reason); // } // // public FailedToBuildPreferenceException(String reason, Throwable rootCause) { // super(reason, rootCause); // } // } // // Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/types/AbstractTweakableValue.java // public abstract class AbstractTweakableValue<T> implements TweakableValue<T> { // public static final String BUNDLE_KEYATTR_KEY = "key"; // public static final String BUNDLE_TITLE_KEY = "title"; // public static final String BUNDLE_SUMMARY_KEY = "summary"; // // public static final String BUNDLE_CATEGORY_KEY = "category"; // public static final String BUNDLE_SCREEN_KEY = "screen"; // // public static final String ROOT_SCREEN_KEY = "tweakable-values-root-screen"; // public static final String ROOT_CATEGORY_KEY = "tweakable-values-root-category"; // // // protected String mTitle; // protected String mKey; // protected String mSummary; // protected String mCategory; // protected String mScreen; // // @Override // public String getKey() { // return mKey; // } // // @Override // public String getTitle() { // return mTitle == null ? "ERROR" : mTitle; // } // // @Override // public String getSummary() { // return mSummary; // } // // @Override // public String getCategory() { // return mCategory; // } // // @Override // public String getScreen() { // return mScreen; // } // // public static String getDefaultString(String value, String defaultValue) { // if (value == null || value.isEmpty()) { // return defaultValue; // } // return value; // } // } // Path: tweakable/src/main/java/com/jackwink/tweakable/Tweakable.java import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import com.jackwink.tweakable.binders.ActionBinder; import com.jackwink.tweakable.binders.ValueBinder; import com.jackwink.tweakable.exceptions.FailedToBuildPreferenceException; import com.jackwink.tweakable.types.AbstractTweakableValue; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.util.LinkedHashMap; import java.util.Map; package com.jackwink.tweakable; /** * Tweakable values and Feature Flags for Android. * * <h2>Usage Instructions</h2> * * <p>Call {@link Tweakable#init(Context)} to inject the default values * (or saved values from Preferences) on the start of your application or main activity.</p> * * <p>Shake your phone to pull up the generated settings!</p> */ @SuppressWarnings({ "rawtypes", "unchecked" }) public class Tweakable { private static final String TAG = Tweakable.class.getSimpleName(); private static String mSharedPreferencesName; private static SharedPreferences mSharedPreferences; private static TweakableShakeDetector mShakeDetector; private static boolean mOnShakeEnabled;
private static LinkedHashMap<String, ValueBinder> mValueBinders =
JackWink/tweakable
tweakable/src/main/java/com/jackwink/tweakable/Tweakable.java
// Path: tweakable/src/main/java/com/jackwink/tweakable/binders/ActionBinder.java // public class ActionBinder extends AbstractValueBinder<Method> { // // protected Method mMethod; // // public ActionBinder(Method method) { // mMethod = method; // } // // @Override // public Class<Method> getType() { // return Method.class; // } // // @Override // public void bindValue(SharedPreferences preferences, String key) { // try { // mMethod.invoke(null); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public Method getValue() { // return mMethod; // } // } // // Path: tweakable/src/main/java/com/jackwink/tweakable/binders/ValueBinder.java // public interface ValueBinder<T> { // // void bindValue(SharedPreferences preferences, String key); // // Class<T> getType(); // // T getValue(); // // @SuppressWarnings({ "rawtypes" }) // enum DeclaredTypes { // BOOL(new Class[] {Boolean.class, boolean.class }), // INT(new Class[] {Integer.class, int.class }), // FLOAT(new Class[] {Float.class, float.class }), // STRING(new Class[] {String.class }), // ACTION(new Class[] {Method.class }); // // private Class[] mHandledTypes; // // DeclaredTypes(Class[] types) { // mHandledTypes = types; // } // // public boolean contains(Class cls) { // for (Class clazz : mHandledTypes) { // if (clazz.equals(cls)) { // return true; // } // } // return false; // } // // public ValueBinder getBinder(Object fieldOrMethod) { // switch (this) { // case BOOL: // return new BooleanValueBinder((Field) fieldOrMethod); // case INT: // return new IntegerValueBinder((Field) fieldOrMethod); // case FLOAT: // return new FloatValueBinder((Field) fieldOrMethod); // case STRING: // return new StringValueBinder((Field) fieldOrMethod); // case ACTION: // return new ActionBinder((Method) fieldOrMethod); // default: // return null; // } // } // } // } // // Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/exceptions/FailedToBuildPreferenceException.java // public class FailedToBuildPreferenceException extends RuntimeException { // public static final long serialVersionUID = 0L; // // public FailedToBuildPreferenceException(String reason) { // super(reason); // } // // public FailedToBuildPreferenceException(String reason, Throwable rootCause) { // super(reason, rootCause); // } // } // // Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/types/AbstractTweakableValue.java // public abstract class AbstractTweakableValue<T> implements TweakableValue<T> { // public static final String BUNDLE_KEYATTR_KEY = "key"; // public static final String BUNDLE_TITLE_KEY = "title"; // public static final String BUNDLE_SUMMARY_KEY = "summary"; // // public static final String BUNDLE_CATEGORY_KEY = "category"; // public static final String BUNDLE_SCREEN_KEY = "screen"; // // public static final String ROOT_SCREEN_KEY = "tweakable-values-root-screen"; // public static final String ROOT_CATEGORY_KEY = "tweakable-values-root-category"; // // // protected String mTitle; // protected String mKey; // protected String mSummary; // protected String mCategory; // protected String mScreen; // // @Override // public String getKey() { // return mKey; // } // // @Override // public String getTitle() { // return mTitle == null ? "ERROR" : mTitle; // } // // @Override // public String getSummary() { // return mSummary; // } // // @Override // public String getCategory() { // return mCategory; // } // // @Override // public String getScreen() { // return mScreen; // } // // public static String getDefaultString(String value, String defaultValue) { // if (value == null || value.isEmpty()) { // return defaultValue; // } // return value; // } // }
import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import com.jackwink.tweakable.binders.ActionBinder; import com.jackwink.tweakable.binders.ValueBinder; import com.jackwink.tweakable.exceptions.FailedToBuildPreferenceException; import com.jackwink.tweakable.types.AbstractTweakableValue; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.util.LinkedHashMap; import java.util.Map;
} protected static synchronized void resetShakeListener() { if (!mOnShakeEnabled) { Log.w(TAG, "Shake detection not enabled!"); } mShakeDetector.reset(); } protected static synchronized boolean isShakeListenerEnabled() { return mOnShakeEnabled; } protected static synchronized void startShakeListener() { if (mOnShakeEnabled) { Log.w(TAG, "Shake detection not enabled!"); } mShakeDetector.listen(); } /** * <p>Returns an instance of the generated preferences class, or throws an exception if it can't * be found. For internal use only!</p> * @return The generated {@link PreferenceAnnotationProcessor} */ protected static PreferenceAnnotationProcessor getPreferences() { try { return (PreferenceAnnotationProcessor) Class.forName("com.jackwink.tweakable.GeneratedPreferences").newInstance(); } catch (Exception e) {
// Path: tweakable/src/main/java/com/jackwink/tweakable/binders/ActionBinder.java // public class ActionBinder extends AbstractValueBinder<Method> { // // protected Method mMethod; // // public ActionBinder(Method method) { // mMethod = method; // } // // @Override // public Class<Method> getType() { // return Method.class; // } // // @Override // public void bindValue(SharedPreferences preferences, String key) { // try { // mMethod.invoke(null); // } catch (Exception e) { // e.printStackTrace(); // } // } // // @Override // public Method getValue() { // return mMethod; // } // } // // Path: tweakable/src/main/java/com/jackwink/tweakable/binders/ValueBinder.java // public interface ValueBinder<T> { // // void bindValue(SharedPreferences preferences, String key); // // Class<T> getType(); // // T getValue(); // // @SuppressWarnings({ "rawtypes" }) // enum DeclaredTypes { // BOOL(new Class[] {Boolean.class, boolean.class }), // INT(new Class[] {Integer.class, int.class }), // FLOAT(new Class[] {Float.class, float.class }), // STRING(new Class[] {String.class }), // ACTION(new Class[] {Method.class }); // // private Class[] mHandledTypes; // // DeclaredTypes(Class[] types) { // mHandledTypes = types; // } // // public boolean contains(Class cls) { // for (Class clazz : mHandledTypes) { // if (clazz.equals(cls)) { // return true; // } // } // return false; // } // // public ValueBinder getBinder(Object fieldOrMethod) { // switch (this) { // case BOOL: // return new BooleanValueBinder((Field) fieldOrMethod); // case INT: // return new IntegerValueBinder((Field) fieldOrMethod); // case FLOAT: // return new FloatValueBinder((Field) fieldOrMethod); // case STRING: // return new StringValueBinder((Field) fieldOrMethod); // case ACTION: // return new ActionBinder((Method) fieldOrMethod); // default: // return null; // } // } // } // } // // Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/exceptions/FailedToBuildPreferenceException.java // public class FailedToBuildPreferenceException extends RuntimeException { // public static final long serialVersionUID = 0L; // // public FailedToBuildPreferenceException(String reason) { // super(reason); // } // // public FailedToBuildPreferenceException(String reason, Throwable rootCause) { // super(reason, rootCause); // } // } // // Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/types/AbstractTweakableValue.java // public abstract class AbstractTweakableValue<T> implements TweakableValue<T> { // public static final String BUNDLE_KEYATTR_KEY = "key"; // public static final String BUNDLE_TITLE_KEY = "title"; // public static final String BUNDLE_SUMMARY_KEY = "summary"; // // public static final String BUNDLE_CATEGORY_KEY = "category"; // public static final String BUNDLE_SCREEN_KEY = "screen"; // // public static final String ROOT_SCREEN_KEY = "tweakable-values-root-screen"; // public static final String ROOT_CATEGORY_KEY = "tweakable-values-root-category"; // // // protected String mTitle; // protected String mKey; // protected String mSummary; // protected String mCategory; // protected String mScreen; // // @Override // public String getKey() { // return mKey; // } // // @Override // public String getTitle() { // return mTitle == null ? "ERROR" : mTitle; // } // // @Override // public String getSummary() { // return mSummary; // } // // @Override // public String getCategory() { // return mCategory; // } // // @Override // public String getScreen() { // return mScreen; // } // // public static String getDefaultString(String value, String defaultValue) { // if (value == null || value.isEmpty()) { // return defaultValue; // } // return value; // } // } // Path: tweakable/src/main/java/com/jackwink/tweakable/Tweakable.java import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import com.jackwink.tweakable.binders.ActionBinder; import com.jackwink.tweakable.binders.ValueBinder; import com.jackwink.tweakable.exceptions.FailedToBuildPreferenceException; import com.jackwink.tweakable.types.AbstractTweakableValue; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.util.LinkedHashMap; import java.util.Map; } protected static synchronized void resetShakeListener() { if (!mOnShakeEnabled) { Log.w(TAG, "Shake detection not enabled!"); } mShakeDetector.reset(); } protected static synchronized boolean isShakeListenerEnabled() { return mOnShakeEnabled; } protected static synchronized void startShakeListener() { if (mOnShakeEnabled) { Log.w(TAG, "Shake detection not enabled!"); } mShakeDetector.listen(); } /** * <p>Returns an instance of the generated preferences class, or throws an exception if it can't * be found. For internal use only!</p> * @return The generated {@link PreferenceAnnotationProcessor} */ protected static PreferenceAnnotationProcessor getPreferences() { try { return (PreferenceAnnotationProcessor) Class.forName("com.jackwink.tweakable.GeneratedPreferences").newInstance(); } catch (Exception e) {
throw new FailedToBuildPreferenceException("Could not find generated preferences.", e);
JackWink/tweakable
tweakable/src/main/java/com/jackwink/tweakable/binders/IntegerValueBinder.java
// Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/exceptions/FailedToBuildPreferenceException.java // public class FailedToBuildPreferenceException extends RuntimeException { // public static final long serialVersionUID = 0L; // // public FailedToBuildPreferenceException(String reason) { // super(reason); // } // // public FailedToBuildPreferenceException(String reason, Throwable rootCause) { // super(reason, rootCause); // } // }
import android.content.SharedPreferences; import com.jackwink.tweakable.exceptions.FailedToBuildPreferenceException; import java.lang.reflect.Field;
package com.jackwink.tweakable.binders; /** * Binds an integer value to a static field */ public class IntegerValueBinder extends AbstractValueBinder<Integer> { public IntegerValueBinder(Field field) { mField = field; } @Override public Class<Integer> getType() { return Integer.class; } @Override public Integer getValue() { try { if (mField.getType().equals(int.class)) { return mField.getInt(null); } else if (mField.getType().equals(Integer.class)) { return (Integer) mField.get(null); }
// Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/exceptions/FailedToBuildPreferenceException.java // public class FailedToBuildPreferenceException extends RuntimeException { // public static final long serialVersionUID = 0L; // // public FailedToBuildPreferenceException(String reason) { // super(reason); // } // // public FailedToBuildPreferenceException(String reason, Throwable rootCause) { // super(reason, rootCause); // } // } // Path: tweakable/src/main/java/com/jackwink/tweakable/binders/IntegerValueBinder.java import android.content.SharedPreferences; import com.jackwink.tweakable.exceptions.FailedToBuildPreferenceException; import java.lang.reflect.Field; package com.jackwink.tweakable.binders; /** * Binds an integer value to a static field */ public class IntegerValueBinder extends AbstractValueBinder<Integer> { public IntegerValueBinder(Field field) { mField = field; } @Override public Class<Integer> getType() { return Integer.class; } @Override public Integer getValue() { try { if (mField.getType().equals(int.class)) { return mField.getInt(null); } else if (mField.getType().equals(Integer.class)) { return (Integer) mField.get(null); }
throw new FailedToBuildPreferenceException(
JackWink/tweakable
tweakable/src/main/java/com/jackwink/tweakable/builders/BooleanPreferenceBuilder.java
// Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/types/TweakableBoolean.java // public class TweakableBoolean extends AbstractTweakableValue<Boolean> { // private static final String TAG = TweakableBoolean.class.getSimpleName(); // // public static final String BUNDLE_ON_LABEL_KEY = "switch_text_on"; // public static final String BUNDLE_OFF_LABEL_KEY = "switch_text_off"; // public static final String BUNDLE_ON_SUMMARY_KEY = "summary_on"; // public static final String BUNDLE_OFF_SUMMARY_KEY = "summary_off"; // // private TwkBoolean mParsedAnnotation; // // // public String getOnLabel() { // return mParsedAnnotation.onLabel(); // } // // public String getOffLabel() { // return mParsedAnnotation.offLabel(); // } // // public String getOnSummary() { // return mParsedAnnotation.onSummary(); // } // // public String getOffSummary() { // return mParsedAnnotation.offSummary(); // } // // @Override // public Class<Boolean> getType() { // return Boolean.class; // } // // public static TweakableBoolean parse(String className, String fieldName, // TwkBoolean annotation) { // TweakableBoolean returnValue = new TweakableBoolean(); // // /* Abstract Tweakable Values */ // returnValue.mKey = className + "." + fieldName; // returnValue.mTitle = getDefaultString(annotation.title(), fieldName); // returnValue.mSummary = annotation.summary(); // returnValue.mCategory = getDefaultString(annotation.category(), null); // returnValue.mScreen = getDefaultString(annotation.screen(), null); // // /* TweakableBoolean */ // returnValue.mParsedAnnotation = annotation; // return returnValue; // } // // }
import android.preference.Preference; import android.preference.SwitchPreference; import com.jackwink.tweakable.types.TweakableBoolean;
package com.jackwink.tweakable.builders; /** * */ @SuppressWarnings({ "rawtypes" }) public class BooleanPreferenceBuilder extends BasePreferenceBuilder<Preference> { private static final String TAG = PreferenceFactory.class.getSimpleName(); public BooleanPreferenceBuilder() { } @Override public Class[] getHandledTypes() { return new Class[] {Boolean.class, boolean.class }; } /** * Builds a SwitchPreference object */ @Override public Preference build() { SwitchPreference preference = null; preference = build(SwitchPreference.class, true); preference.setChecked((boolean) mDefaultValue); preference.setSummaryOn((String)
// Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/types/TweakableBoolean.java // public class TweakableBoolean extends AbstractTweakableValue<Boolean> { // private static final String TAG = TweakableBoolean.class.getSimpleName(); // // public static final String BUNDLE_ON_LABEL_KEY = "switch_text_on"; // public static final String BUNDLE_OFF_LABEL_KEY = "switch_text_off"; // public static final String BUNDLE_ON_SUMMARY_KEY = "summary_on"; // public static final String BUNDLE_OFF_SUMMARY_KEY = "summary_off"; // // private TwkBoolean mParsedAnnotation; // // // public String getOnLabel() { // return mParsedAnnotation.onLabel(); // } // // public String getOffLabel() { // return mParsedAnnotation.offLabel(); // } // // public String getOnSummary() { // return mParsedAnnotation.onSummary(); // } // // public String getOffSummary() { // return mParsedAnnotation.offSummary(); // } // // @Override // public Class<Boolean> getType() { // return Boolean.class; // } // // public static TweakableBoolean parse(String className, String fieldName, // TwkBoolean annotation) { // TweakableBoolean returnValue = new TweakableBoolean(); // // /* Abstract Tweakable Values */ // returnValue.mKey = className + "." + fieldName; // returnValue.mTitle = getDefaultString(annotation.title(), fieldName); // returnValue.mSummary = annotation.summary(); // returnValue.mCategory = getDefaultString(annotation.category(), null); // returnValue.mScreen = getDefaultString(annotation.screen(), null); // // /* TweakableBoolean */ // returnValue.mParsedAnnotation = annotation; // return returnValue; // } // // } // Path: tweakable/src/main/java/com/jackwink/tweakable/builders/BooleanPreferenceBuilder.java import android.preference.Preference; import android.preference.SwitchPreference; import com.jackwink.tweakable.types.TweakableBoolean; package com.jackwink.tweakable.builders; /** * */ @SuppressWarnings({ "rawtypes" }) public class BooleanPreferenceBuilder extends BasePreferenceBuilder<Preference> { private static final String TAG = PreferenceFactory.class.getSimpleName(); public BooleanPreferenceBuilder() { } @Override public Class[] getHandledTypes() { return new Class[] {Boolean.class, boolean.class }; } /** * Builds a SwitchPreference object */ @Override public Preference build() { SwitchPreference preference = null; preference = build(SwitchPreference.class, true); preference.setChecked((boolean) mDefaultValue); preference.setSummaryOn((String)
getOptionalAttribute(TweakableBoolean.BUNDLE_ON_SUMMARY_KEY));
JackWink/tweakable
tweakable/src/main/java/com/jackwink/tweakable/builders/IntegerPreferenceBuilder.java
// Path: tweakable/src/main/java/com/jackwink/tweakable/controls/NumberPickerPreference.java // public class NumberPickerPreference extends DialogPreference { // private static final String TAG = NumberPickerPreference.class.getSimpleName(); // // private static final int MIN_VALUE = 0; // private static final int MAX_VALUE = 100; // private static final boolean WRAP_SELECTOR_WHEEL = false; // // private int mSelectedValue; // private int mMinValue = MIN_VALUE; // private int mMaxValue = MAX_VALUE; // private int mOriginalValue; // private boolean mWrapSelectorWheel = WRAP_SELECTOR_WHEEL; // private NumberPicker mNumberPicker; // // public NumberPickerPreference(final Context context) { // super(context, null); // } // // public void setMinValue(int value) { // mMinValue = value; // } // // public void setMaxValue(int value) { // mMaxValue = value; // } // // public void setWraps(boolean shouldWrap) { // mWrapSelectorWheel = shouldWrap; // } // // @Override // protected void onSetInitialValue(final boolean restoreValue, final Object defaultValue) { // setSelectedValue(restoreValue ? getPersistedInt(0) : (Integer) defaultValue, false); // mOriginalValue = mSelectedValue; // } // // @Override // protected Object onGetDefaultValue(final TypedArray a, final int index) { // return a.getInteger(index, 0); // } // // @Override // protected void onPrepareDialogBuilder(final Builder builder) { // super.onPrepareDialogBuilder(builder); // mNumberPicker = new NumberPicker(getContext()); // mNumberPicker.setMinValue(mMinValue); // mNumberPicker.setMaxValue(mMaxValue); // mNumberPicker.setValue(mSelectedValue); // mNumberPicker.setWrapSelectorWheel(mWrapSelectorWheel); // mNumberPicker.setLayoutParams(new LinearLayout.LayoutParams( // LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); // // for (int i = 0; i < mNumberPicker.getChildCount(); i++) { // View v = mNumberPicker.getChildAt(i); // if (v instanceof EditText) { // v.setOnKeyListener(new KeyListener()); // } // } // final LinearLayout linearLayout = new LinearLayout(this.getContext()); // linearLayout.setLayoutParams(new LinearLayout.LayoutParams( // LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); // linearLayout.setGravity(Gravity.CENTER); // linearLayout.addView(mNumberPicker); // // builder.setView(linearLayout); // } // // @Override // protected void onDialogClosed(final boolean positiveResult) { // if (positiveResult && shouldPersist()) { // setSelectedValue(mNumberPicker.getValue(), true); // } else { // setSelectedValue(getPersistedInt(mOriginalValue), false); // } // } // // private void setSelectedValue(int value, boolean persist) { // mSelectedValue = value; // if (persist) { // persistInt(mSelectedValue); // } // setSummary(Integer.toString(mSelectedValue)); // } // // private class KeyListener implements View.OnKeyListener { // @Override // public boolean onKey(View v, int keyCode, KeyEvent event) { // if (event.getAction() == KeyEvent.ACTION_UP) { // String number = ((EditText) v).getText().toString(); // if (number.isEmpty()) { // setSelectedValue(mMinValue, false); // } else { // int currentValue = Integer.valueOf(number); // if (currentValue >= mMinValue) { // setSelectedValue(Integer.valueOf(number), false); // mNumberPicker.setValue(mSelectedValue); // } else { // setSelectedValue(mMinValue, false); // } // } // } // return false; // } // } // // } // // Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/types/TweakableInteger.java // public class TweakableInteger extends AbstractTweakableValue<Integer> { // // public static final String BUNDLE_MIN_VALUE_KEY = "min_value"; // public static final String BUNDLE_MAX_VALUE_KEY = "max_value"; // // private TwkInteger mParsedAnnotation; // // public Integer getMaxValue() { // return mParsedAnnotation.maxValue(); // } // // public Integer getMinValue() { // return mParsedAnnotation.minValue(); // } // // @Override // public Class<Integer> getType() { // return Integer.class; // } // // public static TweakableInteger parse(String className, String fieldName, // TwkInteger annotation) { // TweakableInteger returnValue = new TweakableInteger(); // // /* Abstract Tweakable Values */ // returnValue.mKey = className + "." + fieldName; // returnValue.mTitle = getDefaultString(annotation.title(), fieldName); // returnValue.mSummary = annotation.summary(); // returnValue.mCategory = getDefaultString(annotation.category(), null); // returnValue.mScreen = getDefaultString(annotation.screen(), null); // // /* TweakableInteger */ // returnValue.mParsedAnnotation = annotation; // return returnValue; // } // }
import android.preference.Preference; import com.jackwink.tweakable.controls.NumberPickerPreference; import com.jackwink.tweakable.types.TweakableInteger;
package com.jackwink.tweakable.builders; /** * */ @SuppressWarnings({ "rawtypes" }) public class IntegerPreferenceBuilder extends BasePreferenceBuilder<Preference> { @Override public Class[] getHandledTypes() { return new Class[] {Integer.class, int.class }; } @Override public Preference build() {
// Path: tweakable/src/main/java/com/jackwink/tweakable/controls/NumberPickerPreference.java // public class NumberPickerPreference extends DialogPreference { // private static final String TAG = NumberPickerPreference.class.getSimpleName(); // // private static final int MIN_VALUE = 0; // private static final int MAX_VALUE = 100; // private static final boolean WRAP_SELECTOR_WHEEL = false; // // private int mSelectedValue; // private int mMinValue = MIN_VALUE; // private int mMaxValue = MAX_VALUE; // private int mOriginalValue; // private boolean mWrapSelectorWheel = WRAP_SELECTOR_WHEEL; // private NumberPicker mNumberPicker; // // public NumberPickerPreference(final Context context) { // super(context, null); // } // // public void setMinValue(int value) { // mMinValue = value; // } // // public void setMaxValue(int value) { // mMaxValue = value; // } // // public void setWraps(boolean shouldWrap) { // mWrapSelectorWheel = shouldWrap; // } // // @Override // protected void onSetInitialValue(final boolean restoreValue, final Object defaultValue) { // setSelectedValue(restoreValue ? getPersistedInt(0) : (Integer) defaultValue, false); // mOriginalValue = mSelectedValue; // } // // @Override // protected Object onGetDefaultValue(final TypedArray a, final int index) { // return a.getInteger(index, 0); // } // // @Override // protected void onPrepareDialogBuilder(final Builder builder) { // super.onPrepareDialogBuilder(builder); // mNumberPicker = new NumberPicker(getContext()); // mNumberPicker.setMinValue(mMinValue); // mNumberPicker.setMaxValue(mMaxValue); // mNumberPicker.setValue(mSelectedValue); // mNumberPicker.setWrapSelectorWheel(mWrapSelectorWheel); // mNumberPicker.setLayoutParams(new LinearLayout.LayoutParams( // LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); // // for (int i = 0; i < mNumberPicker.getChildCount(); i++) { // View v = mNumberPicker.getChildAt(i); // if (v instanceof EditText) { // v.setOnKeyListener(new KeyListener()); // } // } // final LinearLayout linearLayout = new LinearLayout(this.getContext()); // linearLayout.setLayoutParams(new LinearLayout.LayoutParams( // LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); // linearLayout.setGravity(Gravity.CENTER); // linearLayout.addView(mNumberPicker); // // builder.setView(linearLayout); // } // // @Override // protected void onDialogClosed(final boolean positiveResult) { // if (positiveResult && shouldPersist()) { // setSelectedValue(mNumberPicker.getValue(), true); // } else { // setSelectedValue(getPersistedInt(mOriginalValue), false); // } // } // // private void setSelectedValue(int value, boolean persist) { // mSelectedValue = value; // if (persist) { // persistInt(mSelectedValue); // } // setSummary(Integer.toString(mSelectedValue)); // } // // private class KeyListener implements View.OnKeyListener { // @Override // public boolean onKey(View v, int keyCode, KeyEvent event) { // if (event.getAction() == KeyEvent.ACTION_UP) { // String number = ((EditText) v).getText().toString(); // if (number.isEmpty()) { // setSelectedValue(mMinValue, false); // } else { // int currentValue = Integer.valueOf(number); // if (currentValue >= mMinValue) { // setSelectedValue(Integer.valueOf(number), false); // mNumberPicker.setValue(mSelectedValue); // } else { // setSelectedValue(mMinValue, false); // } // } // } // return false; // } // } // // } // // Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/types/TweakableInteger.java // public class TweakableInteger extends AbstractTweakableValue<Integer> { // // public static final String BUNDLE_MIN_VALUE_KEY = "min_value"; // public static final String BUNDLE_MAX_VALUE_KEY = "max_value"; // // private TwkInteger mParsedAnnotation; // // public Integer getMaxValue() { // return mParsedAnnotation.maxValue(); // } // // public Integer getMinValue() { // return mParsedAnnotation.minValue(); // } // // @Override // public Class<Integer> getType() { // return Integer.class; // } // // public static TweakableInteger parse(String className, String fieldName, // TwkInteger annotation) { // TweakableInteger returnValue = new TweakableInteger(); // // /* Abstract Tweakable Values */ // returnValue.mKey = className + "." + fieldName; // returnValue.mTitle = getDefaultString(annotation.title(), fieldName); // returnValue.mSummary = annotation.summary(); // returnValue.mCategory = getDefaultString(annotation.category(), null); // returnValue.mScreen = getDefaultString(annotation.screen(), null); // // /* TweakableInteger */ // returnValue.mParsedAnnotation = annotation; // return returnValue; // } // } // Path: tweakable/src/main/java/com/jackwink/tweakable/builders/IntegerPreferenceBuilder.java import android.preference.Preference; import com.jackwink.tweakable.controls.NumberPickerPreference; import com.jackwink.tweakable.types.TweakableInteger; package com.jackwink.tweakable.builders; /** * */ @SuppressWarnings({ "rawtypes" }) public class IntegerPreferenceBuilder extends BasePreferenceBuilder<Preference> { @Override public Class[] getHandledTypes() { return new Class[] {Integer.class, int.class }; } @Override public Preference build() {
NumberPickerPreference preference = build(NumberPickerPreference.class, true);
JackWink/tweakable
tweakable/src/main/java/com/jackwink/tweakable/builders/IntegerPreferenceBuilder.java
// Path: tweakable/src/main/java/com/jackwink/tweakable/controls/NumberPickerPreference.java // public class NumberPickerPreference extends DialogPreference { // private static final String TAG = NumberPickerPreference.class.getSimpleName(); // // private static final int MIN_VALUE = 0; // private static final int MAX_VALUE = 100; // private static final boolean WRAP_SELECTOR_WHEEL = false; // // private int mSelectedValue; // private int mMinValue = MIN_VALUE; // private int mMaxValue = MAX_VALUE; // private int mOriginalValue; // private boolean mWrapSelectorWheel = WRAP_SELECTOR_WHEEL; // private NumberPicker mNumberPicker; // // public NumberPickerPreference(final Context context) { // super(context, null); // } // // public void setMinValue(int value) { // mMinValue = value; // } // // public void setMaxValue(int value) { // mMaxValue = value; // } // // public void setWraps(boolean shouldWrap) { // mWrapSelectorWheel = shouldWrap; // } // // @Override // protected void onSetInitialValue(final boolean restoreValue, final Object defaultValue) { // setSelectedValue(restoreValue ? getPersistedInt(0) : (Integer) defaultValue, false); // mOriginalValue = mSelectedValue; // } // // @Override // protected Object onGetDefaultValue(final TypedArray a, final int index) { // return a.getInteger(index, 0); // } // // @Override // protected void onPrepareDialogBuilder(final Builder builder) { // super.onPrepareDialogBuilder(builder); // mNumberPicker = new NumberPicker(getContext()); // mNumberPicker.setMinValue(mMinValue); // mNumberPicker.setMaxValue(mMaxValue); // mNumberPicker.setValue(mSelectedValue); // mNumberPicker.setWrapSelectorWheel(mWrapSelectorWheel); // mNumberPicker.setLayoutParams(new LinearLayout.LayoutParams( // LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); // // for (int i = 0; i < mNumberPicker.getChildCount(); i++) { // View v = mNumberPicker.getChildAt(i); // if (v instanceof EditText) { // v.setOnKeyListener(new KeyListener()); // } // } // final LinearLayout linearLayout = new LinearLayout(this.getContext()); // linearLayout.setLayoutParams(new LinearLayout.LayoutParams( // LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); // linearLayout.setGravity(Gravity.CENTER); // linearLayout.addView(mNumberPicker); // // builder.setView(linearLayout); // } // // @Override // protected void onDialogClosed(final boolean positiveResult) { // if (positiveResult && shouldPersist()) { // setSelectedValue(mNumberPicker.getValue(), true); // } else { // setSelectedValue(getPersistedInt(mOriginalValue), false); // } // } // // private void setSelectedValue(int value, boolean persist) { // mSelectedValue = value; // if (persist) { // persistInt(mSelectedValue); // } // setSummary(Integer.toString(mSelectedValue)); // } // // private class KeyListener implements View.OnKeyListener { // @Override // public boolean onKey(View v, int keyCode, KeyEvent event) { // if (event.getAction() == KeyEvent.ACTION_UP) { // String number = ((EditText) v).getText().toString(); // if (number.isEmpty()) { // setSelectedValue(mMinValue, false); // } else { // int currentValue = Integer.valueOf(number); // if (currentValue >= mMinValue) { // setSelectedValue(Integer.valueOf(number), false); // mNumberPicker.setValue(mSelectedValue); // } else { // setSelectedValue(mMinValue, false); // } // } // } // return false; // } // } // // } // // Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/types/TweakableInteger.java // public class TweakableInteger extends AbstractTweakableValue<Integer> { // // public static final String BUNDLE_MIN_VALUE_KEY = "min_value"; // public static final String BUNDLE_MAX_VALUE_KEY = "max_value"; // // private TwkInteger mParsedAnnotation; // // public Integer getMaxValue() { // return mParsedAnnotation.maxValue(); // } // // public Integer getMinValue() { // return mParsedAnnotation.minValue(); // } // // @Override // public Class<Integer> getType() { // return Integer.class; // } // // public static TweakableInteger parse(String className, String fieldName, // TwkInteger annotation) { // TweakableInteger returnValue = new TweakableInteger(); // // /* Abstract Tweakable Values */ // returnValue.mKey = className + "." + fieldName; // returnValue.mTitle = getDefaultString(annotation.title(), fieldName); // returnValue.mSummary = annotation.summary(); // returnValue.mCategory = getDefaultString(annotation.category(), null); // returnValue.mScreen = getDefaultString(annotation.screen(), null); // // /* TweakableInteger */ // returnValue.mParsedAnnotation = annotation; // return returnValue; // } // }
import android.preference.Preference; import com.jackwink.tweakable.controls.NumberPickerPreference; import com.jackwink.tweakable.types.TweakableInteger;
package com.jackwink.tweakable.builders; /** * */ @SuppressWarnings({ "rawtypes" }) public class IntegerPreferenceBuilder extends BasePreferenceBuilder<Preference> { @Override public Class[] getHandledTypes() { return new Class[] {Integer.class, int.class }; } @Override public Preference build() { NumberPickerPreference preference = build(NumberPickerPreference.class, true); preference.setDialogMessage((String) getRequiredAttribute(BUNDLE_SUMMARY_KEY)); preference.setWraps(true); preference.setMaxValue((Integer)
// Path: tweakable/src/main/java/com/jackwink/tweakable/controls/NumberPickerPreference.java // public class NumberPickerPreference extends DialogPreference { // private static final String TAG = NumberPickerPreference.class.getSimpleName(); // // private static final int MIN_VALUE = 0; // private static final int MAX_VALUE = 100; // private static final boolean WRAP_SELECTOR_WHEEL = false; // // private int mSelectedValue; // private int mMinValue = MIN_VALUE; // private int mMaxValue = MAX_VALUE; // private int mOriginalValue; // private boolean mWrapSelectorWheel = WRAP_SELECTOR_WHEEL; // private NumberPicker mNumberPicker; // // public NumberPickerPreference(final Context context) { // super(context, null); // } // // public void setMinValue(int value) { // mMinValue = value; // } // // public void setMaxValue(int value) { // mMaxValue = value; // } // // public void setWraps(boolean shouldWrap) { // mWrapSelectorWheel = shouldWrap; // } // // @Override // protected void onSetInitialValue(final boolean restoreValue, final Object defaultValue) { // setSelectedValue(restoreValue ? getPersistedInt(0) : (Integer) defaultValue, false); // mOriginalValue = mSelectedValue; // } // // @Override // protected Object onGetDefaultValue(final TypedArray a, final int index) { // return a.getInteger(index, 0); // } // // @Override // protected void onPrepareDialogBuilder(final Builder builder) { // super.onPrepareDialogBuilder(builder); // mNumberPicker = new NumberPicker(getContext()); // mNumberPicker.setMinValue(mMinValue); // mNumberPicker.setMaxValue(mMaxValue); // mNumberPicker.setValue(mSelectedValue); // mNumberPicker.setWrapSelectorWheel(mWrapSelectorWheel); // mNumberPicker.setLayoutParams(new LinearLayout.LayoutParams( // LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); // // for (int i = 0; i < mNumberPicker.getChildCount(); i++) { // View v = mNumberPicker.getChildAt(i); // if (v instanceof EditText) { // v.setOnKeyListener(new KeyListener()); // } // } // final LinearLayout linearLayout = new LinearLayout(this.getContext()); // linearLayout.setLayoutParams(new LinearLayout.LayoutParams( // LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); // linearLayout.setGravity(Gravity.CENTER); // linearLayout.addView(mNumberPicker); // // builder.setView(linearLayout); // } // // @Override // protected void onDialogClosed(final boolean positiveResult) { // if (positiveResult && shouldPersist()) { // setSelectedValue(mNumberPicker.getValue(), true); // } else { // setSelectedValue(getPersistedInt(mOriginalValue), false); // } // } // // private void setSelectedValue(int value, boolean persist) { // mSelectedValue = value; // if (persist) { // persistInt(mSelectedValue); // } // setSummary(Integer.toString(mSelectedValue)); // } // // private class KeyListener implements View.OnKeyListener { // @Override // public boolean onKey(View v, int keyCode, KeyEvent event) { // if (event.getAction() == KeyEvent.ACTION_UP) { // String number = ((EditText) v).getText().toString(); // if (number.isEmpty()) { // setSelectedValue(mMinValue, false); // } else { // int currentValue = Integer.valueOf(number); // if (currentValue >= mMinValue) { // setSelectedValue(Integer.valueOf(number), false); // mNumberPicker.setValue(mSelectedValue); // } else { // setSelectedValue(mMinValue, false); // } // } // } // return false; // } // } // // } // // Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/types/TweakableInteger.java // public class TweakableInteger extends AbstractTweakableValue<Integer> { // // public static final String BUNDLE_MIN_VALUE_KEY = "min_value"; // public static final String BUNDLE_MAX_VALUE_KEY = "max_value"; // // private TwkInteger mParsedAnnotation; // // public Integer getMaxValue() { // return mParsedAnnotation.maxValue(); // } // // public Integer getMinValue() { // return mParsedAnnotation.minValue(); // } // // @Override // public Class<Integer> getType() { // return Integer.class; // } // // public static TweakableInteger parse(String className, String fieldName, // TwkInteger annotation) { // TweakableInteger returnValue = new TweakableInteger(); // // /* Abstract Tweakable Values */ // returnValue.mKey = className + "." + fieldName; // returnValue.mTitle = getDefaultString(annotation.title(), fieldName); // returnValue.mSummary = annotation.summary(); // returnValue.mCategory = getDefaultString(annotation.category(), null); // returnValue.mScreen = getDefaultString(annotation.screen(), null); // // /* TweakableInteger */ // returnValue.mParsedAnnotation = annotation; // return returnValue; // } // } // Path: tweakable/src/main/java/com/jackwink/tweakable/builders/IntegerPreferenceBuilder.java import android.preference.Preference; import com.jackwink.tweakable.controls.NumberPickerPreference; import com.jackwink.tweakable.types.TweakableInteger; package com.jackwink.tweakable.builders; /** * */ @SuppressWarnings({ "rawtypes" }) public class IntegerPreferenceBuilder extends BasePreferenceBuilder<Preference> { @Override public Class[] getHandledTypes() { return new Class[] {Integer.class, int.class }; } @Override public Preference build() { NumberPickerPreference preference = build(NumberPickerPreference.class, true); preference.setDialogMessage((String) getRequiredAttribute(BUNDLE_SUMMARY_KEY)); preference.setWraps(true); preference.setMaxValue((Integer)
getRequiredAttribute(TweakableInteger.BUNDLE_MAX_VALUE_KEY));
JackWink/tweakable
tweakable/src/main/java/com/jackwink/tweakable/builders/StringPreferenceBuilder.java
// Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/types/TweakableString.java // public class TweakableString extends AbstractTweakableValue<String> { // // public static final String BUNDLE_OPTIONS_KEY = "options"; // // private TwkString mParsedAnnotation; // // @Override // public Class<String> getType() { // return String.class; // } // // public String[] getOptions() { // return mParsedAnnotation.options(); // } // // public static TweakableString parse(String className, String fieldName, TwkString annotation) { // TweakableString returnValue = new TweakableString(); // // /* Abstract Tweakable Values */ // returnValue.mKey = className + "." + fieldName; // returnValue.mTitle = getDefaultString(annotation.title(), fieldName); // returnValue.mSummary = annotation.summary(); // returnValue.mCategory = getDefaultString(annotation.category(), null); // returnValue.mScreen = getDefaultString(annotation.screen(), null); // // /* TweakableString */ // returnValue.mParsedAnnotation = annotation; // // return returnValue; // } // // }
import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import com.jackwink.tweakable.types.TweakableString;
package com.jackwink.tweakable.builders; /** * */ @SuppressWarnings({ "rawtypes" }) public class StringPreferenceBuilder extends BasePreferenceBuilder<Preference> { @Override public Class[] getHandledTypes() { return new Class[] {String.class }; } @Override public Preference build() { Preference preference = null;
// Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/types/TweakableString.java // public class TweakableString extends AbstractTweakableValue<String> { // // public static final String BUNDLE_OPTIONS_KEY = "options"; // // private TwkString mParsedAnnotation; // // @Override // public Class<String> getType() { // return String.class; // } // // public String[] getOptions() { // return mParsedAnnotation.options(); // } // // public static TweakableString parse(String className, String fieldName, TwkString annotation) { // TweakableString returnValue = new TweakableString(); // // /* Abstract Tweakable Values */ // returnValue.mKey = className + "." + fieldName; // returnValue.mTitle = getDefaultString(annotation.title(), fieldName); // returnValue.mSummary = annotation.summary(); // returnValue.mCategory = getDefaultString(annotation.category(), null); // returnValue.mScreen = getDefaultString(annotation.screen(), null); // // /* TweakableString */ // returnValue.mParsedAnnotation = annotation; // // return returnValue; // } // // } // Path: tweakable/src/main/java/com/jackwink/tweakable/builders/StringPreferenceBuilder.java import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import com.jackwink.tweakable.types.TweakableString; package com.jackwink.tweakable.builders; /** * */ @SuppressWarnings({ "rawtypes" }) public class StringPreferenceBuilder extends BasePreferenceBuilder<Preference> { @Override public Class[] getHandledTypes() { return new Class[] {String.class }; } @Override public Preference build() { Preference preference = null;
String[] options = (String[]) getRequiredAttribute(TweakableString.BUNDLE_OPTIONS_KEY);
JackWink/tweakable
tweakable/src/main/java/com/jackwink/tweakable/builders/BasePreferenceBuilder.java
// Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/exceptions/FailedToBuildPreferenceException.java // public class FailedToBuildPreferenceException extends RuntimeException { // public static final long serialVersionUID = 0L; // // public FailedToBuildPreferenceException(String reason) { // super(reason); // } // // public FailedToBuildPreferenceException(String reason, Throwable rootCause) { // super(reason, rootCause); // } // } // // Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/types/AbstractTweakableValue.java // public abstract class AbstractTweakableValue<T> implements TweakableValue<T> { // public static final String BUNDLE_KEYATTR_KEY = "key"; // public static final String BUNDLE_TITLE_KEY = "title"; // public static final String BUNDLE_SUMMARY_KEY = "summary"; // // public static final String BUNDLE_CATEGORY_KEY = "category"; // public static final String BUNDLE_SCREEN_KEY = "screen"; // // public static final String ROOT_SCREEN_KEY = "tweakable-values-root-screen"; // public static final String ROOT_CATEGORY_KEY = "tweakable-values-root-category"; // // // protected String mTitle; // protected String mKey; // protected String mSummary; // protected String mCategory; // protected String mScreen; // // @Override // public String getKey() { // return mKey; // } // // @Override // public String getTitle() { // return mTitle == null ? "ERROR" : mTitle; // } // // @Override // public String getSummary() { // return mSummary; // } // // @Override // public String getCategory() { // return mCategory; // } // // @Override // public String getScreen() { // return mScreen; // } // // public static String getDefaultString(String value, String defaultValue) { // if (value == null || value.isEmpty()) { // return defaultValue; // } // return value; // } // }
import android.content.Context; import android.os.Bundle; import android.preference.DialogPreference; import android.preference.Preference; import android.util.Log; import com.jackwink.tweakable.exceptions.FailedToBuildPreferenceException; import com.jackwink.tweakable.types.AbstractTweakableValue; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Map;
package com.jackwink.tweakable.builders; /** * Contains convenience methods for any {@link PreferenceBuilder} subclass */ @SuppressWarnings({ "rawtypes", "unchecked" }) public abstract class BasePreferenceBuilder<T extends Preference> implements PreferenceBuilder<T> { private static final String TAG = BasePreferenceBuilder.class.getSimpleName();
// Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/exceptions/FailedToBuildPreferenceException.java // public class FailedToBuildPreferenceException extends RuntimeException { // public static final long serialVersionUID = 0L; // // public FailedToBuildPreferenceException(String reason) { // super(reason); // } // // public FailedToBuildPreferenceException(String reason, Throwable rootCause) { // super(reason, rootCause); // } // } // // Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/types/AbstractTweakableValue.java // public abstract class AbstractTweakableValue<T> implements TweakableValue<T> { // public static final String BUNDLE_KEYATTR_KEY = "key"; // public static final String BUNDLE_TITLE_KEY = "title"; // public static final String BUNDLE_SUMMARY_KEY = "summary"; // // public static final String BUNDLE_CATEGORY_KEY = "category"; // public static final String BUNDLE_SCREEN_KEY = "screen"; // // public static final String ROOT_SCREEN_KEY = "tweakable-values-root-screen"; // public static final String ROOT_CATEGORY_KEY = "tweakable-values-root-category"; // // // protected String mTitle; // protected String mKey; // protected String mSummary; // protected String mCategory; // protected String mScreen; // // @Override // public String getKey() { // return mKey; // } // // @Override // public String getTitle() { // return mTitle == null ? "ERROR" : mTitle; // } // // @Override // public String getSummary() { // return mSummary; // } // // @Override // public String getCategory() { // return mCategory; // } // // @Override // public String getScreen() { // return mScreen; // } // // public static String getDefaultString(String value, String defaultValue) { // if (value == null || value.isEmpty()) { // return defaultValue; // } // return value; // } // } // Path: tweakable/src/main/java/com/jackwink/tweakable/builders/BasePreferenceBuilder.java import android.content.Context; import android.os.Bundle; import android.preference.DialogPreference; import android.preference.Preference; import android.util.Log; import com.jackwink.tweakable.exceptions.FailedToBuildPreferenceException; import com.jackwink.tweakable.types.AbstractTweakableValue; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Map; package com.jackwink.tweakable.builders; /** * Contains convenience methods for any {@link PreferenceBuilder} subclass */ @SuppressWarnings({ "rawtypes", "unchecked" }) public abstract class BasePreferenceBuilder<T extends Preference> implements PreferenceBuilder<T> { private static final String TAG = BasePreferenceBuilder.class.getSimpleName();
public static final String BUNDLE_KEYATTR_KEY = AbstractTweakableValue.BUNDLE_KEYATTR_KEY;
JackWink/tweakable
tweakable/src/main/java/com/jackwink/tweakable/builders/BasePreferenceBuilder.java
// Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/exceptions/FailedToBuildPreferenceException.java // public class FailedToBuildPreferenceException extends RuntimeException { // public static final long serialVersionUID = 0L; // // public FailedToBuildPreferenceException(String reason) { // super(reason); // } // // public FailedToBuildPreferenceException(String reason, Throwable rootCause) { // super(reason, rootCause); // } // } // // Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/types/AbstractTweakableValue.java // public abstract class AbstractTweakableValue<T> implements TweakableValue<T> { // public static final String BUNDLE_KEYATTR_KEY = "key"; // public static final String BUNDLE_TITLE_KEY = "title"; // public static final String BUNDLE_SUMMARY_KEY = "summary"; // // public static final String BUNDLE_CATEGORY_KEY = "category"; // public static final String BUNDLE_SCREEN_KEY = "screen"; // // public static final String ROOT_SCREEN_KEY = "tweakable-values-root-screen"; // public static final String ROOT_CATEGORY_KEY = "tweakable-values-root-category"; // // // protected String mTitle; // protected String mKey; // protected String mSummary; // protected String mCategory; // protected String mScreen; // // @Override // public String getKey() { // return mKey; // } // // @Override // public String getTitle() { // return mTitle == null ? "ERROR" : mTitle; // } // // @Override // public String getSummary() { // return mSummary; // } // // @Override // public String getCategory() { // return mCategory; // } // // @Override // public String getScreen() { // return mScreen; // } // // public static String getDefaultString(String value, String defaultValue) { // if (value == null || value.isEmpty()) { // return defaultValue; // } // return value; // } // }
import android.content.Context; import android.os.Bundle; import android.preference.DialogPreference; import android.preference.Preference; import android.util.Log; import com.jackwink.tweakable.exceptions.FailedToBuildPreferenceException; import com.jackwink.tweakable.types.AbstractTweakableValue; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Map;
package com.jackwink.tweakable.builders; /** * Contains convenience methods for any {@link PreferenceBuilder} subclass */ @SuppressWarnings({ "rawtypes", "unchecked" }) public abstract class BasePreferenceBuilder<T extends Preference> implements PreferenceBuilder<T> { private static final String TAG = BasePreferenceBuilder.class.getSimpleName(); public static final String BUNDLE_KEYATTR_KEY = AbstractTweakableValue.BUNDLE_KEYATTR_KEY; public static final String BUNDLE_TITLE_KEY = AbstractTweakableValue.BUNDLE_TITLE_KEY; public static final String BUNDLE_SUMMARY_KEY = AbstractTweakableValue.BUNDLE_SUMMARY_KEY; /* Builder set attributes */ protected Map<String, Object> mAttributeMap = null; protected Context mContext = null; protected Object mDefaultValue = null; /** * Returns the value of a given attribute or throws an exception if it's not found * * @param attributeName Name of the user-provided attribute * @return Value of the provided {@code attributeName} * @throws FailedToBuildPreferenceException if bundle is missing an attribute */ protected Object getRequiredAttribute(String attributeName) { if (!mAttributeMap.containsKey(attributeName)) {
// Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/exceptions/FailedToBuildPreferenceException.java // public class FailedToBuildPreferenceException extends RuntimeException { // public static final long serialVersionUID = 0L; // // public FailedToBuildPreferenceException(String reason) { // super(reason); // } // // public FailedToBuildPreferenceException(String reason, Throwable rootCause) { // super(reason, rootCause); // } // } // // Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/types/AbstractTweakableValue.java // public abstract class AbstractTweakableValue<T> implements TweakableValue<T> { // public static final String BUNDLE_KEYATTR_KEY = "key"; // public static final String BUNDLE_TITLE_KEY = "title"; // public static final String BUNDLE_SUMMARY_KEY = "summary"; // // public static final String BUNDLE_CATEGORY_KEY = "category"; // public static final String BUNDLE_SCREEN_KEY = "screen"; // // public static final String ROOT_SCREEN_KEY = "tweakable-values-root-screen"; // public static final String ROOT_CATEGORY_KEY = "tweakable-values-root-category"; // // // protected String mTitle; // protected String mKey; // protected String mSummary; // protected String mCategory; // protected String mScreen; // // @Override // public String getKey() { // return mKey; // } // // @Override // public String getTitle() { // return mTitle == null ? "ERROR" : mTitle; // } // // @Override // public String getSummary() { // return mSummary; // } // // @Override // public String getCategory() { // return mCategory; // } // // @Override // public String getScreen() { // return mScreen; // } // // public static String getDefaultString(String value, String defaultValue) { // if (value == null || value.isEmpty()) { // return defaultValue; // } // return value; // } // } // Path: tweakable/src/main/java/com/jackwink/tweakable/builders/BasePreferenceBuilder.java import android.content.Context; import android.os.Bundle; import android.preference.DialogPreference; import android.preference.Preference; import android.util.Log; import com.jackwink.tweakable.exceptions.FailedToBuildPreferenceException; import com.jackwink.tweakable.types.AbstractTweakableValue; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Map; package com.jackwink.tweakable.builders; /** * Contains convenience methods for any {@link PreferenceBuilder} subclass */ @SuppressWarnings({ "rawtypes", "unchecked" }) public abstract class BasePreferenceBuilder<T extends Preference> implements PreferenceBuilder<T> { private static final String TAG = BasePreferenceBuilder.class.getSimpleName(); public static final String BUNDLE_KEYATTR_KEY = AbstractTweakableValue.BUNDLE_KEYATTR_KEY; public static final String BUNDLE_TITLE_KEY = AbstractTweakableValue.BUNDLE_TITLE_KEY; public static final String BUNDLE_SUMMARY_KEY = AbstractTweakableValue.BUNDLE_SUMMARY_KEY; /* Builder set attributes */ protected Map<String, Object> mAttributeMap = null; protected Context mContext = null; protected Object mDefaultValue = null; /** * Returns the value of a given attribute or throws an exception if it's not found * * @param attributeName Name of the user-provided attribute * @return Value of the provided {@code attributeName} * @throws FailedToBuildPreferenceException if bundle is missing an attribute */ protected Object getRequiredAttribute(String attributeName) { if (!mAttributeMap.containsKey(attributeName)) {
throw new FailedToBuildPreferenceException(
JackWink/tweakable
tweakable/src/main/java/com/jackwink/tweakable/binders/FloatValueBinder.java
// Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/exceptions/FailedToBuildPreferenceException.java // public class FailedToBuildPreferenceException extends RuntimeException { // public static final long serialVersionUID = 0L; // // public FailedToBuildPreferenceException(String reason) { // super(reason); // } // // public FailedToBuildPreferenceException(String reason, Throwable rootCause) { // super(reason, rootCause); // } // }
import android.content.SharedPreferences; import com.jackwink.tweakable.exceptions.FailedToBuildPreferenceException; import java.lang.reflect.Field;
package com.jackwink.tweakable.binders; /** * */ public class FloatValueBinder extends AbstractValueBinder<Float> { public FloatValueBinder(Field field) { mField = field; } @Override public Class<Float> getType() { return Float.class; } @Override public void bindValue(SharedPreferences preferences, String key) { try { if (mField.getType().equals(Float.class)) { mField.set(null, preferences.getFloat(key, getValue())); } else if (mField.getType().equals(float.class)) { mField.setFloat(null, preferences.getFloat(key, getValue())); } } catch (IllegalAccessException e) { e.printStackTrace(); } } @Override public Float getValue() { try { if (mField.getType().equals(float.class)) { return mField.getFloat(null); } else if (mField.getType().equals(Float.class)) { return (Float) mField.get(null); }
// Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/exceptions/FailedToBuildPreferenceException.java // public class FailedToBuildPreferenceException extends RuntimeException { // public static final long serialVersionUID = 0L; // // public FailedToBuildPreferenceException(String reason) { // super(reason); // } // // public FailedToBuildPreferenceException(String reason, Throwable rootCause) { // super(reason, rootCause); // } // } // Path: tweakable/src/main/java/com/jackwink/tweakable/binders/FloatValueBinder.java import android.content.SharedPreferences; import com.jackwink.tweakable.exceptions.FailedToBuildPreferenceException; import java.lang.reflect.Field; package com.jackwink.tweakable.binders; /** * */ public class FloatValueBinder extends AbstractValueBinder<Float> { public FloatValueBinder(Field field) { mField = field; } @Override public Class<Float> getType() { return Float.class; } @Override public void bindValue(SharedPreferences preferences, String key) { try { if (mField.getType().equals(Float.class)) { mField.set(null, preferences.getFloat(key, getValue())); } else if (mField.getType().equals(float.class)) { mField.setFloat(null, preferences.getFloat(key, getValue())); } } catch (IllegalAccessException e) { e.printStackTrace(); } } @Override public Float getValue() { try { if (mField.getType().equals(float.class)) { return mField.getFloat(null); } else if (mField.getType().equals(Float.class)) { return (Float) mField.get(null); }
throw new FailedToBuildPreferenceException(
JackWink/tweakable
tweakable/src/main/java/com/jackwink/tweakable/builders/PreferenceFactory.java
// Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/exceptions/FailedToBuildPreferenceException.java // public class FailedToBuildPreferenceException extends RuntimeException { // public static final long serialVersionUID = 0L; // // public FailedToBuildPreferenceException(String reason) { // super(reason); // } // // public FailedToBuildPreferenceException(String reason, Throwable rootCause) { // super(reason, rootCause); // } // }
import android.content.Context; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.SwitchPreference; import com.jackwink.tweakable.exceptions.FailedToBuildPreferenceException; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set;
package com.jackwink.tweakable.builders; /** * Builds a {@link Preference} from a {@link Bundle} */ @SuppressWarnings({ "rawtypes" }) public class PreferenceFactory { private static final String TAG = PreferenceFactory.class.getSimpleName(); static Set<BasePreferenceBuilder<Preference>> builders = new LinkedHashSet<>(5); static { builders.add(new ActionPreferenceBuilder()); builders.add(new BooleanPreferenceBuilder()); builders.add(new FloatPreferenceBuilder()); builders.add(new IntegerPreferenceBuilder()); builders.add(new StringPreferenceBuilder()); } private Context mContext; public PreferenceFactory() { } /** * Builds a Preference object, can be any of the following types: * <ul> * <li>{@link EditTextPreference}</li> * <li>{@link ListPreference}</li> * <li>{@link com.jackwink.tweakable.controls.NumberPickerPreference}</li> * <li>{@link com.jackwink.tweakable.controls.ActionPreference}</li> * <li>{@link com.jackwink.tweakable.controls.SliderPreference}</li> * <li>{@link SwitchPreference}</li> * </ul> * @return An android preference. */ public Preference build(Class type, Context context, Map<String, Object> attributeMap, Object defaultValue) { for (BasePreferenceBuilder<Preference> builder : builders) { for (Class cls : builder.getHandledTypes()) { if (cls.equals(type)) { Preference preference = builder .setContext(context) .setBundle(attributeMap) .setDefaultValue(defaultValue) .build(); builder.reset(); return preference; } } }
// Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/exceptions/FailedToBuildPreferenceException.java // public class FailedToBuildPreferenceException extends RuntimeException { // public static final long serialVersionUID = 0L; // // public FailedToBuildPreferenceException(String reason) { // super(reason); // } // // public FailedToBuildPreferenceException(String reason, Throwable rootCause) { // super(reason, rootCause); // } // } // Path: tweakable/src/main/java/com/jackwink/tweakable/builders/PreferenceFactory.java import android.content.Context; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.SwitchPreference; import com.jackwink.tweakable.exceptions.FailedToBuildPreferenceException; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; package com.jackwink.tweakable.builders; /** * Builds a {@link Preference} from a {@link Bundle} */ @SuppressWarnings({ "rawtypes" }) public class PreferenceFactory { private static final String TAG = PreferenceFactory.class.getSimpleName(); static Set<BasePreferenceBuilder<Preference>> builders = new LinkedHashSet<>(5); static { builders.add(new ActionPreferenceBuilder()); builders.add(new BooleanPreferenceBuilder()); builders.add(new FloatPreferenceBuilder()); builders.add(new IntegerPreferenceBuilder()); builders.add(new StringPreferenceBuilder()); } private Context mContext; public PreferenceFactory() { } /** * Builds a Preference object, can be any of the following types: * <ul> * <li>{@link EditTextPreference}</li> * <li>{@link ListPreference}</li> * <li>{@link com.jackwink.tweakable.controls.NumberPickerPreference}</li> * <li>{@link com.jackwink.tweakable.controls.ActionPreference}</li> * <li>{@link com.jackwink.tweakable.controls.SliderPreference}</li> * <li>{@link SwitchPreference}</li> * </ul> * @return An android preference. */ public Preference build(Class type, Context context, Map<String, Object> attributeMap, Object defaultValue) { for (BasePreferenceBuilder<Preference> builder : builders) { for (Class cls : builder.getHandledTypes()) { if (cls.equals(type)) { Preference preference = builder .setContext(context) .setBundle(attributeMap) .setDefaultValue(defaultValue) .build(); builder.reset(); return preference; } } }
throw new FailedToBuildPreferenceException("Type: " + type.getName() + " not supported.");
JackWink/tweakable
tweakable/src/main/java/com/jackwink/tweakable/builders/PreferenceScreenBuilder.java
// Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/exceptions/FailedToBuildPreferenceScreenException.java // public class FailedToBuildPreferenceScreenException extends RuntimeException { // public static final long serialVersionUID = 0L; // // public FailedToBuildPreferenceScreenException(String reason) { // super(reason); // } // // public FailedToBuildPreferenceScreenException(String reason, Throwable rootCause) { // super(reason, rootCause); // } // } // // Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/types/AbstractTweakableValue.java // public abstract class AbstractTweakableValue<T> implements TweakableValue<T> { // public static final String BUNDLE_KEYATTR_KEY = "key"; // public static final String BUNDLE_TITLE_KEY = "title"; // public static final String BUNDLE_SUMMARY_KEY = "summary"; // // public static final String BUNDLE_CATEGORY_KEY = "category"; // public static final String BUNDLE_SCREEN_KEY = "screen"; // // public static final String ROOT_SCREEN_KEY = "tweakable-values-root-screen"; // public static final String ROOT_CATEGORY_KEY = "tweakable-values-root-category"; // // // protected String mTitle; // protected String mKey; // protected String mSummary; // protected String mCategory; // protected String mScreen; // // @Override // public String getKey() { // return mKey; // } // // @Override // public String getTitle() { // return mTitle == null ? "ERROR" : mTitle; // } // // @Override // public String getSummary() { // return mSummary; // } // // @Override // public String getCategory() { // return mCategory; // } // // @Override // public String getScreen() { // return mScreen; // } // // public static String getDefaultString(String value, String defaultValue) { // if (value == null || value.isEmpty()) { // return defaultValue; // } // return value; // } // }
import android.content.Context; import android.preference.PreferenceManager; import android.preference.PreferenceScreen; import com.jackwink.tweakable.exceptions.FailedToBuildPreferenceScreenException; import com.jackwink.tweakable.types.AbstractTweakableValue; import java.util.LinkedHashMap; import java.util.Map;
package com.jackwink.tweakable.builders; /** * Builds a {@link PreferenceScreen} */ @SuppressWarnings({ "rawtypes" }) public class PreferenceScreenBuilder extends BasePreferenceBuilder<PreferenceScreen> { private static final String TAG = PreferenceScreenBuilder.class.getSimpleName(); private PreferenceManager mPreferenceManager = null; public PreferenceScreenBuilder() { mAttributeMap = new LinkedHashMap<String, Object>(); } @Override public Class[] getHandledTypes() { return new Class[0]; } @Override public PreferenceScreenBuilder setContext(Context context) { mContext = context; return this; } @Override public PreferenceScreenBuilder setBundle(Map<String, Object> map) { mAttributeMap = map; return this; } public PreferenceScreenBuilder setPreferenceManager(PreferenceManager preferenceManager) { mPreferenceManager = preferenceManager; return this; } /** {@inheritDoc} */ public PreferenceScreen build() { if (mContext == null) {
// Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/exceptions/FailedToBuildPreferenceScreenException.java // public class FailedToBuildPreferenceScreenException extends RuntimeException { // public static final long serialVersionUID = 0L; // // public FailedToBuildPreferenceScreenException(String reason) { // super(reason); // } // // public FailedToBuildPreferenceScreenException(String reason, Throwable rootCause) { // super(reason, rootCause); // } // } // // Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/types/AbstractTweakableValue.java // public abstract class AbstractTweakableValue<T> implements TweakableValue<T> { // public static final String BUNDLE_KEYATTR_KEY = "key"; // public static final String BUNDLE_TITLE_KEY = "title"; // public static final String BUNDLE_SUMMARY_KEY = "summary"; // // public static final String BUNDLE_CATEGORY_KEY = "category"; // public static final String BUNDLE_SCREEN_KEY = "screen"; // // public static final String ROOT_SCREEN_KEY = "tweakable-values-root-screen"; // public static final String ROOT_CATEGORY_KEY = "tweakable-values-root-category"; // // // protected String mTitle; // protected String mKey; // protected String mSummary; // protected String mCategory; // protected String mScreen; // // @Override // public String getKey() { // return mKey; // } // // @Override // public String getTitle() { // return mTitle == null ? "ERROR" : mTitle; // } // // @Override // public String getSummary() { // return mSummary; // } // // @Override // public String getCategory() { // return mCategory; // } // // @Override // public String getScreen() { // return mScreen; // } // // public static String getDefaultString(String value, String defaultValue) { // if (value == null || value.isEmpty()) { // return defaultValue; // } // return value; // } // } // Path: tweakable/src/main/java/com/jackwink/tweakable/builders/PreferenceScreenBuilder.java import android.content.Context; import android.preference.PreferenceManager; import android.preference.PreferenceScreen; import com.jackwink.tweakable.exceptions.FailedToBuildPreferenceScreenException; import com.jackwink.tweakable.types.AbstractTweakableValue; import java.util.LinkedHashMap; import java.util.Map; package com.jackwink.tweakable.builders; /** * Builds a {@link PreferenceScreen} */ @SuppressWarnings({ "rawtypes" }) public class PreferenceScreenBuilder extends BasePreferenceBuilder<PreferenceScreen> { private static final String TAG = PreferenceScreenBuilder.class.getSimpleName(); private PreferenceManager mPreferenceManager = null; public PreferenceScreenBuilder() { mAttributeMap = new LinkedHashMap<String, Object>(); } @Override public Class[] getHandledTypes() { return new Class[0]; } @Override public PreferenceScreenBuilder setContext(Context context) { mContext = context; return this; } @Override public PreferenceScreenBuilder setBundle(Map<String, Object> map) { mAttributeMap = map; return this; } public PreferenceScreenBuilder setPreferenceManager(PreferenceManager preferenceManager) { mPreferenceManager = preferenceManager; return this; } /** {@inheritDoc} */ public PreferenceScreen build() { if (mContext == null) {
throw new FailedToBuildPreferenceScreenException(
JackWink/tweakable
tweakable/src/main/java/com/jackwink/tweakable/builders/PreferenceScreenBuilder.java
// Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/exceptions/FailedToBuildPreferenceScreenException.java // public class FailedToBuildPreferenceScreenException extends RuntimeException { // public static final long serialVersionUID = 0L; // // public FailedToBuildPreferenceScreenException(String reason) { // super(reason); // } // // public FailedToBuildPreferenceScreenException(String reason, Throwable rootCause) { // super(reason, rootCause); // } // } // // Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/types/AbstractTweakableValue.java // public abstract class AbstractTweakableValue<T> implements TweakableValue<T> { // public static final String BUNDLE_KEYATTR_KEY = "key"; // public static final String BUNDLE_TITLE_KEY = "title"; // public static final String BUNDLE_SUMMARY_KEY = "summary"; // // public static final String BUNDLE_CATEGORY_KEY = "category"; // public static final String BUNDLE_SCREEN_KEY = "screen"; // // public static final String ROOT_SCREEN_KEY = "tweakable-values-root-screen"; // public static final String ROOT_CATEGORY_KEY = "tweakable-values-root-category"; // // // protected String mTitle; // protected String mKey; // protected String mSummary; // protected String mCategory; // protected String mScreen; // // @Override // public String getKey() { // return mKey; // } // // @Override // public String getTitle() { // return mTitle == null ? "ERROR" : mTitle; // } // // @Override // public String getSummary() { // return mSummary; // } // // @Override // public String getCategory() { // return mCategory; // } // // @Override // public String getScreen() { // return mScreen; // } // // public static String getDefaultString(String value, String defaultValue) { // if (value == null || value.isEmpty()) { // return defaultValue; // } // return value; // } // }
import android.content.Context; import android.preference.PreferenceManager; import android.preference.PreferenceScreen; import com.jackwink.tweakable.exceptions.FailedToBuildPreferenceScreenException; import com.jackwink.tweakable.types.AbstractTweakableValue; import java.util.LinkedHashMap; import java.util.Map;
package com.jackwink.tweakable.builders; /** * Builds a {@link PreferenceScreen} */ @SuppressWarnings({ "rawtypes" }) public class PreferenceScreenBuilder extends BasePreferenceBuilder<PreferenceScreen> { private static final String TAG = PreferenceScreenBuilder.class.getSimpleName(); private PreferenceManager mPreferenceManager = null; public PreferenceScreenBuilder() { mAttributeMap = new LinkedHashMap<String, Object>(); } @Override public Class[] getHandledTypes() { return new Class[0]; } @Override public PreferenceScreenBuilder setContext(Context context) { mContext = context; return this; } @Override public PreferenceScreenBuilder setBundle(Map<String, Object> map) { mAttributeMap = map; return this; } public PreferenceScreenBuilder setPreferenceManager(PreferenceManager preferenceManager) { mPreferenceManager = preferenceManager; return this; } /** {@inheritDoc} */ public PreferenceScreen build() { if (mContext == null) { throw new FailedToBuildPreferenceScreenException( "Failed to set context before building!"); } if (mPreferenceManager == null) { throw new FailedToBuildPreferenceScreenException( "Failed to set preference manager before building!"); } PreferenceScreen screen = mPreferenceManager.createPreferenceScreen(mContext);
// Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/exceptions/FailedToBuildPreferenceScreenException.java // public class FailedToBuildPreferenceScreenException extends RuntimeException { // public static final long serialVersionUID = 0L; // // public FailedToBuildPreferenceScreenException(String reason) { // super(reason); // } // // public FailedToBuildPreferenceScreenException(String reason, Throwable rootCause) { // super(reason, rootCause); // } // } // // Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/types/AbstractTweakableValue.java // public abstract class AbstractTweakableValue<T> implements TweakableValue<T> { // public static final String BUNDLE_KEYATTR_KEY = "key"; // public static final String BUNDLE_TITLE_KEY = "title"; // public static final String BUNDLE_SUMMARY_KEY = "summary"; // // public static final String BUNDLE_CATEGORY_KEY = "category"; // public static final String BUNDLE_SCREEN_KEY = "screen"; // // public static final String ROOT_SCREEN_KEY = "tweakable-values-root-screen"; // public static final String ROOT_CATEGORY_KEY = "tweakable-values-root-category"; // // // protected String mTitle; // protected String mKey; // protected String mSummary; // protected String mCategory; // protected String mScreen; // // @Override // public String getKey() { // return mKey; // } // // @Override // public String getTitle() { // return mTitle == null ? "ERROR" : mTitle; // } // // @Override // public String getSummary() { // return mSummary; // } // // @Override // public String getCategory() { // return mCategory; // } // // @Override // public String getScreen() { // return mScreen; // } // // public static String getDefaultString(String value, String defaultValue) { // if (value == null || value.isEmpty()) { // return defaultValue; // } // return value; // } // } // Path: tweakable/src/main/java/com/jackwink/tweakable/builders/PreferenceScreenBuilder.java import android.content.Context; import android.preference.PreferenceManager; import android.preference.PreferenceScreen; import com.jackwink.tweakable.exceptions.FailedToBuildPreferenceScreenException; import com.jackwink.tweakable.types.AbstractTweakableValue; import java.util.LinkedHashMap; import java.util.Map; package com.jackwink.tweakable.builders; /** * Builds a {@link PreferenceScreen} */ @SuppressWarnings({ "rawtypes" }) public class PreferenceScreenBuilder extends BasePreferenceBuilder<PreferenceScreen> { private static final String TAG = PreferenceScreenBuilder.class.getSimpleName(); private PreferenceManager mPreferenceManager = null; public PreferenceScreenBuilder() { mAttributeMap = new LinkedHashMap<String, Object>(); } @Override public Class[] getHandledTypes() { return new Class[0]; } @Override public PreferenceScreenBuilder setContext(Context context) { mContext = context; return this; } @Override public PreferenceScreenBuilder setBundle(Map<String, Object> map) { mAttributeMap = map; return this; } public PreferenceScreenBuilder setPreferenceManager(PreferenceManager preferenceManager) { mPreferenceManager = preferenceManager; return this; } /** {@inheritDoc} */ public PreferenceScreen build() { if (mContext == null) { throw new FailedToBuildPreferenceScreenException( "Failed to set context before building!"); } if (mPreferenceManager == null) { throw new FailedToBuildPreferenceScreenException( "Failed to set preference manager before building!"); } PreferenceScreen screen = mPreferenceManager.createPreferenceScreen(mContext);
screen.setTitle((String) getRequiredAttribute(AbstractTweakableValue.BUNDLE_TITLE_KEY));
JackWink/tweakable
tweakable/src/main/java/com/jackwink/tweakable/binders/BooleanValueBinder.java
// Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/exceptions/FailedToBuildPreferenceException.java // public class FailedToBuildPreferenceException extends RuntimeException { // public static final long serialVersionUID = 0L; // // public FailedToBuildPreferenceException(String reason) { // super(reason); // } // // public FailedToBuildPreferenceException(String reason, Throwable rootCause) { // super(reason, rootCause); // } // }
import android.content.SharedPreferences; import com.jackwink.tweakable.exceptions.FailedToBuildPreferenceException; import java.lang.reflect.Field;
package com.jackwink.tweakable.binders; /** * Binds a boolean value to a given field */ public class BooleanValueBinder extends AbstractValueBinder<Boolean> { public BooleanValueBinder(Field field) { mField = field; } @Override public Class<Boolean> getType() { return Boolean.class; } @Override public Boolean getValue() { try { if (mField.getType().equals(boolean.class)) { return mField.getBoolean(null); } else if (mField.getType().equals(Boolean.class)) { return (Boolean) mField.get(null); }
// Path: tweakable-annotations/src/main/java/com/jackwink/tweakable/exceptions/FailedToBuildPreferenceException.java // public class FailedToBuildPreferenceException extends RuntimeException { // public static final long serialVersionUID = 0L; // // public FailedToBuildPreferenceException(String reason) { // super(reason); // } // // public FailedToBuildPreferenceException(String reason, Throwable rootCause) { // super(reason, rootCause); // } // } // Path: tweakable/src/main/java/com/jackwink/tweakable/binders/BooleanValueBinder.java import android.content.SharedPreferences; import com.jackwink.tweakable.exceptions.FailedToBuildPreferenceException; import java.lang.reflect.Field; package com.jackwink.tweakable.binders; /** * Binds a boolean value to a given field */ public class BooleanValueBinder extends AbstractValueBinder<Boolean> { public BooleanValueBinder(Field field) { mField = field; } @Override public Class<Boolean> getType() { return Boolean.class; } @Override public Boolean getValue() { try { if (mField.getType().equals(boolean.class)) { return mField.getBoolean(null); } else if (mField.getType().equals(Boolean.class)) { return (Boolean) mField.get(null); }
throw new FailedToBuildPreferenceException(
fahrgemeinschaft/android-app
src/androidTest/java/de/fahrgemeinschaft/test/ContactProviderTest.java
// Path: src/main/java/de/fahrgemeinschaft/ContactProvider.java // public class ContactProvider extends ContentProvider { // // private static final String TABLE = "contacts"; // public static final String AUTHORITY = "de.fahrgemeinschaft.private"; // public static final String URI = "content://" + AUTHORITY + "/contacts"; // // public static final class CONTACT { // public static final String USER = "user"; // public static final String EMAIL = "Email"; // public static final String PLATE = "NumberPlate"; // public static final String MOBILE = "Mobile"; // public static final String LANDLINE = "Landline"; // } // // private static final int VERSION = 3; // private SQLiteOpenHelper db; // // @Override // public boolean onCreate() { // db = new SQLiteOpenHelper(getContext(), "contacts.db", null, VERSION) { // // @Override // public void onCreate(SQLiteDatabase db) { // db.execSQL("CREATE TABLE " + TABLE + " (" + // "_id integer PRIMARY KEY AUTOINCREMENT," + // CONTACT.USER + " text, " + // CONTACT.EMAIL + " text, " + // CONTACT.MOBILE + " text, " + // CONTACT.LANDLINE + " text," + // CONTACT.PLATE + " text);"); // } // // @Override // public void onUpgrade(SQLiteDatabase db, int oldV, int newV) { // db.execSQL("DROP table contacts;"); // onCreate(db); // } // }; // return false; // } // // @Override // public String getType(Uri uri) { // return null; // } // // @Override // public Uri insert(Uri uri, ContentValues values) { // if (values.containsKey(CONTACT.PLATE) // && values.getAsString(CONTACT.PLATE) // .equals(FahrgemeinschaftConnector.BAHN)) { // values.remove(CONTACT.PLATE); // } // db.getWritableDatabase().insert(TABLE, null, values); // return null; // } // // // private static String SELECT(String something) { // return "SELECT _id, " + something + "," + // " COUNT(" + something + ") AS count FROM contacts" + // " WHERE " + CONTACT.USER + " IS ?" + // " AND " + something + " LIKE ?" + // " AND " + something + " IS NOT NULL" + // " AND " + something + " IS NOT ''" + // " GROUP BY " + something + // " ORDER BY _id DESC"; // } // // private static final String SELECT_MAILS = SELECT(CONTACT.EMAIL); // private static final String SELECT_MOBILES = SELECT(CONTACT.MOBILE); // private static final String SELECT_LANDLINES = SELECT(CONTACT.LANDLINE); // private static final String SELECT_PLATES = SELECT(CONTACT.PLATE); // // @Override // public Cursor query(Uri uri, String[] p, String s, String[] a, String o) { // String query = uri.getQueryParameter("q"); // if (query == null) query = ""; // query = query + "%"; // switch(uriMatcher.match(uri)) { // case MAILS: // return db.getReadableDatabase().rawQuery(SELECT_MAILS, // new String[]{ uri.getPathSegments().get(1), query }); // case MOBILES: // return db.getReadableDatabase().rawQuery(SELECT_MOBILES, // new String[]{ uri.getPathSegments().get(1), query }); // case LANDLINES: // return db.getReadableDatabase().rawQuery(SELECT_LANDLINES, // new String[]{ uri.getPathSegments().get(1), query }); // case PLATES: // return db.getReadableDatabase().rawQuery(SELECT_PLATES, // new String[]{ uri.getPathSegments().get(1), query }); // } // return null; // } // // @Override // public int update(Uri uri, ContentValues values, String selection, // String[] selectionArgs) { // return db.getWritableDatabase().update( // TABLE, values, CONTACT.USER + " IS NULL", null); // } // // @Override // public int delete(Uri uri, String selection, String[] selectionArgs) { // return db.getReadableDatabase().delete(TABLE, CONTACT.USER + " = ?", // new String[]{ uri.getLastPathSegment() }); // } // // private static final int MAILS = 1; // private static final int MOBILES = 2; // private static final int LANDLINES = 3; // private static final int PLATES = 4; // // static UriMatcher uriMatcher = new UriMatcher(0); // static { // uriMatcher.addURI(AUTHORITY, "users/*/mails", MAILS); // uriMatcher.addURI(AUTHORITY, "users/*/mobiles", MOBILES); // uriMatcher.addURI(AUTHORITY, "users/*/landlines", LANDLINES); // uriMatcher.addURI(AUTHORITY, "users/*/plates", PLATES); // } // } // // Path: src/main/java/de/fahrgemeinschaft/ContactProvider.java // public static final class CONTACT { // public static final String USER = "user"; // public static final String EMAIL = "Email"; // public static final String PLATE = "NumberPlate"; // public static final String MOBILE = "Mobile"; // public static final String LANDLINE = "Landline"; // }
import de.fahrgemeinschaft.ContactProvider; import de.fahrgemeinschaft.ContactProvider.CONTACT; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.test.ProviderTestCase2;
package de.fahrgemeinschaft.test; public class ContactProviderTest extends ProviderTestCase2<ContactProvider> { public ContactProviderTest() { super(ContactProvider.class, "de.fahrgemeinschaft.test"); } @Override protected void setUp() throws Exception { super.setUp(); getMockContentResolver().addProvider( "de.fahrgemeinschaft.private", getProvider()); ContentValues cv = new ContentValues();
// Path: src/main/java/de/fahrgemeinschaft/ContactProvider.java // public class ContactProvider extends ContentProvider { // // private static final String TABLE = "contacts"; // public static final String AUTHORITY = "de.fahrgemeinschaft.private"; // public static final String URI = "content://" + AUTHORITY + "/contacts"; // // public static final class CONTACT { // public static final String USER = "user"; // public static final String EMAIL = "Email"; // public static final String PLATE = "NumberPlate"; // public static final String MOBILE = "Mobile"; // public static final String LANDLINE = "Landline"; // } // // private static final int VERSION = 3; // private SQLiteOpenHelper db; // // @Override // public boolean onCreate() { // db = new SQLiteOpenHelper(getContext(), "contacts.db", null, VERSION) { // // @Override // public void onCreate(SQLiteDatabase db) { // db.execSQL("CREATE TABLE " + TABLE + " (" + // "_id integer PRIMARY KEY AUTOINCREMENT," + // CONTACT.USER + " text, " + // CONTACT.EMAIL + " text, " + // CONTACT.MOBILE + " text, " + // CONTACT.LANDLINE + " text," + // CONTACT.PLATE + " text);"); // } // // @Override // public void onUpgrade(SQLiteDatabase db, int oldV, int newV) { // db.execSQL("DROP table contacts;"); // onCreate(db); // } // }; // return false; // } // // @Override // public String getType(Uri uri) { // return null; // } // // @Override // public Uri insert(Uri uri, ContentValues values) { // if (values.containsKey(CONTACT.PLATE) // && values.getAsString(CONTACT.PLATE) // .equals(FahrgemeinschaftConnector.BAHN)) { // values.remove(CONTACT.PLATE); // } // db.getWritableDatabase().insert(TABLE, null, values); // return null; // } // // // private static String SELECT(String something) { // return "SELECT _id, " + something + "," + // " COUNT(" + something + ") AS count FROM contacts" + // " WHERE " + CONTACT.USER + " IS ?" + // " AND " + something + " LIKE ?" + // " AND " + something + " IS NOT NULL" + // " AND " + something + " IS NOT ''" + // " GROUP BY " + something + // " ORDER BY _id DESC"; // } // // private static final String SELECT_MAILS = SELECT(CONTACT.EMAIL); // private static final String SELECT_MOBILES = SELECT(CONTACT.MOBILE); // private static final String SELECT_LANDLINES = SELECT(CONTACT.LANDLINE); // private static final String SELECT_PLATES = SELECT(CONTACT.PLATE); // // @Override // public Cursor query(Uri uri, String[] p, String s, String[] a, String o) { // String query = uri.getQueryParameter("q"); // if (query == null) query = ""; // query = query + "%"; // switch(uriMatcher.match(uri)) { // case MAILS: // return db.getReadableDatabase().rawQuery(SELECT_MAILS, // new String[]{ uri.getPathSegments().get(1), query }); // case MOBILES: // return db.getReadableDatabase().rawQuery(SELECT_MOBILES, // new String[]{ uri.getPathSegments().get(1), query }); // case LANDLINES: // return db.getReadableDatabase().rawQuery(SELECT_LANDLINES, // new String[]{ uri.getPathSegments().get(1), query }); // case PLATES: // return db.getReadableDatabase().rawQuery(SELECT_PLATES, // new String[]{ uri.getPathSegments().get(1), query }); // } // return null; // } // // @Override // public int update(Uri uri, ContentValues values, String selection, // String[] selectionArgs) { // return db.getWritableDatabase().update( // TABLE, values, CONTACT.USER + " IS NULL", null); // } // // @Override // public int delete(Uri uri, String selection, String[] selectionArgs) { // return db.getReadableDatabase().delete(TABLE, CONTACT.USER + " = ?", // new String[]{ uri.getLastPathSegment() }); // } // // private static final int MAILS = 1; // private static final int MOBILES = 2; // private static final int LANDLINES = 3; // private static final int PLATES = 4; // // static UriMatcher uriMatcher = new UriMatcher(0); // static { // uriMatcher.addURI(AUTHORITY, "users/*/mails", MAILS); // uriMatcher.addURI(AUTHORITY, "users/*/mobiles", MOBILES); // uriMatcher.addURI(AUTHORITY, "users/*/landlines", LANDLINES); // uriMatcher.addURI(AUTHORITY, "users/*/plates", PLATES); // } // } // // Path: src/main/java/de/fahrgemeinschaft/ContactProvider.java // public static final class CONTACT { // public static final String USER = "user"; // public static final String EMAIL = "Email"; // public static final String PLATE = "NumberPlate"; // public static final String MOBILE = "Mobile"; // public static final String LANDLINE = "Landline"; // } // Path: src/androidTest/java/de/fahrgemeinschaft/test/ContactProviderTest.java import de.fahrgemeinschaft.ContactProvider; import de.fahrgemeinschaft.ContactProvider.CONTACT; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.test.ProviderTestCase2; package de.fahrgemeinschaft.test; public class ContactProviderTest extends ProviderTestCase2<ContactProvider> { public ContactProviderTest() { super(ContactProvider.class, "de.fahrgemeinschaft.test"); } @Override protected void setUp() throws Exception { super.setUp(); getMockContentResolver().addProvider( "de.fahrgemeinschaft.private", getProvider()); ContentValues cv = new ContentValues();
cv.put(CONTACT.EMAIL, "blablamail@gmx.net");
fahrgemeinschaft/android-app
src/main/java/de/fahrgemeinschaft/MainFragment.java
// Path: src/main/java/de/fahrgemeinschaft/util/DateImageButton.java // public class DateImageButton extends BaseImageButton { // // static final SimpleDateFormat df = // new SimpleDateFormat("HH:mm", Locale.GERMANY); // public Button btn; // // @Override // protected int inflate() { // return R.layout.btn_date_picker; // } // // public DateImageButton(Context context) { // super(context); // btn = (Button) findViewById(R.id.text); // btn.setId(ID--); // } // // public DateImageButton(Context context, AttributeSet attrs) { // super(context, attrs); // btn = (Button) findViewById(R.id.text); // btn.setText(getContext().getString(attrs.getAttributeResourceValue( // droid, TEXT, R.string.app_name))); // btn.setId(ID--); // } // // public void setDate(long timestamp) { // Calendar cal = Calendar.getInstance(); // int thisYear = cal.get(Calendar.YEAR); // int today = cal.get(Calendar.DAY_OF_YEAR); // cal.setTimeInMillis(timestamp); // btn.setText(new SimpleDateFormat("dd. MMM yyyy", // Locale.GERMANY).format(timestamp)); // if (cal.get(Calendar.YEAR) == thisYear) { // if (cal.get(Calendar.DAY_OF_YEAR) == today) // btn.setText(getContext().getString(R.string.today)); // else if (cal.get(Calendar.DAY_OF_YEAR) == today + 1) // btn.setText(getContext().getString(R.string.tomorrow)); // else if (cal.get(Calendar.DAY_OF_YEAR) == today + 2) // btn.setText(getContext().getString(R.string.after_tomorrow)); // } // } // // public void setTime(long timestamp) { // btn.setText(df.format(timestamp)); // } // } // // Path: src/main/java/de/fahrgemeinschaft/util/PlaceImageButton.java // public class PlaceImageButton extends BaseImageButton { // // private TextView address; // public Button name; // // @Override // protected int inflate() { // return R.layout.btn_place_picker; // } // // public PlaceImageButton(Context context) { // super(context); // name = (Button) findViewById(R.id.name); // name.setId(ID--); // address = (TextView) findViewById(R.id.address); // address.setId(ID--); // } // // public PlaceImageButton(Context context, AttributeSet attrs) { // super(context, attrs); // name = (Button) findViewById(R.id.name); // name.setId(ID--); // name.setText(getContext().getString(attrs.getAttributeResourceValue( // droid, TEXT, R.string.app_name))); // address = (TextView) findViewById(R.id.address); // address.setId(ID--); // } // // public void setPlace(Place place) { // if (place != null) { // name.setText(place.getName()); // address.setText(place.getAddress()); // } // } // }
import java.util.Calendar; import java.util.Date; import org.teleportr.Ride; import org.teleportr.RidesProvider; import android.app.Activity; import android.app.DatePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.widget.DatePicker; import com.actionbarsherlock.app.SherlockFragment; import de.fahrgemeinschaft.util.DateImageButton; import de.fahrgemeinschaft.util.PlaceImageButton;
/** * Fahrgemeinschaft / Ridesharing App * Copyright (c) 2013 by it's authors. * Some rights reserved. See LICENSE.. * */ package de.fahrgemeinschaft; public class MainFragment extends SherlockFragment implements OnClickListener, OnDateSetListener { protected static final String TAG = "fahrgemeinschaft"; private static final String STATE = "ride"; private static final int FROM = 42; private static final int TO = 55;
// Path: src/main/java/de/fahrgemeinschaft/util/DateImageButton.java // public class DateImageButton extends BaseImageButton { // // static final SimpleDateFormat df = // new SimpleDateFormat("HH:mm", Locale.GERMANY); // public Button btn; // // @Override // protected int inflate() { // return R.layout.btn_date_picker; // } // // public DateImageButton(Context context) { // super(context); // btn = (Button) findViewById(R.id.text); // btn.setId(ID--); // } // // public DateImageButton(Context context, AttributeSet attrs) { // super(context, attrs); // btn = (Button) findViewById(R.id.text); // btn.setText(getContext().getString(attrs.getAttributeResourceValue( // droid, TEXT, R.string.app_name))); // btn.setId(ID--); // } // // public void setDate(long timestamp) { // Calendar cal = Calendar.getInstance(); // int thisYear = cal.get(Calendar.YEAR); // int today = cal.get(Calendar.DAY_OF_YEAR); // cal.setTimeInMillis(timestamp); // btn.setText(new SimpleDateFormat("dd. MMM yyyy", // Locale.GERMANY).format(timestamp)); // if (cal.get(Calendar.YEAR) == thisYear) { // if (cal.get(Calendar.DAY_OF_YEAR) == today) // btn.setText(getContext().getString(R.string.today)); // else if (cal.get(Calendar.DAY_OF_YEAR) == today + 1) // btn.setText(getContext().getString(R.string.tomorrow)); // else if (cal.get(Calendar.DAY_OF_YEAR) == today + 2) // btn.setText(getContext().getString(R.string.after_tomorrow)); // } // } // // public void setTime(long timestamp) { // btn.setText(df.format(timestamp)); // } // } // // Path: src/main/java/de/fahrgemeinschaft/util/PlaceImageButton.java // public class PlaceImageButton extends BaseImageButton { // // private TextView address; // public Button name; // // @Override // protected int inflate() { // return R.layout.btn_place_picker; // } // // public PlaceImageButton(Context context) { // super(context); // name = (Button) findViewById(R.id.name); // name.setId(ID--); // address = (TextView) findViewById(R.id.address); // address.setId(ID--); // } // // public PlaceImageButton(Context context, AttributeSet attrs) { // super(context, attrs); // name = (Button) findViewById(R.id.name); // name.setId(ID--); // name.setText(getContext().getString(attrs.getAttributeResourceValue( // droid, TEXT, R.string.app_name))); // address = (TextView) findViewById(R.id.address); // address.setId(ID--); // } // // public void setPlace(Place place) { // if (place != null) { // name.setText(place.getName()); // address.setText(place.getAddress()); // } // } // } // Path: src/main/java/de/fahrgemeinschaft/MainFragment.java import java.util.Calendar; import java.util.Date; import org.teleportr.Ride; import org.teleportr.RidesProvider; import android.app.Activity; import android.app.DatePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.widget.DatePicker; import com.actionbarsherlock.app.SherlockFragment; import de.fahrgemeinschaft.util.DateImageButton; import de.fahrgemeinschaft.util.PlaceImageButton; /** * Fahrgemeinschaft / Ridesharing App * Copyright (c) 2013 by it's authors. * Some rights reserved. See LICENSE.. * */ package de.fahrgemeinschaft; public class MainFragment extends SherlockFragment implements OnClickListener, OnDateSetListener { protected static final String TAG = "fahrgemeinschaft"; private static final String STATE = "ride"; private static final int FROM = 42; private static final int TO = 55;
private DateImageButton when;
fahrgemeinschaft/android-app
src/main/java/de/fahrgemeinschaft/MainFragment.java
// Path: src/main/java/de/fahrgemeinschaft/util/DateImageButton.java // public class DateImageButton extends BaseImageButton { // // static final SimpleDateFormat df = // new SimpleDateFormat("HH:mm", Locale.GERMANY); // public Button btn; // // @Override // protected int inflate() { // return R.layout.btn_date_picker; // } // // public DateImageButton(Context context) { // super(context); // btn = (Button) findViewById(R.id.text); // btn.setId(ID--); // } // // public DateImageButton(Context context, AttributeSet attrs) { // super(context, attrs); // btn = (Button) findViewById(R.id.text); // btn.setText(getContext().getString(attrs.getAttributeResourceValue( // droid, TEXT, R.string.app_name))); // btn.setId(ID--); // } // // public void setDate(long timestamp) { // Calendar cal = Calendar.getInstance(); // int thisYear = cal.get(Calendar.YEAR); // int today = cal.get(Calendar.DAY_OF_YEAR); // cal.setTimeInMillis(timestamp); // btn.setText(new SimpleDateFormat("dd. MMM yyyy", // Locale.GERMANY).format(timestamp)); // if (cal.get(Calendar.YEAR) == thisYear) { // if (cal.get(Calendar.DAY_OF_YEAR) == today) // btn.setText(getContext().getString(R.string.today)); // else if (cal.get(Calendar.DAY_OF_YEAR) == today + 1) // btn.setText(getContext().getString(R.string.tomorrow)); // else if (cal.get(Calendar.DAY_OF_YEAR) == today + 2) // btn.setText(getContext().getString(R.string.after_tomorrow)); // } // } // // public void setTime(long timestamp) { // btn.setText(df.format(timestamp)); // } // } // // Path: src/main/java/de/fahrgemeinschaft/util/PlaceImageButton.java // public class PlaceImageButton extends BaseImageButton { // // private TextView address; // public Button name; // // @Override // protected int inflate() { // return R.layout.btn_place_picker; // } // // public PlaceImageButton(Context context) { // super(context); // name = (Button) findViewById(R.id.name); // name.setId(ID--); // address = (TextView) findViewById(R.id.address); // address.setId(ID--); // } // // public PlaceImageButton(Context context, AttributeSet attrs) { // super(context, attrs); // name = (Button) findViewById(R.id.name); // name.setId(ID--); // name.setText(getContext().getString(attrs.getAttributeResourceValue( // droid, TEXT, R.string.app_name))); // address = (TextView) findViewById(R.id.address); // address.setId(ID--); // } // // public void setPlace(Place place) { // if (place != null) { // name.setText(place.getName()); // address.setText(place.getAddress()); // } // } // }
import java.util.Calendar; import java.util.Date; import org.teleportr.Ride; import org.teleportr.RidesProvider; import android.app.Activity; import android.app.DatePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.widget.DatePicker; import com.actionbarsherlock.app.SherlockFragment; import de.fahrgemeinschaft.util.DateImageButton; import de.fahrgemeinschaft.util.PlaceImageButton;
/** * Fahrgemeinschaft / Ridesharing App * Copyright (c) 2013 by it's authors. * Some rights reserved. See LICENSE.. * */ package de.fahrgemeinschaft; public class MainFragment extends SherlockFragment implements OnClickListener, OnDateSetListener { protected static final String TAG = "fahrgemeinschaft"; private static final String STATE = "ride"; private static final int FROM = 42; private static final int TO = 55; private DateImageButton when;
// Path: src/main/java/de/fahrgemeinschaft/util/DateImageButton.java // public class DateImageButton extends BaseImageButton { // // static final SimpleDateFormat df = // new SimpleDateFormat("HH:mm", Locale.GERMANY); // public Button btn; // // @Override // protected int inflate() { // return R.layout.btn_date_picker; // } // // public DateImageButton(Context context) { // super(context); // btn = (Button) findViewById(R.id.text); // btn.setId(ID--); // } // // public DateImageButton(Context context, AttributeSet attrs) { // super(context, attrs); // btn = (Button) findViewById(R.id.text); // btn.setText(getContext().getString(attrs.getAttributeResourceValue( // droid, TEXT, R.string.app_name))); // btn.setId(ID--); // } // // public void setDate(long timestamp) { // Calendar cal = Calendar.getInstance(); // int thisYear = cal.get(Calendar.YEAR); // int today = cal.get(Calendar.DAY_OF_YEAR); // cal.setTimeInMillis(timestamp); // btn.setText(new SimpleDateFormat("dd. MMM yyyy", // Locale.GERMANY).format(timestamp)); // if (cal.get(Calendar.YEAR) == thisYear) { // if (cal.get(Calendar.DAY_OF_YEAR) == today) // btn.setText(getContext().getString(R.string.today)); // else if (cal.get(Calendar.DAY_OF_YEAR) == today + 1) // btn.setText(getContext().getString(R.string.tomorrow)); // else if (cal.get(Calendar.DAY_OF_YEAR) == today + 2) // btn.setText(getContext().getString(R.string.after_tomorrow)); // } // } // // public void setTime(long timestamp) { // btn.setText(df.format(timestamp)); // } // } // // Path: src/main/java/de/fahrgemeinschaft/util/PlaceImageButton.java // public class PlaceImageButton extends BaseImageButton { // // private TextView address; // public Button name; // // @Override // protected int inflate() { // return R.layout.btn_place_picker; // } // // public PlaceImageButton(Context context) { // super(context); // name = (Button) findViewById(R.id.name); // name.setId(ID--); // address = (TextView) findViewById(R.id.address); // address.setId(ID--); // } // // public PlaceImageButton(Context context, AttributeSet attrs) { // super(context, attrs); // name = (Button) findViewById(R.id.name); // name.setId(ID--); // name.setText(getContext().getString(attrs.getAttributeResourceValue( // droid, TEXT, R.string.app_name))); // address = (TextView) findViewById(R.id.address); // address.setId(ID--); // } // // public void setPlace(Place place) { // if (place != null) { // name.setText(place.getName()); // address.setText(place.getAddress()); // } // } // } // Path: src/main/java/de/fahrgemeinschaft/MainFragment.java import java.util.Calendar; import java.util.Date; import org.teleportr.Ride; import org.teleportr.RidesProvider; import android.app.Activity; import android.app.DatePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.widget.DatePicker; import com.actionbarsherlock.app.SherlockFragment; import de.fahrgemeinschaft.util.DateImageButton; import de.fahrgemeinschaft.util.PlaceImageButton; /** * Fahrgemeinschaft / Ridesharing App * Copyright (c) 2013 by it's authors. * Some rights reserved. See LICENSE.. * */ package de.fahrgemeinschaft; public class MainFragment extends SherlockFragment implements OnClickListener, OnDateSetListener { protected static final String TAG = "fahrgemeinschaft"; private static final String STATE = "ride"; private static final int FROM = 42; private static final int TO = 55; private DateImageButton when;
private PlaceImageButton from;
fahrgemeinschaft/android-app
src/main/java/de/fahrgemeinschaft/ProfileFragment.java
// Path: src/main/java/de/fahrgemeinschaft/ContactProvider.java // public static final class CONTACT { // public static final String USER = "user"; // public static final String EMAIL = "Email"; // public static final String PLATE = "NumberPlate"; // public static final String MOBILE = "Mobile"; // public static final String LANDLINE = "Landline"; // } // // Path: src/main/java/de/fahrgemeinschaft/util/EditTextImageButton.java // public class EditTextImageButton extends BaseImageButton // implements TextWatcher, OnClickListener { // // private static final String Q = "q"; // private static final String EMPTY = ""; // private static final String INPUT_TYPE = "inputType"; // private static final String HINT = "hint"; // public AutoCompletePicker text; // private TextListener textListener; // protected String key; // // @Override // protected int inflate() { // return R.layout.btn_edit_text; // } // // public EditTextImageButton(Context context, AttributeSet attrs) { // super(context, attrs); // text = (AutoCompletePicker) findViewById(R.id.text); // text.setThreshold(1); // text.setId(ID--); // text.setHint(getContext().getString(attrs.getAttributeResourceValue( // droid, HINT, R.string.app_name))); // text.setInputType((attrs.getAttributeIntValue( // droid, INPUT_TYPE, InputType.TYPE_CLASS_TEXT))); // text.addTextChangedListener(this); // Util.fixStreifenhoernchen(text); // text.setSelectAllOnFocus(true); // icon.setOnClickListener(this); // } // // @Override // public void onClick(View v) { // text.requestFocus(); // } // // public interface TextListener { // public void onTextChange(String key, String text); // } // // public void setTextListener(String key, TextListener listener) { // this.textListener = listener; // this.key = key; // } // // @Override // public void afterTextChanged(Editable s) { // if (textListener != null) // textListener.onTextChange(key, text.getText().toString()); // } // // @Override // public void beforeTextChanged(CharSequence s, int start, int cnt, int a) {} // // @Override // public void onTextChanged(CharSequence s, int start, int before, int cnt) {} // // } // // Path: src/main/java/de/fahrgemeinschaft/util/WebActivity.java // @SuppressLint({ "SetJavaScriptEnabled", "JavascriptInterface" }) // public class WebActivity extends SherlockActivity { // // private ProgressDialog progress; // private WebView webView; // // @SuppressWarnings("deprecation") // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // webView = new WebView(this); // progress = new ProgressDialog(this); // webView.getSettings().setJavaScriptEnabled(true); // webView.getSettings().setSaveFormData(false); // webView.getSettings().setSavePassword(false); // webView.loadUrl(getIntent().getDataString()); // webView.requestFocus(View.FOCUS_DOWN); // setContentView(webView); // webView.setWebChromeClient(new WebChromeClient(){ // // @Override // public boolean onJsAlert(WebView view, String url, String message, // JsResult result) { // Crouton.makeText(WebActivity.this, message, Style.ALERT).show(); // result.cancel(); // return true; // } // }); // // webView.setWebViewClient(new WebViewClient() { // // @Override // public void onPageStarted(WebView v, String url, Bitmap favic) { // if (url.startsWith("http")) { // progress.show(); // } // super.onPageStarted(v, url, favic); // } // // @Override // public void onPageFinished(WebView view, String url) { // progress.dismiss(); // overridePendingTransition( // R.anim.do_nix, R.anim.slide_out_bottom); // super.onPageFinished(view, url); // } // }); // } // }
import org.teleportr.ConnectorService; import org.teleportr.RidesProvider; import android.app.Activity; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import com.actionbarsherlock.app.SherlockFragment; import de.fahrgemeinschaft.ContactProvider.CONTACT; import de.fahrgemeinschaft.util.EditTextImageButton; import de.fahrgemeinschaft.util.WebActivity; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.Style;
/** * Fahrgemeinschaft / Ridesharing App * Copyright (c) 2013 by it's authors. * Some rights reserved. See LICENSE.. * */ package de.fahrgemeinschaft; public class ProfileFragment extends SherlockFragment implements OnClickListener, OnSharedPreferenceChangeListener { public static final String REMEMBER_PASSWORD = "remember_password"; public static final String INIT_CONTACTS = "init_contacts"; public static final String FIRSTNAME = "firstname"; public static final String LASTNAME = "lastname"; public static final String PASSWORD = "password"; public static final String LOGIN = "login"; public static final String AUTH = "auth"; public static final String EMPTY = "";
// Path: src/main/java/de/fahrgemeinschaft/ContactProvider.java // public static final class CONTACT { // public static final String USER = "user"; // public static final String EMAIL = "Email"; // public static final String PLATE = "NumberPlate"; // public static final String MOBILE = "Mobile"; // public static final String LANDLINE = "Landline"; // } // // Path: src/main/java/de/fahrgemeinschaft/util/EditTextImageButton.java // public class EditTextImageButton extends BaseImageButton // implements TextWatcher, OnClickListener { // // private static final String Q = "q"; // private static final String EMPTY = ""; // private static final String INPUT_TYPE = "inputType"; // private static final String HINT = "hint"; // public AutoCompletePicker text; // private TextListener textListener; // protected String key; // // @Override // protected int inflate() { // return R.layout.btn_edit_text; // } // // public EditTextImageButton(Context context, AttributeSet attrs) { // super(context, attrs); // text = (AutoCompletePicker) findViewById(R.id.text); // text.setThreshold(1); // text.setId(ID--); // text.setHint(getContext().getString(attrs.getAttributeResourceValue( // droid, HINT, R.string.app_name))); // text.setInputType((attrs.getAttributeIntValue( // droid, INPUT_TYPE, InputType.TYPE_CLASS_TEXT))); // text.addTextChangedListener(this); // Util.fixStreifenhoernchen(text); // text.setSelectAllOnFocus(true); // icon.setOnClickListener(this); // } // // @Override // public void onClick(View v) { // text.requestFocus(); // } // // public interface TextListener { // public void onTextChange(String key, String text); // } // // public void setTextListener(String key, TextListener listener) { // this.textListener = listener; // this.key = key; // } // // @Override // public void afterTextChanged(Editable s) { // if (textListener != null) // textListener.onTextChange(key, text.getText().toString()); // } // // @Override // public void beforeTextChanged(CharSequence s, int start, int cnt, int a) {} // // @Override // public void onTextChanged(CharSequence s, int start, int before, int cnt) {} // // } // // Path: src/main/java/de/fahrgemeinschaft/util/WebActivity.java // @SuppressLint({ "SetJavaScriptEnabled", "JavascriptInterface" }) // public class WebActivity extends SherlockActivity { // // private ProgressDialog progress; // private WebView webView; // // @SuppressWarnings("deprecation") // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // webView = new WebView(this); // progress = new ProgressDialog(this); // webView.getSettings().setJavaScriptEnabled(true); // webView.getSettings().setSaveFormData(false); // webView.getSettings().setSavePassword(false); // webView.loadUrl(getIntent().getDataString()); // webView.requestFocus(View.FOCUS_DOWN); // setContentView(webView); // webView.setWebChromeClient(new WebChromeClient(){ // // @Override // public boolean onJsAlert(WebView view, String url, String message, // JsResult result) { // Crouton.makeText(WebActivity.this, message, Style.ALERT).show(); // result.cancel(); // return true; // } // }); // // webView.setWebViewClient(new WebViewClient() { // // @Override // public void onPageStarted(WebView v, String url, Bitmap favic) { // if (url.startsWith("http")) { // progress.show(); // } // super.onPageStarted(v, url, favic); // } // // @Override // public void onPageFinished(WebView view, String url) { // progress.dismiss(); // overridePendingTransition( // R.anim.do_nix, R.anim.slide_out_bottom); // super.onPageFinished(view, url); // } // }); // } // } // Path: src/main/java/de/fahrgemeinschaft/ProfileFragment.java import org.teleportr.ConnectorService; import org.teleportr.RidesProvider; import android.app.Activity; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import com.actionbarsherlock.app.SherlockFragment; import de.fahrgemeinschaft.ContactProvider.CONTACT; import de.fahrgemeinschaft.util.EditTextImageButton; import de.fahrgemeinschaft.util.WebActivity; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.Style; /** * Fahrgemeinschaft / Ridesharing App * Copyright (c) 2013 by it's authors. * Some rights reserved. See LICENSE.. * */ package de.fahrgemeinschaft; public class ProfileFragment extends SherlockFragment implements OnClickListener, OnSharedPreferenceChangeListener { public static final String REMEMBER_PASSWORD = "remember_password"; public static final String INIT_CONTACTS = "init_contacts"; public static final String FIRSTNAME = "firstname"; public static final String LASTNAME = "lastname"; public static final String PASSWORD = "password"; public static final String LOGIN = "login"; public static final String AUTH = "auth"; public static final String EMPTY = "";
private EditTextImageButton username;
fahrgemeinschaft/android-app
src/main/java/de/fahrgemeinschaft/EditRideFragment1.java
// Path: src/main/java/de/fahrgemeinschaft/ContactProvider.java // public static final class CONTACT { // public static final String USER = "user"; // public static final String EMAIL = "Email"; // public static final String PLATE = "NumberPlate"; // public static final String MOBILE = "Mobile"; // public static final String LANDLINE = "Landline"; // } // // Path: src/main/java/de/fahrgemeinschaft/util/PlaceImageButton.java // public class PlaceImageButton extends BaseImageButton { // // private TextView address; // public Button name; // // @Override // protected int inflate() { // return R.layout.btn_place_picker; // } // // public PlaceImageButton(Context context) { // super(context); // name = (Button) findViewById(R.id.name); // name.setId(ID--); // address = (TextView) findViewById(R.id.address); // address.setId(ID--); // } // // public PlaceImageButton(Context context, AttributeSet attrs) { // super(context, attrs); // name = (Button) findViewById(R.id.name); // name.setId(ID--); // name.setText(getContext().getString(attrs.getAttributeResourceValue( // droid, TEXT, R.string.app_name))); // address = (TextView) findViewById(R.id.address); // address.setId(ID--); // } // // public void setPlace(Place place) { // if (place != null) { // name.setText(place.getName()); // address.setText(place.getAddress()); // } // } // }
import java.util.List; import org.teleportr.Place; import org.teleportr.Ride; import org.teleportr.Ride.Mode; import org.teleportr.RidesProvider; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TextView; import com.actionbarsherlock.app.SherlockFragment; import de.fahrgemeinschaft.ContactProvider.CONTACT; import de.fahrgemeinschaft.util.PlaceImageButton;
route = (LinearLayout) v.findViewById(R.id.route); from = (PlaceImageButton) v.findViewById(R.id.from); from.name.setOnClickListener(autocompletePlace); from.icon.setOnClickListener(pickPlace); to = (PlaceImageButton) v.findViewById(R.id.to); to.icon.setOnClickListener(pickDestinationPlace); to.name.setOnClickListener(autocompleteDestinationPlace); } public void setRide(Ride ride) { this.ride = ride; if (ride.getFrom() != null) from.setPlace(ride.getFrom()); if (ride.getTo() != null) to.setPlace(ride.getTo()); setVias(ride.getVias()); setMode(ride.getMode()); setSeats(ride.getSeats()); } private void setMode(Mode mode) { ride.mode(mode); switch(mode) { case CAR: getActivity().findViewById(R.id.mode_car).setSelected(true); getActivity().findViewById(R.id.mode_rail).setSelected(false); ((TextView) getActivity().findViewById(R.id.mode_car_text)) .setTextColor(getResources().getColor(R.color.dark_green)); ((TextView) getActivity().findViewById(R.id.mode_rail_text)) .setTextColor(getResources().getColor(R.color.white));
// Path: src/main/java/de/fahrgemeinschaft/ContactProvider.java // public static final class CONTACT { // public static final String USER = "user"; // public static final String EMAIL = "Email"; // public static final String PLATE = "NumberPlate"; // public static final String MOBILE = "Mobile"; // public static final String LANDLINE = "Landline"; // } // // Path: src/main/java/de/fahrgemeinschaft/util/PlaceImageButton.java // public class PlaceImageButton extends BaseImageButton { // // private TextView address; // public Button name; // // @Override // protected int inflate() { // return R.layout.btn_place_picker; // } // // public PlaceImageButton(Context context) { // super(context); // name = (Button) findViewById(R.id.name); // name.setId(ID--); // address = (TextView) findViewById(R.id.address); // address.setId(ID--); // } // // public PlaceImageButton(Context context, AttributeSet attrs) { // super(context, attrs); // name = (Button) findViewById(R.id.name); // name.setId(ID--); // name.setText(getContext().getString(attrs.getAttributeResourceValue( // droid, TEXT, R.string.app_name))); // address = (TextView) findViewById(R.id.address); // address.setId(ID--); // } // // public void setPlace(Place place) { // if (place != null) { // name.setText(place.getName()); // address.setText(place.getAddress()); // } // } // } // Path: src/main/java/de/fahrgemeinschaft/EditRideFragment1.java import java.util.List; import org.teleportr.Place; import org.teleportr.Ride; import org.teleportr.Ride.Mode; import org.teleportr.RidesProvider; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TextView; import com.actionbarsherlock.app.SherlockFragment; import de.fahrgemeinschaft.ContactProvider.CONTACT; import de.fahrgemeinschaft.util.PlaceImageButton; route = (LinearLayout) v.findViewById(R.id.route); from = (PlaceImageButton) v.findViewById(R.id.from); from.name.setOnClickListener(autocompletePlace); from.icon.setOnClickListener(pickPlace); to = (PlaceImageButton) v.findViewById(R.id.to); to.icon.setOnClickListener(pickDestinationPlace); to.name.setOnClickListener(autocompleteDestinationPlace); } public void setRide(Ride ride) { this.ride = ride; if (ride.getFrom() != null) from.setPlace(ride.getFrom()); if (ride.getTo() != null) to.setPlace(ride.getTo()); setVias(ride.getVias()); setMode(ride.getMode()); setSeats(ride.getSeats()); } private void setMode(Mode mode) { ride.mode(mode); switch(mode) { case CAR: getActivity().findViewById(R.id.mode_car).setSelected(true); getActivity().findViewById(R.id.mode_rail).setSelected(false); ((TextView) getActivity().findViewById(R.id.mode_car_text)) .setTextColor(getResources().getColor(R.color.dark_green)); ((TextView) getActivity().findViewById(R.id.mode_rail_text)) .setTextColor(getResources().getColor(R.color.white));
ride.set(CONTACT.PLATE, "");
fahrgemeinschaft/android-app
src/main/java/de/fahrgemeinschaft/EditRideFragment3.java
// Path: src/main/java/de/fahrgemeinschaft/ContactProvider.java // public static final class CONTACT { // public static final String USER = "user"; // public static final String EMAIL = "Email"; // public static final String PLATE = "NumberPlate"; // public static final String MOBILE = "Mobile"; // public static final String LANDLINE = "Landline"; // } // // Path: src/main/java/de/fahrgemeinschaft/util/EditTextImageButton.java // public interface TextListener { // public void onTextChange(String key, String text); // } // // Path: src/main/java/de/fahrgemeinschaft/util/PrivacyImageButton.java // public class PrivacyImageButton extends EditTextImageButton // implements OnClickListener { // // static final String android = "http://schemas.android.com/apk/res/android"; // // // private int privacy; // private int imageResId; // private PrivacyListener privacyListener; // // // public PrivacyImageButton(Context context, AttributeSet attrs) { // super(context, attrs); // setImageResource(attrs.getAttributeResourceValue( // android, SRC, R.drawable.icn_dropdown)); // icon.setOnClickListener(this); // } // // public void setImageResource(int resourceId) { // imageResId = resourceId; // setVisibility(privacy); // } // // public int getPrivacy() { // return privacy; // } // // public void setPrivacy(int privacy) { // this.privacy = privacy; // switch (privacy) { // case 1: // text.setEnabled(true); // drawIcons(R.drawable.icn_visibility_anyone); // break; // case 4: // text.setEnabled(true); // drawIcons(R.drawable.icn_visibility_members); // break; // case 0: // text.setEnabled(true); // drawIcons(R.drawable.icn_visibility_request); // break; // case 5: // text.setEnabled(false); // drawIcons(R.drawable.icn_visibility_none); // break; // } // } // // @Override // public void onClick(View v) { // AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); // builder.setTitle(getResources().getString(R.string.visibility)); // builder.setItems(R.array.visibility, // new DialogInterface.OnClickListener() { // // @Override // must match @array/visibility in strings.xml // public void onClick(DialogInterface dialog, int click_idx) { // switch (click_idx) { // case 0: // anyone // setPrivacy(1); // break; // case 1: // members // setPrivacy(4); // break; // case 2: // request // setPrivacy(0); // break; // case 3: // none // setPrivacy(5); // break; // } // if (privacyListener != null) // privacyListener.onPrivacyChange(key, privacy); // } // }).show(); // } // // private void drawIcons(int resId) { // icon.setImageDrawable(new LayerDrawable(new Drawable[] { // getResources().getDrawable(imageResId), // getResources().getDrawable(resId) // })); // } // // public void setPrivacyListener(String key, PrivacyListener listener) { // this.privacyListener = listener; // this.key = key; // } // // public interface PrivacyListener { // public void onPrivacyChange(String key, int visibility); // } // } // // Path: src/main/java/de/fahrgemeinschaft/util/PrivacyImageButton.java // public interface PrivacyListener { // public void onPrivacyChange(String key, int visibility); // }
import org.json.JSONException; import org.json.JSONObject; import org.teleportr.Ride; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.actionbarsherlock.app.SherlockFragment; import de.fahrgemeinschaft.ContactProvider.CONTACT; import de.fahrgemeinschaft.util.EditTextImageButton.TextListener; import de.fahrgemeinschaft.util.PrivacyImageButton; import de.fahrgemeinschaft.util.PrivacyImageButton.PrivacyListener;
/** * Fahrgemeinschaft / Ridesharing App * Copyright (c) 2013 by it's authors. * Some rights reserved. See LICENSE.. * */ package de.fahrgemeinschaft; public class EditRideFragment3 extends SherlockFragment implements TextListener, PrivacyListener { private static final String NAME = "Name"; private static final String EMPTY = "";
// Path: src/main/java/de/fahrgemeinschaft/ContactProvider.java // public static final class CONTACT { // public static final String USER = "user"; // public static final String EMAIL = "Email"; // public static final String PLATE = "NumberPlate"; // public static final String MOBILE = "Mobile"; // public static final String LANDLINE = "Landline"; // } // // Path: src/main/java/de/fahrgemeinschaft/util/EditTextImageButton.java // public interface TextListener { // public void onTextChange(String key, String text); // } // // Path: src/main/java/de/fahrgemeinschaft/util/PrivacyImageButton.java // public class PrivacyImageButton extends EditTextImageButton // implements OnClickListener { // // static final String android = "http://schemas.android.com/apk/res/android"; // // // private int privacy; // private int imageResId; // private PrivacyListener privacyListener; // // // public PrivacyImageButton(Context context, AttributeSet attrs) { // super(context, attrs); // setImageResource(attrs.getAttributeResourceValue( // android, SRC, R.drawable.icn_dropdown)); // icon.setOnClickListener(this); // } // // public void setImageResource(int resourceId) { // imageResId = resourceId; // setVisibility(privacy); // } // // public int getPrivacy() { // return privacy; // } // // public void setPrivacy(int privacy) { // this.privacy = privacy; // switch (privacy) { // case 1: // text.setEnabled(true); // drawIcons(R.drawable.icn_visibility_anyone); // break; // case 4: // text.setEnabled(true); // drawIcons(R.drawable.icn_visibility_members); // break; // case 0: // text.setEnabled(true); // drawIcons(R.drawable.icn_visibility_request); // break; // case 5: // text.setEnabled(false); // drawIcons(R.drawable.icn_visibility_none); // break; // } // } // // @Override // public void onClick(View v) { // AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); // builder.setTitle(getResources().getString(R.string.visibility)); // builder.setItems(R.array.visibility, // new DialogInterface.OnClickListener() { // // @Override // must match @array/visibility in strings.xml // public void onClick(DialogInterface dialog, int click_idx) { // switch (click_idx) { // case 0: // anyone // setPrivacy(1); // break; // case 1: // members // setPrivacy(4); // break; // case 2: // request // setPrivacy(0); // break; // case 3: // none // setPrivacy(5); // break; // } // if (privacyListener != null) // privacyListener.onPrivacyChange(key, privacy); // } // }).show(); // } // // private void drawIcons(int resId) { // icon.setImageDrawable(new LayerDrawable(new Drawable[] { // getResources().getDrawable(imageResId), // getResources().getDrawable(resId) // })); // } // // public void setPrivacyListener(String key, PrivacyListener listener) { // this.privacyListener = listener; // this.key = key; // } // // public interface PrivacyListener { // public void onPrivacyChange(String key, int visibility); // } // } // // Path: src/main/java/de/fahrgemeinschaft/util/PrivacyImageButton.java // public interface PrivacyListener { // public void onPrivacyChange(String key, int visibility); // } // Path: src/main/java/de/fahrgemeinschaft/EditRideFragment3.java import org.json.JSONException; import org.json.JSONObject; import org.teleportr.Ride; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.actionbarsherlock.app.SherlockFragment; import de.fahrgemeinschaft.ContactProvider.CONTACT; import de.fahrgemeinschaft.util.EditTextImageButton.TextListener; import de.fahrgemeinschaft.util.PrivacyImageButton; import de.fahrgemeinschaft.util.PrivacyImageButton.PrivacyListener; /** * Fahrgemeinschaft / Ridesharing App * Copyright (c) 2013 by it's authors. * Some rights reserved. See LICENSE.. * */ package de.fahrgemeinschaft; public class EditRideFragment3 extends SherlockFragment implements TextListener, PrivacyListener { private static final String NAME = "Name"; private static final String EMPTY = "";
private PrivacyImageButton mobile;
fahrgemeinschaft/android-app
src/main/java/de/fahrgemeinschaft/EditRideFragment3.java
// Path: src/main/java/de/fahrgemeinschaft/ContactProvider.java // public static final class CONTACT { // public static final String USER = "user"; // public static final String EMAIL = "Email"; // public static final String PLATE = "NumberPlate"; // public static final String MOBILE = "Mobile"; // public static final String LANDLINE = "Landline"; // } // // Path: src/main/java/de/fahrgemeinschaft/util/EditTextImageButton.java // public interface TextListener { // public void onTextChange(String key, String text); // } // // Path: src/main/java/de/fahrgemeinschaft/util/PrivacyImageButton.java // public class PrivacyImageButton extends EditTextImageButton // implements OnClickListener { // // static final String android = "http://schemas.android.com/apk/res/android"; // // // private int privacy; // private int imageResId; // private PrivacyListener privacyListener; // // // public PrivacyImageButton(Context context, AttributeSet attrs) { // super(context, attrs); // setImageResource(attrs.getAttributeResourceValue( // android, SRC, R.drawable.icn_dropdown)); // icon.setOnClickListener(this); // } // // public void setImageResource(int resourceId) { // imageResId = resourceId; // setVisibility(privacy); // } // // public int getPrivacy() { // return privacy; // } // // public void setPrivacy(int privacy) { // this.privacy = privacy; // switch (privacy) { // case 1: // text.setEnabled(true); // drawIcons(R.drawable.icn_visibility_anyone); // break; // case 4: // text.setEnabled(true); // drawIcons(R.drawable.icn_visibility_members); // break; // case 0: // text.setEnabled(true); // drawIcons(R.drawable.icn_visibility_request); // break; // case 5: // text.setEnabled(false); // drawIcons(R.drawable.icn_visibility_none); // break; // } // } // // @Override // public void onClick(View v) { // AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); // builder.setTitle(getResources().getString(R.string.visibility)); // builder.setItems(R.array.visibility, // new DialogInterface.OnClickListener() { // // @Override // must match @array/visibility in strings.xml // public void onClick(DialogInterface dialog, int click_idx) { // switch (click_idx) { // case 0: // anyone // setPrivacy(1); // break; // case 1: // members // setPrivacy(4); // break; // case 2: // request // setPrivacy(0); // break; // case 3: // none // setPrivacy(5); // break; // } // if (privacyListener != null) // privacyListener.onPrivacyChange(key, privacy); // } // }).show(); // } // // private void drawIcons(int resId) { // icon.setImageDrawable(new LayerDrawable(new Drawable[] { // getResources().getDrawable(imageResId), // getResources().getDrawable(resId) // })); // } // // public void setPrivacyListener(String key, PrivacyListener listener) { // this.privacyListener = listener; // this.key = key; // } // // public interface PrivacyListener { // public void onPrivacyChange(String key, int visibility); // } // } // // Path: src/main/java/de/fahrgemeinschaft/util/PrivacyImageButton.java // public interface PrivacyListener { // public void onPrivacyChange(String key, int visibility); // }
import org.json.JSONException; import org.json.JSONObject; import org.teleportr.Ride; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.actionbarsherlock.app.SherlockFragment; import de.fahrgemeinschaft.ContactProvider.CONTACT; import de.fahrgemeinschaft.util.EditTextImageButton.TextListener; import de.fahrgemeinschaft.util.PrivacyImageButton; import de.fahrgemeinschaft.util.PrivacyImageButton.PrivacyListener;
/** * Fahrgemeinschaft / Ridesharing App * Copyright (c) 2013 by it's authors. * Some rights reserved. See LICENSE.. * */ package de.fahrgemeinschaft; public class EditRideFragment3 extends SherlockFragment implements TextListener, PrivacyListener { private static final String NAME = "Name"; private static final String EMPTY = ""; private PrivacyImageButton mobile; private PrivacyImageButton plate; private PrivacyImageButton email; private PrivacyImageButton land; private PrivacyImageButton name; private SharedPreferences prefs; @Override public View onCreateView(final LayoutInflater lI, ViewGroup p, Bundle b) { prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); return lI.inflate(R.layout.fragment_ride_edit3, p, false); } @Override public void onViewCreated(View v, Bundle savedInstanceState) { super.onViewCreated(v, savedInstanceState); email = (PrivacyImageButton) v.findViewById(R.id.email); land = (PrivacyImageButton) v.findViewById(R.id.landline); mobile = (PrivacyImageButton) v.findViewById(R.id.mobile); plate = (PrivacyImageButton) v.findViewById(R.id.plate); name = (PrivacyImageButton) v.findViewById(R.id.name);
// Path: src/main/java/de/fahrgemeinschaft/ContactProvider.java // public static final class CONTACT { // public static final String USER = "user"; // public static final String EMAIL = "Email"; // public static final String PLATE = "NumberPlate"; // public static final String MOBILE = "Mobile"; // public static final String LANDLINE = "Landline"; // } // // Path: src/main/java/de/fahrgemeinschaft/util/EditTextImageButton.java // public interface TextListener { // public void onTextChange(String key, String text); // } // // Path: src/main/java/de/fahrgemeinschaft/util/PrivacyImageButton.java // public class PrivacyImageButton extends EditTextImageButton // implements OnClickListener { // // static final String android = "http://schemas.android.com/apk/res/android"; // // // private int privacy; // private int imageResId; // private PrivacyListener privacyListener; // // // public PrivacyImageButton(Context context, AttributeSet attrs) { // super(context, attrs); // setImageResource(attrs.getAttributeResourceValue( // android, SRC, R.drawable.icn_dropdown)); // icon.setOnClickListener(this); // } // // public void setImageResource(int resourceId) { // imageResId = resourceId; // setVisibility(privacy); // } // // public int getPrivacy() { // return privacy; // } // // public void setPrivacy(int privacy) { // this.privacy = privacy; // switch (privacy) { // case 1: // text.setEnabled(true); // drawIcons(R.drawable.icn_visibility_anyone); // break; // case 4: // text.setEnabled(true); // drawIcons(R.drawable.icn_visibility_members); // break; // case 0: // text.setEnabled(true); // drawIcons(R.drawable.icn_visibility_request); // break; // case 5: // text.setEnabled(false); // drawIcons(R.drawable.icn_visibility_none); // break; // } // } // // @Override // public void onClick(View v) { // AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); // builder.setTitle(getResources().getString(R.string.visibility)); // builder.setItems(R.array.visibility, // new DialogInterface.OnClickListener() { // // @Override // must match @array/visibility in strings.xml // public void onClick(DialogInterface dialog, int click_idx) { // switch (click_idx) { // case 0: // anyone // setPrivacy(1); // break; // case 1: // members // setPrivacy(4); // break; // case 2: // request // setPrivacy(0); // break; // case 3: // none // setPrivacy(5); // break; // } // if (privacyListener != null) // privacyListener.onPrivacyChange(key, privacy); // } // }).show(); // } // // private void drawIcons(int resId) { // icon.setImageDrawable(new LayerDrawable(new Drawable[] { // getResources().getDrawable(imageResId), // getResources().getDrawable(resId) // })); // } // // public void setPrivacyListener(String key, PrivacyListener listener) { // this.privacyListener = listener; // this.key = key; // } // // public interface PrivacyListener { // public void onPrivacyChange(String key, int visibility); // } // } // // Path: src/main/java/de/fahrgemeinschaft/util/PrivacyImageButton.java // public interface PrivacyListener { // public void onPrivacyChange(String key, int visibility); // } // Path: src/main/java/de/fahrgemeinschaft/EditRideFragment3.java import org.json.JSONException; import org.json.JSONObject; import org.teleportr.Ride; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.actionbarsherlock.app.SherlockFragment; import de.fahrgemeinschaft.ContactProvider.CONTACT; import de.fahrgemeinschaft.util.EditTextImageButton.TextListener; import de.fahrgemeinschaft.util.PrivacyImageButton; import de.fahrgemeinschaft.util.PrivacyImageButton.PrivacyListener; /** * Fahrgemeinschaft / Ridesharing App * Copyright (c) 2013 by it's authors. * Some rights reserved. See LICENSE.. * */ package de.fahrgemeinschaft; public class EditRideFragment3 extends SherlockFragment implements TextListener, PrivacyListener { private static final String NAME = "Name"; private static final String EMPTY = ""; private PrivacyImageButton mobile; private PrivacyImageButton plate; private PrivacyImageButton email; private PrivacyImageButton land; private PrivacyImageButton name; private SharedPreferences prefs; @Override public View onCreateView(final LayoutInflater lI, ViewGroup p, Bundle b) { prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); return lI.inflate(R.layout.fragment_ride_edit3, p, false); } @Override public void onViewCreated(View v, Bundle savedInstanceState) { super.onViewCreated(v, savedInstanceState); email = (PrivacyImageButton) v.findViewById(R.id.email); land = (PrivacyImageButton) v.findViewById(R.id.landline); mobile = (PrivacyImageButton) v.findViewById(R.id.mobile); plate = (PrivacyImageButton) v.findViewById(R.id.plate); name = (PrivacyImageButton) v.findViewById(R.id.name);
email.setTextListener(CONTACT.EMAIL, this);
fahrgemeinschaft/android-app
src/main/java/de/fahrgemeinschaft/BaseActivity.java
// Path: src/main/java/de/fahrgemeinschaft/ContactProvider.java // public static final class CONTACT { // public static final String USER = "user"; // public static final String EMAIL = "Email"; // public static final String PLATE = "NumberPlate"; // public static final String MOBILE = "Mobile"; // public static final String LANDLINE = "Landline"; // } // // Path: src/main/java/de/fahrgemeinschaft/util/SpinningZebraListFragment.java // public interface ListFragmentCallback { // public void onListItemClick(int position, int id); // public void onSpinningWheelClick(); // }
import org.json.JSONException; import org.json.JSONObject; import org.teleportr.ConnectorService; import org.teleportr.ConnectorService.ServiceCallback; import org.teleportr.Ride.COLUMNS; import org.teleportr.RidesProvider; import android.app.NotificationManager; import android.content.ComponentName; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.IBinder; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentManager.OnBackStackChangedListener; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.Log; import android.view.View; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import de.fahrgemeinschaft.ContactProvider.CONTACT; import de.fahrgemeinschaft.util.SpinningZebraListFragment.ListFragmentCallback; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.Style;
class GetContactsFromMyridesTask extends AsyncTask<String, String, String> { private static final String EMPTY = ""; @Override protected String doInBackground(String... params) { Log.d(TAG, "getting contacts from myrides"); Cursor mr = getContentResolver().query(RidesProvider .getMyRidesUri(BaseActivity.this), null, null, null, null); System.out.println("myrides: " + mr.getCount()); for (int i = 0; i < mr.getCount(); i++) { mr.moveToPosition(i); try { storeContacts(new JSONObject( mr.getString(COLUMNS.DETAILS))); } catch (JSONException e) { Log.e(TAG, "error getting myride details"); e.printStackTrace(); } } PreferenceManager.getDefaultSharedPreferences(BaseActivity.this) .edit().remove(ProfileFragment.INIT_CONTACTS).commit(); Log.d(TAG, "got contacts from myrides"); return null; } public void storeContacts(JSONObject details) throws JSONException { ContentValues cv = new ContentValues();
// Path: src/main/java/de/fahrgemeinschaft/ContactProvider.java // public static final class CONTACT { // public static final String USER = "user"; // public static final String EMAIL = "Email"; // public static final String PLATE = "NumberPlate"; // public static final String MOBILE = "Mobile"; // public static final String LANDLINE = "Landline"; // } // // Path: src/main/java/de/fahrgemeinschaft/util/SpinningZebraListFragment.java // public interface ListFragmentCallback { // public void onListItemClick(int position, int id); // public void onSpinningWheelClick(); // } // Path: src/main/java/de/fahrgemeinschaft/BaseActivity.java import org.json.JSONException; import org.json.JSONObject; import org.teleportr.ConnectorService; import org.teleportr.ConnectorService.ServiceCallback; import org.teleportr.Ride.COLUMNS; import org.teleportr.RidesProvider; import android.app.NotificationManager; import android.content.ComponentName; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.IBinder; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentManager.OnBackStackChangedListener; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.Log; import android.view.View; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import de.fahrgemeinschaft.ContactProvider.CONTACT; import de.fahrgemeinschaft.util.SpinningZebraListFragment.ListFragmentCallback; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.Style; class GetContactsFromMyridesTask extends AsyncTask<String, String, String> { private static final String EMPTY = ""; @Override protected String doInBackground(String... params) { Log.d(TAG, "getting contacts from myrides"); Cursor mr = getContentResolver().query(RidesProvider .getMyRidesUri(BaseActivity.this), null, null, null, null); System.out.println("myrides: " + mr.getCount()); for (int i = 0; i < mr.getCount(); i++) { mr.moveToPosition(i); try { storeContacts(new JSONObject( mr.getString(COLUMNS.DETAILS))); } catch (JSONException e) { Log.e(TAG, "error getting myride details"); e.printStackTrace(); } } PreferenceManager.getDefaultSharedPreferences(BaseActivity.this) .edit().remove(ProfileFragment.INIT_CONTACTS).commit(); Log.d(TAG, "got contacts from myrides"); return null; } public void storeContacts(JSONObject details) throws JSONException { ContentValues cv = new ContentValues();
if (details.has(CONTACT.EMAIL))