repo_name
stringlengths
7
104
file_path
stringlengths
11
238
context
list
import_statement
stringlengths
103
6.85k
code
stringlengths
60
38.4k
next_line
stringlengths
10
824
gold_snippet_index
int32
0
8
nikhaldi/android-view-selector
src/test-lib/src/com/nikhaldimann/viewselector/test/abstrakt/AbstractViewSelectorAssertionsTest.java
[ "public static ViewSelectionAssert assertThat(ViewSelection actual) {\n return new ViewSelectionAssert(actual);\n}", "public static ViewSelectionAssert assertThatSelection(String selector, Activity activity) {\n return assertThat(selection(selector, activity));\n}", "public static Attributes extractAttribute(String attributeName) {\n return new Attributes(attributeName);\n}", "public static ViewSelection selection(String selector, Activity activity) {\n return selection(selector, activity.findViewById(android.R.id.content));\n}", "public abstract class ViewSelectorAndroidTestCase extends AndroidTestCase {\n\n protected ViewFactory viewFactory;\n\n @Before\n public void setUp() throws Exception {\n super.setUp();\n viewFactory = createViewFactory();\n }\n\n /**\n * @return the factory to be used for creating views in this test\n */\n protected abstract ViewFactory createViewFactory();\n\n /**\n * Reimplementation of Android's MoreAsserts.assertContentsInOrder() because we\n * can't use MoreAsserts in Robolectric 1.2.\n */\n public static void assertContentsInOrder(Iterable<?> actual, Object... expected) {\n ArrayList<Object> actualList = new ArrayList<Object>();\n for (Object o : actual) {\n actualList.add(o);\n }\n assertEquals(Arrays.asList(expected), actualList);\n }\n}" ]
import static com.nikhaldimann.viewselector.ViewSelectorAssertions.assertThat; import static com.nikhaldimann.viewselector.ViewSelectorAssertions.assertThatSelection; import static com.nikhaldimann.viewselector.ViewSelectorAssertions.extractAttribute; import static com.nikhaldimann.viewselector.ViewSelectorAssertions.selection; import org.junit.Test; import android.widget.TextView; import com.nikhaldimann.viewselector.test.util.ViewSelectorAndroidTestCase;
package com.nikhaldimann.viewselector.test.abstrakt; public abstract class AbstractViewSelectorAssertionsTest extends ViewSelectorAndroidTestCase { /** * Fails with a RuntimeException, so we can distinguish this from planned * assertion failures. */ private void failHard() { throw new RuntimeException("Failed to cause an assertion failure"); } @Test public void testAssertThat() { TextView view = viewFactory.createTextView();
assertThat(selection("TextView", view))
3
wangchongjie/multi-task
src/main/java/com/baidu/unbiz/multitask/task/thread/TaskWrapper.java
[ "public class TaskPair extends Pair<String, Object> {\n\n public TaskPair() {\n }\n\n public TaskPair(String taskName, Object param) {\n this.field1 = taskName;\n this.field2 = param;\n }\n\n public TaskPair wrap(String taskName, Object param) {\n return new TaskPair(taskName, param);\n }\n}", "@Component\npublic class TaskBeanContainer implements ApplicationContextAware, PriorityOrdered {\n\n private static final Log LOG = LogFactory.getLog(TaskBeanContainer.class);\n\n // Spring应用上下文环境\n private static ApplicationContext applicationContext;\n private static Map<String, Taskable<?>> container = new ConcurrentHashMap<String, Taskable<?>>();\n private static AtomicBoolean initing = new AtomicBoolean(false);\n private static CountDownLatch hasInit = new CountDownLatch(1);\n private static volatile String springContainerInstanceFlag = \"\";\n\n // @PostConstruct\n public static void initFetcherContainer() {\n initFetcherContainer(applicationContext);\n }\n\n /**\n * 初始化Fetcher容器\n *\n * @param factory\n */\n public static void initFetcherContainer(ListableBeanFactory factory) {\n if (initing.get()) {\n waitInit();\n return;\n }\n if (initing.compareAndSet(false, true)) {\n Map<String, Object> fetcherServices = factory.getBeansWithAnnotation(TaskService.class);\n for (Object service : fetcherServices.values()) {\n regiserOneService(service);\n }\n hasInit.countDown();\n } else {\n waitInit();\n }\n }\n\n private static void waitInit() {\n try {\n hasInit.await();\n } catch (InterruptedException e) {\n LOG.error(\"Interrupted while waiting init.\", e);\n }\n }\n\n /**\n * 向容器中注册一个service中带FetcherBean的方法,并包装成Fetcher\n *\n * @param service\n */\n public static void regiserOneService(Object service) {\n Class<?> clazz = service.getClass();\n for (Method method : ReflectionUtils.getAllDeclaredMethods(clazz)) {\n TaskBean bean = method.getAnnotation(TaskBean.class);\n if (bean != null) {\n registerFetcher(service, method, bean.value());\n }\n }\n }\n\n /**\n * 优先使用@Resource方式注入,此处为预留接口,也可获取Fetcher Bean\n *\n * @param beanName\n *\n * @return bean\n */\n @SuppressWarnings(\"unchecked\")\n public <T> T bean(String beanName) {\n T bean = (T) container.get(beanName);\n if (bean != null) {\n return bean;\n } else {\n return (T) TaskBeanContainer.getBean(beanName);\n }\n }\n\n public Taskable<?> task(String beanName) {\n return bean(beanName);\n }\n\n /**\n * 注册一个Fetcher\n *\n * @param service\n * @param method\n * @param beanName\n */\n private static void registerFetcher(final Object service, final Method method, final String beanName) {\n if (TaskBeanContainer.containsBean(beanName)) {\n throw new TaskBizException(\"Fetcher bean duplicate for Spring:\" + beanName);\n }\n\n final int paramLen = method.getGenericParameterTypes().length;\n Taskable<?> fetcher = TaskBeanHelper.newFetcher(service, method, beanName, paramLen);\n\n BeanFactory factory = applicationContext.getAutowireCapableBeanFactory();\n\n if (factory instanceof DefaultListableBeanFactory) {\n DefaultListableBeanFactory defaultFactory = (DefaultListableBeanFactory) factory;\n defaultFactory.registerSingleton(beanName, fetcher);\n // GenericBeanDefinition beanDefinition = new GenericBeanDefinition();\n // beanDefinition.setBeanClass(task.getClass());\n // listFactory.registerBeanDefinition(beanName, beanDefinition);\n LOG.info(\"DefaultListableBeanFactory Fetcher register: \" + beanName);\n } else if (factory instanceof AbstractBeanFactory) {\n AbstractBeanFactory abstFactory = (AbstractBeanFactory) factory;\n abstFactory.registerSingleton(beanName, fetcher);\n LOG.info(\"AbstractBeanFactory Fetcher register: \" + beanName);\n } else {\n container.put(beanName, fetcher);\n LOG.info(\"LocalContainer Fetcher register: \" + beanName);\n }\n }\n\n /**\n * 显式注册TaskBean\n *\n * @param service\n * @param beanName\n * @param funcName\n * @param paramsType\n */\n public static void registerTaskBean(Object service, String beanName, String funcName, Class<?>... paramsType) {\n Method method = null;\n try {\n method = service.getClass().getMethod(funcName, paramsType);\n } catch (NoSuchMethodException e) {\n LOG.error(\"register TaskBean fail:\", e);\n }\n registerFetcher(service, method, beanName);\n }\n\n /**\n * spring bean是否存在\n *\n * @param name\n *\n * @return spring bean是否存在\n */\n public static boolean containsBean(String name) {\n return applicationContext.containsBean(name);\n }\n\n /**\n * 获取spring bean\n *\n * @param name\n *\n * @return spring bean\n */\n @SuppressWarnings(\"unchecked\")\n public static <T> T getBean(String name) {\n return (T) applicationContext.getBean(name);\n }\n\n /**\n * 设置spring上下文\n */\n @Override\n public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {\n TaskBeanContainer.applicationContext = applicationContext;\n String newValue = String.valueOf(applicationContext.hashCode());\n LOG.info(\"fetcherBean container id:\" + newValue);\n // 不同的Spring Context Refreshing,允许重新初始化,此处不会有并发\n if (!springContainerInstanceFlag.equals(newValue)) {\n hasInit = new CountDownLatch(1);\n initing.set(false);\n initFetcherContainer();\n springContainerInstanceFlag = newValue;\n }\n }\n\n /**\n * 设置spring构建优先级\n */\n @Override\n public int getOrder() {\n return PriorityOrdered.HIGHEST_PRECEDENCE;\n }\n}", "public interface Taskable<T> {\n\n /**\n * 执行数据获取\n * \n * @param request\n * @return 返回结果\n * @since 2015-7-3 by wangchongjie\n */\n <E> T work(E request);\n\n}", "public class ArrayUtils {\n /**\n * 判断数组是否为空\n * \n * @param array\n * @return boolean\n */\n public static <T> boolean isArrayEmpty(T[] array) {\n if (null == array || array.length <= 0) {\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * 数据是否非空\n * \n * @param array 数组\n * @since 2015-7-28 by wangchongjie\n * @return boolean\n */\n public static <T> boolean isArrayNotEmpty(T[] array) {\n return !isArrayEmpty(array);\n }\n\n /**\n * 数组转列表\n * \n * @param array\n * @since 2015-7-28\n * @return List\n */\n public static <T> List<T> arrayToList(T[] array) {\n return isArrayEmpty(array) ? new ArrayList<T>(1) : Arrays.asList(array);\n }\n}", "public class AssistUtils {\n\n /**\n * 去除taskBean中的版本标识\n *\n * @param taskBean\n * @return\n */\n public static String removeTaskVersion(String taskBean) {\n return taskBean.replaceAll(TaskConfig.TASKNAME_SEPARATOR + \".*\", \"\");\n }\n}" ]
import java.util.ArrayList; import java.util.List; import java.util.Set; import com.baidu.unbiz.multitask.common.TaskPair; import com.baidu.unbiz.multitask.spring.integration.TaskBeanContainer; import com.baidu.unbiz.multitask.task.Taskable; import com.baidu.unbiz.multitask.utils.ArrayUtils; import com.baidu.unbiz.multitask.utils.AssistUtils;
package com.baidu.unbiz.multitask.task.thread; /** * 报表数据抓取类包装器,包装为可执行类 * * @author wangchongjie * @since 2015-11-21 下午7:57:58 */ public class TaskWrapper implements Runnable { /** * 可并行执行的fetcher */ private Taskable<?> fetcher; /** * fetcher名称 */ private String fetcherName; /** * 参数封装 */ private Object args; /** * 并行执行上下文 */ private TaskContext context; /** * 将Fetcher包装,绑定执行上下文 * * @param fetcher * @param args * @param context */ public <T> TaskWrapper(Taskable<?> fetcher, Object args, TaskContext context) { this.fetcher = fetcher; // 此处参数有可能为null(暂不限制),应用时需注意 this.args = args; this.context = context; } public <T> TaskWrapper(Taskable<?> fetcher, Object args, TaskContext context, String fetcherName) { this.fetcher = fetcher; // 此处参数有可能为null(暂不限制),应用时需注意 this.args = args; this.context = context; this.fetcherName = fetcherName; } /** * 将Fetcher构建成包装类 * * @param container * @param context * @param queryPairs * * @return TaskWrapper List */ public static List<TaskWrapper> wrapperFetcher(TaskBeanContainer container, TaskContext context, TaskPair... queryPairs) { List<TaskWrapper> fetchers = new ArrayList<TaskWrapper>(); if (ArrayUtils.isArrayEmpty(queryPairs)) { return fetchers; } // wrap task for (TaskPair qp : queryPairs) {
Taskable<?> fetcher = container.bean(AssistUtils.removeTaskVersion(qp.field1));
4
xiaoshanlin000/SLTableView
app/src/main/java/com/shanlin/sltableview/MainActivity.java
[ "public class DefaultFragment extends DemoBaseFragment {\n\n public DefaultFragment() {\n // Required empty public constructor\n }\n\n /**\n * Use this factory method to create a new instance of\n * this fragment using the provided parameters.\n *\n * @return A new instance of fragment DefaultFragment.\n */\n // TODO: Rename and change types and number of parameters\n public static DefaultFragment newInstance( ) {\n DefaultFragment fragment = new DefaultFragment();\n return fragment;\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n }\n\n @Override\n public int layoutId() {\n return R.layout.fragment_default;\n }\n\n @Override\n public void initView(ViewGroup view) {\n tableView = new SLTableView.Builder(context)\n .setTableViewDataSource(this)\n .setTableViewDelegate(this)\n .showStickyHeader(false)\n .build();\n view.addView(tableView);\n }\n\n @Override\n public void initData() {\n dataLists.clear();\n dataLists.add(Arrays.asList(\"类型1\",\"类型1\"));\n dataLists.add(Arrays.asList(\"类型2\",\"类型2\"));\n dataLists.add(Arrays.asList(\"按钮\"));\n if (tableView != null) {\n tableView.getAdapter().notifyDataSetChanged();\n }\n }\n\n\n\n\n @Override\n public void onAttach(Context context) {\n super.onAttach(context);\n\n }\n\n @Override\n public void onDetach() {\n super.onDetach();\n }\n\n}", "public class DouyuFollowFragment extends CellBaseFragment {\n\n\n @Override\n public void initView(ViewGroup view) {\n tableView = new SLTableView.Builder(context)\n .setTableViewDataSource(this)\n .setTableViewDelegate(this)\n .setTableViewLayoutManagerExpand(this)\n .showStickyHeader(false)\n .setBgColor(context.getResources().getColor(R.color.color_white))\n .setLayoutManager(new GridLayoutManager(context,2))\n .build();\n view.addView(tableView);\n }\n @Override\n public void initData() {\n dataLists.clear();\n ArrayList<CellBaseBean> list = new ArrayList<>();\n list.add(new DouyuRoomBean(\"暴走漫画出品\",\"暴走漫画 再看最后一集\",\"6.6万\"));\n list.add(new DouyuRoomBean(\"暴走漫画出品\",\"暴走漫画 再看最后一集\",\"6.6万\"));\n list.add(new DouyuRoomBean(\"暴走漫画出品\",\"暴走漫画 再看最后一集\",\"6.6万\"));\n list.add(new DouyuRoomBean(\"暴走漫画出品\",\"暴走漫画 再看最后一集\",\"6.6万\"));\n list.add(new DouyuRoomBean(\"暴走漫画出品\",\"暴走漫画 再看最后一集\",\"6.6万\"));\n list.add(new DouyuRoomBean(\"暴走漫画出品\",\"暴走漫画 再看最后一集\",\"6.6万\"));\n list.add(new DouyuRoomBean(\"暴走漫画出品\",\"暴走漫画 再看最后一集\",\"6.6万\"));\n list.add(new DouyuRoomBean(\"暴走漫画出品\",\"暴走漫画 再看最后一集\",\"6.6万\"));\n list.add(new DouyuRoomBean(\"凉风有兴\",\"斗鱼第一亚索\",\"8万\"));\n list.add(new DouyuRoomBean(\"凉风有兴\",\"斗鱼第一亚索\",\"8万\"));\n list.add(new DouyuRoomBean(\"凉风有兴\",\"斗鱼第一亚索\",\"8万\"));\n list.add(new DouyuRoomBean(\"凉风有兴\",\"斗鱼第一亚索\",\"8万\"));\n list.add(new DouyuRoomBean(\"文艺冉\",\"七煌|文艺冉 M勇气试炼\",\"2113\"));\n list.add(new DouyuRoomBean(\"文艺冉\",\"七煌|文艺冉 M勇气试炼\",\"2113\"));\n list.add(new DouyuRoomBean(\"文艺冉\",\"七煌|文艺冉 M勇气试炼\",\"2113\"));\n list.add(new DouyuRoomBean(\"文艺冉\",\"七煌|文艺冉 M勇气试炼\",\"2113\"));\n list.add(new DouyuRoomBean(\"战术大师rubick\",\"[战术大师] CDEC大师\",\"4550\"));\n list.add(new DouyuRoomBean(\"战术大师rubick\",\"[战术大师] CDEC大师\",\"4550\"));\n list.add(new DouyuRoomBean(\"战术大师rubick\",\"[战术大师] CDEC大师\",\"4550\"));\n list.add(new DouyuRoomBean(\"战术大师rubick\",\"[战术大师] CDEC大师\",\"4550\"));\n dataLists.add(list);\n tableView.getAdapter().notifyDataSetChanged();\n }\n\n\n //SLTableViewLayoutManagerExpand\n @Override\n public void getItemOffsets(Rect outRect, SLIndexPath indexPath) {\n int section = indexPath.getSection();\n int row = indexPath.getRow();\n if (row % 2 == 0){\n outRect.left = table_padding;\n outRect.right = table_padding_s2;\n outRect.top = row == 0 ? table_padding : table_padding_s2;\n outRect.bottom = table_padding_s2;\n\n }else if(row % 2 == 1){\n outRect.right = table_padding;\n outRect.left = table_padding_s2;\n outRect.top = row == 1 ? table_padding : table_padding_s2;\n outRect.bottom = table_padding_s2;\n }\n }\n}", "public class DouyuFragment extends CellBaseFragment {\n @Override\n public void initView(ViewGroup view) {\n tableView = new SLTableView.Builder(context)\n .setTableViewDataSource(this)\n .setTableViewDelegate(this)\n .setTableViewLayoutManagerExpand(this)\n .showStickyHeader(false)\n .setBgColor(context.getResources().getColor(R.color.color_white))\n .setLayoutManager(new GridLayoutManager(context,2))\n .build();\n view.addView(tableView);\n }\n\n @Override\n public void initData() {\n dataLists.clear();\n ArrayList<CellBaseBean> list = new ArrayList<>();\n list.add(new DouyuHeadBean(\"最热\"));\n list.add(new DouyuRoomBean(\"暴走漫画出品\",\"暴走漫画 再看最后一集\",\"6.6万\"));\n list.add(new DouyuRoomBean(\"暴走漫画出品\",\"暴走漫画 再看最后一集\",\"6.6万\"));\n list.add(new DouyuRoomBean(\"暴走漫画出品\",\"暴走漫画 再看最后一集\",\"6.6万\"));\n list.add(new DouyuRoomBean(\"暴走漫画出品\",\"暴走漫画 再看最后一集\",\"6.6万\"));\n list.add(new DouyuRoomBean(\"暴走漫画出品\",\"暴走漫画 再看最后一集\",\"6.6万\"));\n list.add(new DouyuRoomBean(\"暴走漫画出品\",\"暴走漫画 再看最后一集\",\"6.6万\"));\n list.add(new DouyuRoomBean(\"暴走漫画出品\",\"暴走漫画 再看最后一集\",\"6.6万\"));\n list.add(new DouyuRoomBean(\"暴走漫画出品\",\"暴走漫画 再看最后一集\",\"6.6万\"));\n dataLists.add(list);\n list = new ArrayList<>();\n list.add(new DouyuHeadBean(\"颜值\"));\n list.add(new DouyuYanzhiBean(\"Cherry宛夕\",\"4.1万\",\"北京市\"));\n list.add(new DouyuYanzhiBean(\"Cherry宛夕\",\"4.1万\",\"北京市\"));\n list.add(new DouyuYanzhiBean(\"Cherry宛夕\",\"4.1万\",\"北京市\"));\n list.add(new DouyuYanzhiBean(\"Cherry宛夕\",\"4.1万\",\"北京市\"));\n dataLists.add(list);\n list = new ArrayList<>();\n list.add(new DouyuHeadBean(\"英雄联盟\"));\n list.add(new DouyuRoomBean(\"凉风有兴\",\"斗鱼第一亚索\",\"8万\"));\n list.add(new DouyuRoomBean(\"凉风有兴\",\"斗鱼第一亚索\",\"8万\"));\n list.add(new DouyuRoomBean(\"凉风有兴\",\"斗鱼第一亚索\",\"8万\"));\n list.add(new DouyuRoomBean(\"凉风有兴\",\"斗鱼第一亚索\",\"8万\"));\n dataLists.add(list);\n list = new ArrayList<>();\n list.add(new DouyuHeadBean(\"魔兽世界\"));\n list.add(new DouyuRoomBean(\"文艺冉\",\"七煌|文艺冉 M勇气试炼\",\"2113\"));\n list.add(new DouyuRoomBean(\"文艺冉\",\"七煌|文艺冉 M勇气试炼\",\"2113\"));\n list.add(new DouyuRoomBean(\"文艺冉\",\"七煌|文艺冉 M勇气试炼\",\"2113\"));\n list.add(new DouyuRoomBean(\"文艺冉\",\"七煌|文艺冉 M勇气试炼\",\"2113\"));\n dataLists.add(list);\n list = new ArrayList<>();\n list.add(new DouyuHeadBean(\"DOTA2\"));\n list.add(new DouyuRoomBean(\"战术大师rubick\",\"[战术大师] CDEC大师\",\"4550\"));\n list.add(new DouyuRoomBean(\"战术大师rubick\",\"[战术大师] CDEC大师\",\"4550\"));\n list.add(new DouyuRoomBean(\"战术大师rubick\",\"[战术大师] CDEC大师\",\"4550\"));\n list.add(new DouyuRoomBean(\"战术大师rubick\",\"[战术大师] CDEC大师\",\"4550\"));\n dataLists.add(list);\n list = new ArrayList<>();\n list.add(new DouyuHeadBean(\"热门作者\"));\n list.add(new DouyuHotAuthorBean(\"萝菽菽_acfun\",\"72\",\"9237\"));\n list.add(new DouyuHotAuthorBean(\"鱼小碗\",\"30\",\"437\"));\n dataLists.add(list);\n tableView.getAdapter().notifyDataSetChanged();\n }\n\n //SLTableViewLayoutManagerExpand\n @Override\n public void getItemOffsets(Rect outRect, SLIndexPath indexPath) {\n int section = indexPath.getSection();\n int row = indexPath.getRow();\n CellBaseBean baseBean = dataLists.get(section).get(row);\n if (baseBean.getType() == CellType.CELL_TYPE_DOUYU_HOT_AUTHOR){\n return;\n }\n if (baseBean.getType() == CellType.CELL_TYPE_DOUYU_HEAD){\n return;\n }\n if (row >0 && row % 2 == 1){\n outRect.left = table_padding;\n outRect.right = table_padding_s2;\n outRect.top = table_padding_s2;\n outRect.bottom = table_padding_s2;\n\n }else if(row > 0 && row %2 == 0){\n outRect.right = table_padding;\n outRect.left = table_padding_s2;\n outRect.top = table_padding_s2;\n outRect.bottom = table_padding_s2;\n }\n }\n}", "public class GroupHeaderFragment extends DemoBaseFragment implements SLTableViewLayoutManagerExpand {\n\n\n public GroupHeaderFragment(){\n\n }\n // TODO: Rename and change types and number of parameters\n public static DefaultFragment newInstance( ) {\n DefaultFragment fragment = new DefaultFragment();\n return fragment;\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n }\n\n\n @Override\n public int layoutId() {\n return R.layout.fragment_default;\n }\n\n @Override\n public void initView(ViewGroup view) {\n tableView = new SLTableView.Builder(context)\n .setTableViewDataSource(this)\n .setTableViewDelegate(this)\n .setTableViewLayoutManagerExpand(this)\n .showStickyHeader(false)\n .setHeaderBgColor(context.getResources().getColor(R.color.color_red))\n .setHeaderTextColor(context.getResources().getColor(R.color.color_white))\n .setLayoutManager(new GridLayoutManager(context,2))\n .build();\n view.addView(tableView);\n }\n @Override\n public void initData() {\n dataLists.clear();\n dataLists.add(Arrays.asList(\"类型1\",\"类型1\",\"类型1\",\"类型1\",\"类型1\",\"类型1\"));\n dataLists.add(Arrays.asList(\"类型2\",\"类型2\",\"类型2\",\"类型2\",\"类型2\"));\n dataLists.add(Arrays.asList(\"类型1\",\"类型1\",\"类型1\",\"类型1\",\"类型1\"));\n dataLists.add(Arrays.asList(\"类型2\",\"类型2\",\"类型2\",\"类型2\",\"类型2\"));\n dataLists.add(Arrays.asList(\"类型:按钮\"));\n if (tableView != null) {\n tableView.getAdapter().notifyDataSetChanged();\n }\n }\n\n\n @Override\n public void onAttach(Context context) {\n super.onAttach(context);\n\n }\n\n @Override\n public void onDetach() {\n super.onDetach();\n }\n\n @Override\n public int gridSpanSizeOfIndexPath(SLIndexPath indexPath) {\n int row = indexPath.getRow();\n int section = indexPath.getSection();\n if (section == dataLists.size() - 1 && row == 0){ // 按钮夸两行\n return 2;\n }\n if (row == 2){\n return 2;\n }\n return 0;\n }\n\n @Override\n public void getItemOffsets(Rect outRect, SLIndexPath indexPath) {\n\n }\n}", "public class GroupStickyHeaderFragment extends DemoBaseFragment {\n\n\n public GroupStickyHeaderFragment() {\n\n }\n\n // TODO: Rename and change types and number of parameters\n public static DefaultFragment newInstance() {\n DefaultFragment fragment = new DefaultFragment();\n return fragment;\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n }\n\n @Override\n public int layoutId() {\n return R.layout.fragment_sticky_header;\n }\n\n @Override\n public void initView(ViewGroup view) {\n tableView = new SLTableView.Builder(context)\n .setTableViewDataSource(this)\n .setTableViewDelegate(this)\n .showStickyHeader(true)\n .setHeaderBgColor(context.getResources().getColor(R.color.color_red))\n .setHeaderTextColor(context.getResources().getColor(R.color.color_white))\n .setLayoutManager(new GridLayoutManager(context, 2))\n .build();\n view.addView(tableView);\n }\n\n @Override\n public void initData() {\n dataLists.clear();\n dataLists.add(Arrays.asList(\"类型1\", \"类型1\", \"类型1\", \"类型1\", \"类型1\", \"类型1\", \"类型1\", \"类型1\", \"类型1\"));\n dataLists.add(Arrays.asList(\"类型2\", \"类型2\", \"类型2\", \"类型2\", \"类型2\", \"类型2\", \"类型2\", \"类型2\"));\n dataLists.add(Arrays.asList(\"类型1\", \"类型1\", \"类型1\", \"类型1\", \"类型1\", \"类型1\", \"类型1\", \"类型1\"));\n dataLists.add(Arrays.asList(\"类型2\", \"类型2\", \"类型2\", \"类型2\", \"类型2\", \"类型2\", \"类型2\", \"类型2\"));\n dataLists.add(Arrays.asList(\"类型1\", \"类型1\", \"类型1\", \"类型1\", \"类型1\", \"类型1\", \"类型1\", \"类型1\"));\n dataLists.add(Arrays.asList(\"类型2\", \"类型2\", \"类型2\", \"类型2\", \"类型2\", \"类型2\", \"类型2\", \"类型2\"));\n dataLists.add(Arrays.asList(\"类型1\", \"类型1\", \"类型1\", \"类型1\", \"类型1\", \"类型1\", \"类型1\", \"类型1\"));\n dataLists.add(Arrays.asList(\"类型2\", \"类型2\", \"类型2\", \"类型2\", \"类型2\", \"类型2\", \"类型2\", \"类型2\"));\n if (tableView != null) {\n tableView.getAdapter().notifyDataSetChanged();\n }\n }\n\n\n @Override\n public View viewForHeaderInSection(SLTableView tableView, int section) {\n View view = LayoutInflater.from(context).inflate(R.layout.cell_head, null);\n view.setLayoutParams(new ViewGroup.LayoutParams(context.getResources().getDimensionPixelOffset(R.dimen.dimen_80dp), context.getResources().getDimensionPixelOffset(R.dimen.dimen_40dp)));\n return view;\n }\n\n @Override\n public void onBindHeaderInSection(SLTableView tableView, View view, int section) {\n super.onBindHeaderInSection(tableView, view, section);\n TextView textView = view.findViewById(R.id.tv_text);\n textView.setText(\"第\"+section+\"组\");\n }\n\n @Override\n public int typeOfIndexPath(SLTableView tableView, SLIndexPath indexPath) {\n int section = indexPath.getSection();\n return indexPath.getSection() % 2;\n }\n\n @Override\n public boolean hiddenHeaderInSection(SLTableView tableView, int section) {\n return false;\n }\n\n @Override\n public boolean hiddenFooterInSection(SLTableView tableView, int section) {\n return false;\n }\n\n @Override\n public void onAttach(Context context) {\n super.onAttach(context);\n\n }\n\n @Override\n public void onDetach() {\n super.onDetach();\n }\n}", "public class StickyHeaderClickFragment extends DemoBaseFragment {\n\n\n public StickyHeaderClickFragment(){\n\n }\n // TODO: Rename and change types and number of parameters\n public static DefaultFragment newInstance( ) {\n DefaultFragment fragment = new DefaultFragment();\n return fragment;\n }\n private View headerRoot;\n private LinearLayout ll_header ;\n private TextView tv_header ;\n private LinearLayout ll_header2 ;\n private TextView tv_header2 ;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n }\n\n @Override\n public int layoutId() {\n return R.layout.fragment_sticky_header;\n }\n\n @Override\n public void initView(ViewGroup view) {\n headerRoot = inflater.inflate(R.layout.view_sticky_header_click,null,false);\n ll_header = headerRoot.findViewById(R.id.ll_header);\n tv_header = headerRoot.findViewById(R.id.tv_header);\n tv_header.setText(\"clickme\");\n ll_header.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(context,\"header clicked\",Toast.LENGTH_SHORT).show();\n }\n });\n ll_header2 = headerRoot.findViewById(R.id.ll_header2);\n tv_header2 = headerRoot.findViewById(R.id.tv_header2);\n tv_header2.setText(\"clickme2\");\n ll_header2.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(context,\"header 2 clicked\",Toast.LENGTH_SHORT).show();\n }\n });\n tableView = new SLTableView.Builder(context)\n .setTableViewDataSource(this)\n .setTableViewDelegate(this)\n .showStickyHeader(true)\n .setHeaderBgColor(context.getResources().getColor(R.color.color_red))\n .setHeaderTextColor(context.getResources().getColor(R.color.color_white))\n .build();\n view.addView(tableView);\n }\n @Override\n public void initData() {\n dataLists.clear();\n dataLists.add(Arrays.asList(\"类型1\",\"类型1\",\"类型1\",\"类型1\"));\n dataLists.add(Arrays.asList(\"类型1\",\"类型1\",\"类型1\",\"类型1\"));\n dataLists.add(Arrays.asList(\"类型1\",\"类型1\",\"类型1\",\"类型1\"));\n dataLists.add(Arrays.asList(\"类型1\",\"类型1\",\"类型1\",\"类型1\"));\n dataLists.add(Arrays.asList(\"类型1\",\"类型1\",\"类型1\",\"类型1\"));\n dataLists.add(Arrays.asList(\"类型2\",\"类型2\",\"类型2\",\"类型2\"));\n dataLists.add(Arrays.asList(\"类型1\",\"类型1\",\"类型1\",\"类型1\"));\n dataLists.add(Arrays.asList(\"类型2\",\"类型2\",\"类型2\",\"类型2\"));\n dataLists.add(Arrays.asList(\"按钮\"));\n if (tableView != null) {\n tableView.getAdapter().notifyDataSetChanged();\n }\n }\n\n @Override\n public String titleForHeaderInSection(SLTableView tableView, int section) {\n return null;\n }\n\n @Override\n public View viewForHeaderInSection(SLTableView tableView, int section) {\n if (section == 0 ) {\n return headerRoot;\n }\n return super.viewForHeaderInSection(tableView, section);\n }\n\n @Override\n public boolean hiddenHeaderInSection(SLTableView tableView, int section) {\n if (section ==0) {\n return false;\n }\n return true;\n }\n\n @Override\n public void onBindHeaderInSection(SLTableView tableView, View view, int section) {\n super.onBindHeaderInSection(tableView, view, section);\n if (section == 0 ) {\n }\n }\n\n @Override\n public void onAttach(Context context) {\n super.onAttach(context);\n\n }\n\n @Override\n public void onDetach() {\n super.onDetach();\n }\n}", "public class StickyHeaderFragment extends DemoBaseFragment {\n\n\n public StickyHeaderFragment(){\n\n }\n // TODO: Rename and change types and number of parameters\n public static DefaultFragment newInstance( ) {\n DefaultFragment fragment = new DefaultFragment();\n return fragment;\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n }\n\n @Override\n public int layoutId() {\n return R.layout.fragment_sticky_header;\n }\n\n @Override\n public void initView(ViewGroup view) {\n tableView = new SLTableView.Builder(context)\n .setTableViewDataSource(this)\n .setTableViewDelegate(this)\n .showStickyHeader(true)\n .setHeaderBgColor(context.getResources().getColor(R.color.color_red))\n .setHeaderTextColor(context.getResources().getColor(R.color.color_white))\n .build();\n view.addView(tableView);\n }\n @Override\n public void initData() {\n dataLists.clear();\n dataLists.add(Arrays.asList(\"类型1\",\"类型1\",\"类型1\",\"类型1\"));\n dataLists.add(Arrays.asList(\"类型2\",\"类型2\",\"类型2\",\"类型2\"));\n dataLists.add(Arrays.asList(\"类型1\",\"类型1\",\"类型1\",\"类型1\"));\n dataLists.add(Arrays.asList(\"类型2\",\"类型2\",\"类型2\",\"类型2\"));\n dataLists.add(Arrays.asList(\"按钮\"));\n if (tableView != null) {\n tableView.getAdapter().notifyDataSetChanged();\n }\n }\n\n\n @Override\n public void onAttach(Context context) {\n super.onAttach(context);\n\n }\n\n @Override\n public void onDetach() {\n super.onDetach();\n }\n}", "public class UserInfoFragment extends CellBaseFragment implements TimePopupWindow.OnTimeSelectListener {\n\n @Override\n public void initView(ViewGroup view) {\n tableView = new SLTableView.Builder(context)\n .setTableViewDataSource(this)\n .setTableViewDelegate(this)\n .setTableViewLayoutManagerExpand(this)\n .showStickyHeader(false)\n .setBgColor(context.getResources().getColor(R.color.color_background))\n .setLayoutManager(new GridLayoutManager(context, 1))\n .build();\n view.addView(tableView);\n }\n\n @Override\n public void initData() {\n dataLists.clear();\n ArrayList<CellBaseBean> arrayList = new ArrayList<>();\n arrayList.add(new EditTextBean().setIcon(R.drawable.img_person_black)\n .setHint(\"请输入昵称\").setKey(\"nickname\").setRequiredValue(true)\n );\n arrayList.add(new LineBean());\n arrayList.add(new DateSelectorBean().setIcon(R.drawable.img_person_black)\n .setContent(\"生日\").setKey(\"birthday\").setRequiredValue(true));\n arrayList.add(new LineBean());\n arrayList.add(new GenderSelectorBean().setIcon(R.drawable.img_person_black)\n .setFemaleStr(\"女\").setMaleStr(\"男\")\n .setGender(\"1\").setKey(\"gender\").setRequiredValue(true));\n dataLists.add(arrayList);\n\n arrayList = new ArrayList<>();\n arrayList.add(new EditTextUnitBean().setIcon(R.drawable.img_person_black)\n .setHint(\"请输入身高\").setUnit(\"cm\")\n .setInputType(EditorInfo.TYPE_CLASS_NUMBER).setKey(\"height\").setRequiredValue(true));\n arrayList.add(new LineBean());\n arrayList.add(new EditTextUnitBean().setIcon(R.drawable.img_person_black)\n .setHint(\"请输入体重\").setUnit(\"kg\")\n .setInputType(EditorInfo.TYPE_CLASS_NUMBER).setKey(\"weight\").setRequiredValue(true));\n dataLists.add(arrayList);\n\n arrayList = new ArrayList<>();\n arrayList.add(new CheckBoxBean().setIcon(R.drawable.img_person_black)\n .setContent(\"喜欢唱歌\").setKey(\"sing\"));\n arrayList.add(new LineBean());\n arrayList.add(new CheckBoxBean().setIcon(R.drawable.img_person_black)\n .setContent(\"喜欢跳舞\").setKey(\"dance\"));\n dataLists.add(arrayList);\n\n arrayList = new ArrayList<>();\n arrayList.add(new ButtonBean().setText(\"保存\"));\n dataLists.add(arrayList);\n\n tableView.notifyDataSetChanged();\n }\n\n\n @Override\n public boolean hiddenHeaderInSection(SLTableView tableView, int section) {\n if (section == dataLists.size() - 1) {\n return true;\n }\n return false;\n }\n\n @Override\n public View viewForHeaderInSection(SLTableView tableView, int section) {\n View view = new View(context);\n view.setLayoutParams(new ViewGroup.LayoutParams(context.getResources().getDisplayMetrics().widthPixels,\n context.getResources().getDimensionPixelSize(R.dimen.cell_padding_x2)));\n return view;\n }\n\n @Override\n public void onCellViewClick(View view, SLIndexPath indexPath, Object userData) {\n int section = indexPath.getSection();\n int row = indexPath.getRow();\n CellBaseBean bean = dataLists.get(section).get(row);\n switch (bean.getType()) {\n case CELL_TYPE_BUTTON: {\n HashMap<String, Object> values = new HashMap<>();\n values.putAll(tableView.keyValues());\n //获取每个cell 的key value\n Toast.makeText(context, values.toString(), Toast.LENGTH_SHORT).show();\n break;\n }\n case CELL_TYPE_DATE_SELECTOR: {\n showDataPicker();\n break;\n }\n }\n }\n\n\n public void showDataPicker() {\n Calendar d = Calendar.getInstance(Locale.CHINA);\n //创建一个日历引用d,通过静态方法getInstance() 从指定时区 Locale.CHINA 获得一个日期实例\n Date myDate = new Date();\n //创建一个Date实例\n d.setTime(myDate);\n //设置日历的时间,把一个新建Date实例myDate传入\n int year = d.get(Calendar.YEAR);\n TimePopupWindow timePopupWindow = new TimePopupWindow(context, TimePopupWindow.Type.YEAR_MONTH_DAY);\n timePopupWindow.setTime(new Date(System.currentTimeMillis()));\n timePopupWindow.setCyclic(true);\n timePopupWindow.setOnTimeSelectListener(this);\n timePopupWindow.setRange(1900, year);\n timePopupWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);\n }\n\n @Override\n public void onTimeSelect(Date date) {\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd\");\n String selectDay = dateFormat.format(date);\n DateSelectorBean bean = (DateSelectorBean) dataLists.get(0).get(2);\n bean.setDate(selectDay);\n tableView.notifyDataSetChanged();\n }\n}" ]
import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import com.shanlin.sltableview.fragment.DefaultFragment; import com.shanlin.sltableview.fragment.DouyuFollowFragment; import com.shanlin.sltableview.fragment.DouyuFragment; import com.shanlin.sltableview.fragment.GroupHeaderFragment; import com.shanlin.sltableview.fragment.GroupStickyHeaderFragment; import com.shanlin.sltableview.fragment.StickyHeaderClickFragment; import com.shanlin.sltableview.fragment.StickyHeaderFragment; import com.shanlin.sltableview.fragment.UserInfoFragment;
package com.shanlin.sltableview; public class MainActivity extends AppCompatActivity { private Activity context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); context = this; HeaderPagerAdapter adapter = new HeaderPagerAdapter(this.getSupportFragmentManager()); ViewPager pager = (ViewPager) this.findViewById(R.id.pager); pager.setAdapter(adapter); } class HeaderPagerAdapter extends FragmentPagerAdapter { public HeaderPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { switch (position) { case 0:
return new DouyuFragment();
2
hecoding/Pac-Man
src/jeco/core/optimization/threads/MasterWorkerThreads.java
[ "public abstract class Algorithm<V extends Variable<?>> extends AlgObservable {\n\n protected Problem<V> problem = null;\n // Attribute to stop execution of the algorithm.\n protected boolean stop = false;\n \n /**\n * Allows to stop execution after finishing the current generation; must be\n * taken into account in children classes.\n */\n public void stopExection() {\n stop = true;\n }\n\n public boolean isStopped() {\n return this.stop;\n }\n\n public Algorithm(Problem<V> problem) {\n this.problem = problem;\n }\n\n public void setProblem(Problem<V> problem) {\n this.problem = problem;\n }\n\n public abstract void initialize();\n\n public abstract void step();\n\n public abstract Solutions<V> execute();\n}", "public class GrammaticalEvolution extends Algorithm<Variable<Integer>> {\n \n public static final Logger logger = Logger.getLogger(NSGAII.class.getName());\n private boolean NEUTRALMUTATION = false;\n private static final boolean jecoPopulationMerge = false; // true if you want to mix old and new generations and then select best individuals\n\n /////////////////////////////////////////////////////////////////////////\n protected int maxGenerations;\n protected int maxPopulationSize;\n /////////////////////////////////////////////////////////////////////////\n protected Comparator<Solution<Variable<Integer>>> dominance;\n protected int currentGeneration;\n protected Solutions<Variable<Integer>> population;\n public Solutions<Variable<Integer>> getPopulation() { return population; }\n protected MutationOperator<Variable<Integer>> mutationOperator;\n protected NeutralMutation<Variable<Integer>> neutralMutation;\n protected CrossoverOperator<Variable<Integer>> crossoverOperator;\n protected SelectionOperator<Variable<Integer>> selectionOperator;\n /////////////////////////////////////////////////////////////////////////\n public Solution<Variable<Integer>> absoluteBest;\n public ArrayList<ArrayList<Double>> absoluteBestObjetives;\n public ArrayList<ArrayList<Double>> bestObjetives;\n public ArrayList<ArrayList<Double>> averageObjetives;\n public ArrayList<ArrayList<Double>> worstObjetives;\n ////////////////////////////////////////////////////////////////////////\n private final int eliteSize;\n\n public GrammaticalEvolution(Problem<Variable<Integer>> problem, int maxPopulationSize, int maxGenerations, double probMutation, double probCrossover, int eliteSize) {\n super(problem);\n this.maxPopulationSize = maxPopulationSize;\n this.maxGenerations = maxGenerations;\n this.mutationOperator = new IntegerFlipMutation<Variable<Integer>>(problem, probMutation);\n this.neutralMutation = new NeutralMutation<Variable<Integer>>(problem, probMutation);\n this.crossoverOperator = new SinglePointCrossover<Variable<Integer>>(problem, SinglePointCrossover.DEFAULT_FIXED_CROSSOVER_POINT, probCrossover, SinglePointCrossover.ALLOW_REPETITION);\n this.selectionOperator = new BinaryTournamentNSGAII<Variable<Integer>>();\n \n this.absoluteBestObjetives = new ArrayList<>(this.maxGenerations);\n this.bestObjetives = new ArrayList<>(this.maxGenerations);\n this.averageObjetives = new ArrayList<>(this.maxGenerations);\n this.worstObjetives = new ArrayList<>(this.maxGenerations);\n \n this.eliteSize = eliteSize;\n }\n\n public GrammaticalEvolution(Problem<Variable<Integer>> problem, int maxPopulationSize, int maxGenerations, double probMutation, double probCrossover, int eliteSize, boolean neutralMutation) {\n this(problem, maxPopulationSize, maxGenerations, probMutation, probCrossover, eliteSize);\n this.NEUTRALMUTATION = neutralMutation;\n }\n\n public GrammaticalEvolution(Problem<Variable<Integer>> problem, int maxPopulationSize, int maxGenerations) {\n this(problem, maxPopulationSize, maxGenerations, 1.0/problem.getNumberOfVariables(), SinglePointCrossover.DEFAULT_PROBABILITY, EliteSelectorOperator.DEFAULT_ELITE_SIZE);\n }\n\n @Override\n public void initialize() {\n dominance = new SolutionDominance<Variable<Integer>>();\n // Create the initial solutionSet\n population = problem.newRandomSetOfSolutions(maxPopulationSize);\n problem.evaluate(population);\n // Compute crowding distance\n CrowdingDistance<Variable<Integer>> assigner = new CrowdingDistance<Variable<Integer>>(problem.getNumberOfObjectives());\n assigner.execute(population);\n currentGeneration = 0;\n }\n\n @Override\n public Solutions<Variable<Integer>> execute() {\n int nextPercentageReport = 10;\n this.notifyStart();\n \n while (!this.stop && currentGeneration < maxGenerations) {\n step();\n int percentage = Math.round((currentGeneration * 100) / maxGenerations);\n if (percentage == nextPercentageReport) {\n logger.info(percentage + \"% performed ...\");\n logger.info(\"@ # Gen. \"+currentGeneration+\", objective values:\");\n // Print current population\n Solutions<Variable<Integer>> pop = this.getPopulation();\n for (Solution<Variable<Integer>> s : pop) {\n for (int i=0; i<s.getObjectives().size();i++) {\n logger.fine(s.getObjective(i)+\";\");\n }\n }\n nextPercentageReport += 10;\n }\n \n this.collectStatistics();\n \n // Notify observers about current generation (object can be a map with more data)\n this.setChanged();\n this.notifyObservers(currentGeneration);\n }\n this.notifyEnd();\n return this.getCurrentSolution();\n }\n\n public Solutions<Variable<Integer>> getCurrentSolution() {\n population.reduceToNonDominated(dominance);\n return population;\n }\n\n public void step() {\n currentGeneration++;\n // Create the offSpring solutionSet\n if (population.size() < 2) {\n logger.severe(\"Generation: \" + currentGeneration + \". Population size is less than 2.\");\n return;\n }\n\n Solutions<Variable<Integer>> childPop = new Solutions<Variable<Integer>>();\n Solution<Variable<Integer>> parent1, parent2;\n for (int i = 0; i < (maxPopulationSize / 2); i++) {\n //obtain parents\n parent1 = selectionOperator.execute(population).get(0);\n parent2 = selectionOperator.execute(population).get(0);\n if(NEUTRALMUTATION){\n\t neutralMutation.execute(parent1);\n\t neutralMutation.execute(parent2);\n }\n Solutions<Variable<Integer>> offSpring = crossoverOperator.execute(parent1, parent2);\n for (Solution<Variable<Integer>> solution : offSpring) {\n childPop.add(solution);\n }\n } // for\n \n \n //For de mutación\n for (Solution<Variable<Integer>> solution : childPop) {\n mutationOperator.execute(solution);\n }\n \n //Eval\n problem.evaluate(childPop);\n\n if(jecoPopulationMerge) {\n \t// Create the solutionSet union of solutionSet and offSpring\n\t Solutions<Variable<Integer>> mixedPop = new Solutions<Variable<Integer>>();\n\t mixedPop.addAll(population);\n\t mixedPop.addAll(childPop);\n\t \n\t // Reducing the union\n\t population = reduce(mixedPop, maxPopulationSize);\n }\n else {\n \t // Own method \t \n \t population.sort(dominance);\n\t\t for(int i = 0; i < eliteSize; i++) { \t\t\t \n\t\t\t childPop.add(population.get(i));\n\t\t }\n \t \n \t population = reduce(childPop, maxPopulationSize);\n }\n\n logger.fine(\"Generation \" + currentGeneration + \"/\" + maxGenerations + \"\\n\" + population.toString());\n } // step\n\n public Solutions<Variable<Integer>> reduce(Solutions<Variable<Integer>> pop, int maxSize) {\n FrontsExtractor<Variable<Integer>> extractor = new FrontsExtractor<Variable<Integer>>(dominance);\n ArrayList<Solutions<Variable<Integer>>> fronts = extractor.execute(pop);\n\n Solutions<Variable<Integer>> reducedPop = new Solutions<Variable<Integer>>();\n CrowdingDistance<Variable<Integer>> assigner = new CrowdingDistance<Variable<Integer>>(problem.getNumberOfObjectives());\n Solutions<Variable<Integer>> front;\n int i = 0;\n while (reducedPop.size() < maxSize && i < fronts.size()) {\n front = fronts.get(i);\n assigner.execute(front);\n reducedPop.addAll(front);\n i++;\n }\n\n ComparatorNSGAII<Variable<Integer>> comparator = new ComparatorNSGAII<Variable<Integer>>();\n if (reducedPop.size() > maxSize) {\n Collections.sort(reducedPop, comparator);\n while (reducedPop.size() > maxSize) {\n reducedPop.remove(reducedPop.size() - 1);\n }\n }\n return reducedPop;\n }\n \n protected void collectStatistics() {\n\t Solution<Variable<Integer>> currentBest = this.population.get(0);\n\t Comparator<Solution<Variable<Integer>>> comparator = this.dominance;\n\t \n\t if (this.absoluteBest == null || comparator.compare(currentBest, this.absoluteBest) < 0) {\n\t\t this.absoluteBestObjetives.add(currentBest.getObjectives());\n\t\t this.absoluteBest = currentBest;\n\t }\n\t else\n\t\t this.absoluteBestObjetives.add(this.absoluteBest.getObjectives());\n\t \n\t ArrayList<Double> avg = new ArrayList<>(population.get(0).getObjectives().size());\n\t for (int i = 0; i < population.get(0).getObjectives().size(); i++) {\n\t\t avg.add(0.0);\n\t }\n\t for(Solution<Variable<Integer>> sol : this.population) {\n\t\t for (int i = 0; i < sol.getObjectives().size(); i++) {\n\t\t\t avg.set(i, avg.get(i) + sol.getObjective(i));\n\t\t }\n\t }\n\t for (int i = 0; i < avg.size(); i++) {\n\t\t avg.set(i, avg.get(i) / this.maxPopulationSize);\n\t }\n\t this.averageObjetives.add(avg);\n\t \n this.bestObjetives.add(currentBest.getObjectives());\n this.worstObjetives.add(this.population.get(this.maxPopulationSize - 1).getObjectives());\n }\n\n public void setMutationOperator(MutationOperator<Variable<Integer>> mutationOperator) {\n this.mutationOperator = mutationOperator;\n }\n\n public void setCrossoverOperator(CrossoverOperator<Variable<Integer>> crossoverOperator) {\n this.crossoverOperator = crossoverOperator;\n }\n\n public void setSelectionOperator(SelectionOperator<Variable<Integer>> selectionOperator) {\n this.selectionOperator = selectionOperator;\n }\n\n public void setMaxGenerations(int maxGenerations) {\n this.maxGenerations = maxGenerations;\n }\n\n public void setMaxPopulationSize(int maxPopulationSize) {\n this.maxPopulationSize = maxPopulationSize;\n }\n \n public int getCurrentGeneration(){\n\t return this.currentGeneration;\n }\n \n}", "public class GrammaticalEvolution_example extends AbstractProblemGE {\n\tprivate static final Logger logger = Logger.getLogger(GrammaticalEvolution_example.class.getName());\n\n\tprotected ScriptEngine evaluator = null;\n\tprotected double[] func = {0, 4, 30, 120, 340, 780, 1554}; //x^4+x^3+x^2+x\n\n\tpublic GrammaticalEvolution_example(String pathToBnf) {\n\t\tsuper(pathToBnf);\n\t\tScriptEngineManager mgr = new ScriptEngineManager();\n\t\tevaluator = mgr.getEngineByName(\"JavaScript\");\n\t}\n\n\tpublic void evaluate(Solution<Variable<Integer>> solution, Phenotype phenotype) {\n\t\tString originalFunction = phenotype.toString();\n\t\tdouble error, totError = 0, maxError = Double.NEGATIVE_INFINITY;\n\t\tfor(int i=0; i<func.length; ++i) {\n\t\t\tString currentFunction = originalFunction.replaceAll(\"X\", String.valueOf(i));\t\n\t\t\tdouble funcI;\n\t\t\ttry {\n\t\t\t\tString aux = evaluator.eval(currentFunction).toString();\n\t\t\t\tif(aux.equals(\"NaN\"))\n\t\t\t\t\tfuncI = Double.POSITIVE_INFINITY;\n\t\t\t\telse\n\t\t\t\t\tfuncI = Double.valueOf(aux);\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t\tlogger.severe(e.getLocalizedMessage());\n\t\t\t\tfuncI = Double.POSITIVE_INFINITY;\n\t\t\t} catch (ScriptException e) {\n\t\t\t\tlogger.severe(e.getLocalizedMessage());\n\t\t\t\tfuncI = Double.POSITIVE_INFINITY;\n\t\t\t}\n\t\t\terror = Math.abs(funcI-func[i]);\n\t\t\ttotError += error;\n\t\t\tif(error>maxError)\n\t\t\t\tmaxError = error;\n\t\t}\n\t\tsolution.getObjectives().set(0, maxError);\n\t\tsolution.getObjectives().set(1, totError);\n\t}\t\n\n @Override\n public GrammaticalEvolution_example clone() {\n \tGrammaticalEvolution_example clone = new GrammaticalEvolution_example(super.pathToBnf);\n \treturn clone;\n }\n\n public static void main(String[] args) {\n\t\t// First create the problem\n\t\tGrammaticalEvolution_example problem = new GrammaticalEvolution_example(\"test/grammar_example.bnf\");\n\t\t// Second create the algorithm\n\t\tGrammaticalEvolution algorithm = new GrammaticalEvolution(problem, 100, 1000);\n\t\talgorithm.initialize();\n\t\tSolutions<Variable<Integer>> solutions = algorithm.execute();\n\t\tfor (Solution<Variable<Integer>> solution : solutions) {\n\t\t\tlogger.info(\"Fitness = (\" + solution.getObjectives().get(0) + \", \" + solution.getObjectives().get(1) + \")\");\n\t\t\tlogger.info(\"Phenotype = (\" + problem.generatePhenotype(solution).toString() + \")\");\n\t\t}\n\t}\t\t\n\n}", "public abstract class Problem<V extends Variable<?>> {\n //private static final Logger logger = Logger.getLogger(Problem.class.getName());\n\n public static final double INFINITY = Double.POSITIVE_INFINITY;\n protected int numberOfVariables;\n protected int numberOfObjectives;\n protected double[] lowerBound;\n protected double[] upperBound;\n\n protected int maxEvaluations;\n protected int numEvaluations;\n\n public Problem(int numberOfVariables, int numberOfObjectives) {\n this.numberOfVariables = numberOfVariables;\n this.numberOfObjectives = numberOfObjectives;\n this.lowerBound = new double[numberOfVariables];\n this.upperBound = new double[numberOfVariables];\n this.maxEvaluations = Integer.MAX_VALUE;\n resetNumEvaluations();\n }\n\n public int getNumberOfVariables() {\n return numberOfVariables;\n }\n\n public int getNumberOfObjectives() {\n return numberOfObjectives;\n }\n\n public double getLowerBound(int i) {\n return lowerBound[i];\n }\n\n public double getUpperBound(int i) {\n return upperBound[i];\n }\n\n public int getMaxEvaluations() {\n return maxEvaluations;\n }\n\n public void setMaxEvaluations(int maxEvaluations) {\n this.maxEvaluations = maxEvaluations;\n }\n\n public int getNumEvaluations() {\n return numEvaluations;\n }\n\n public final void resetNumEvaluations() {\n numEvaluations = 0;\n }\n \n public void setNumEvaluations(int numEvaluations) {\n this.numEvaluations = numEvaluations;\n }\n\n public abstract Solutions<V> newRandomSetOfSolutions(int size);\n\n public void evaluate(Solutions<V> solutions) {\n for (Solution<V> solution : solutions) {\n evaluate(solution);\n }\n }\n\n public abstract void evaluate(Solution<V> solution);\n\n @Override\n public abstract Problem<V> clone();\n\n public boolean reachedMaxEvaluations() {\n return (numEvaluations >= maxEvaluations);\n }\n}", "@SuppressWarnings(\"serial\")\npublic class Solutions<V extends Variable<?>> extends ArrayList<Solution<V>> {\n\n public Solutions() {\n super();\n }\n\n /**\n * Keep this set of solutions non-dominated. Returns the set of dominated\n * solutions.\n *\n * @param comparator Comparator used.\n * @return The set of dominated solutions.\n */\n public Solutions<V> reduceToNonDominated(Comparator<Solution<V>> comparator) {\n Solutions<V> rest = new Solutions<V>();\n int compare;\n Solution<V> solI;\n Solution<V> solJ;\n for (int i = 0; i < size() - 1; i++) {\n solI = get(i);\n for (int j = i + 1; j < size(); j++) {\n solJ = get(j);\n compare = comparator.compare(solI, solJ);\n if (compare < 0) { // i dominates j\n rest.add(solJ);\n remove(j--);\n } else if (compare > 0) { // j dominates i\n rest.add(solI);\n remove(i--);\n j = size();\n } else if (solI.equals(solJ)) { // both are equal, just one copy\n remove(j--);\n }\n }\n }\n return rest;\n }\n\n @Override\n public String toString() {\n StringBuilder buffer = new StringBuilder();\n for (Solution<V> solution : this) {\n buffer.append(solution.toString());\n buffer.append(\"\\n\");\n }\n return buffer.toString();\n }\n\n /**\n * Function that reads a set of solutions from a file.\n * @param filePath File path\n * @return The set of solutions in the archive.\n * @throws IOException \n * @throws java.lang.Exception\n */\n public static Solutions<Variable<?>> readFrontFromFile(String filePath) throws IOException {\n Solutions<Variable<?>> solutions = new Solutions<Variable<?>>();\n BufferedReader reader = new BufferedReader(new FileReader(new File(filePath)));\n String line = reader.readLine();\n while (line != null) {\n String[] objectives = line.split(\" \");\n if (line.length() > 0 && objectives != null && objectives.length > 0) {\n Solution<Variable<?>> solution = new Solution<Variable<?>>(objectives.length);\n for (int i = 0; i < objectives.length; ++i) {\n solution.getObjectives().set(i, Double.valueOf(objectives[i]));\n }\n solutions.add(solution);\n }\n line = reader.readLine();\n }\n reader.close();\n return solutions;\n }\n\n /**\n * Function that reads N sets of solutions from a file.\n *\n * @param filePath File path\n * @return The set of solutions in the archive. Each solution set is separated\n * in the file by a blank line.\n */\n public static ArrayList<Solutions<Variable<?>>> readFrontsFromFile(String filePath) throws FileNotFoundException, IOException {\n ArrayList<Solutions<Variable<?>>> result = new ArrayList<Solutions<Variable<?>>>();\n BufferedReader reader = new BufferedReader(new FileReader(new File(filePath)));\n String line = reader.readLine();\n Solutions<Variable<?>> solutions = new Solutions<Variable<?>>();\n while (line != null) {\n String[] objectives = line.split(\" \");\n if (line.length() <= 0 || objectives == null || objectives.length == 0) {\n if (solutions.size() > 0) {\n result.add(solutions);\n }\n solutions = new Solutions<Variable<?>>();\n } else {\n Solution<Variable<?>> solution = new Solution<Variable<?>>(objectives.length);\n for (int i = 0; i < objectives.length; ++i) {\n solution.getObjectives().set(i, Double.valueOf(objectives[i]));\n }\n solutions.add(solution);\n }\n line = reader.readLine();\n }\n reader.close();\n return result;\n }\n \n /**\n * Function that normalizes a set of fronts in the given interval.\n * @param setOfSolutions Set of fronts\n * @param dim Number of objectives\n * @param lowerBound lower bound\n * @param upperBound upper bound\n */\n public static void normalize(ArrayList<Solutions<Variable<?>>> setOfSolutions, int dim, double lowerBound, double upperBound) {\n double[] mins = new double[dim];\n double[] maxs = new double[dim];\n for (int i = 0; i < dim; ++i) {\n mins[i] = Double.POSITIVE_INFINITY;\n maxs[i] = Double.NEGATIVE_INFINITY;\n }\n\n Solutions<Variable<?>> allTheSolutions = new Solutions<Variable<?>>();\n for (Solutions<Variable<?>> solutions : setOfSolutions) {\n allTheSolutions.addAll(solutions);\n }\n // Get the maximum and minimun values:\n for (Solution<Variable<?>> solution : allTheSolutions) {\n for (int i = 0; i < dim; ++i) {\n double objI = solution.getObjectives().get(i);\n if (objI < mins[i]) {\n mins[i] = objI;\n }\n if (objI > maxs[i]) {\n maxs[i] = objI;\n }\n }\n }\n\n // Normalize:\n for (Solution<Variable<?>> solution : allTheSolutions) {\n for (int i = 0; i < dim; ++i) {\n double objI = solution.getObjectives().get(i);\n double newObjI = 1.0 + (objI - mins[i]) / (maxs[i] - mins[i]);\n solution.getObjectives().set(i, newObjI);\n }\n }\n\n }\n\n /**\n * Function that normalize a set of fronts in the interval [1,2]\n * @param setOfSolutions Set of fronts\n * @param dim Number of objectives\n */\n public static void normalize(ArrayList<Solutions<Variable<?>>> setOfSolutions, int dim) {\n Solutions.normalize(setOfSolutions, dim, 1.0, 2.0);\n } \n}", "public class Variable<T> {\n protected T value;\n\n public Variable(T value) {\n this.value = value;\n }\n\n public T getValue() { return value; }\n\n public void setValue(T value) { this.value = value; }\n \n @Override\n public Variable<T> clone() {\n return new Variable<T>(value);\n }\n\n @SuppressWarnings(\"unchecked\")\n\t\t@Override\n public boolean equals(Object right) {\n Variable<T> var = (Variable<T>)right;\n return this.value.equals(var.value);\n }\n \n @Override\n public String toString()\n {\n \treturn value.toString();\n }\n}" ]
import java.util.ArrayList; import java.util.LinkedList; import java.util.concurrent.LinkedBlockingQueue; import java.util.logging.Level; import java.util.logging.Logger; import jeco.core.algorithm.Algorithm; import jeco.core.algorithm.moge.GrammaticalEvolution; import jeco.core.algorithm.moge.GrammaticalEvolution_example; import jeco.core.problem.Problem; import jeco.core.problem.Solution; import jeco.core.problem.Solutions; import jeco.core.problem.Variable;
package jeco.core.optimization.threads; public class MasterWorkerThreads<V extends Variable<?>> extends Problem<V> { private static final Logger logger = Logger.getLogger(MasterWorkerThreads.class.getName()); protected Algorithm<V> algorithm = null; protected Problem<V> problem = null; protected LinkedBlockingQueue<Solution<V>> sharedQueue = new LinkedBlockingQueue<Solution<V>>(); protected ArrayList<Problem<V>> problemClones = new ArrayList<Problem<V>>(); protected Integer numWorkers = null; public MasterWorkerThreads(Algorithm<V> algorithm, Problem<V> problem, Integer numWorkers) { super(problem.getNumberOfVariables(), problem.getNumberOfObjectives()); for (int i = 0; i < numberOfVariables; ++i) { super.lowerBound[i] = problem.getLowerBound(i); super.upperBound[i] = problem.getUpperBound(i); } this.algorithm = algorithm; this.problem = problem; this.numWorkers = numWorkers; for (int i = 0; i < numWorkers; ++i) { problemClones.add(problem.clone()); } } public MasterWorkerThreads(Algorithm<V> algorithm, Problem<V> problem) { this(algorithm, problem, Runtime.getRuntime().availableProcessors()); } @Override public void evaluate(Solutions<V> solutions) { sharedQueue.addAll(solutions); LinkedList<Worker<V>> workers = new LinkedList<Worker<V>>(); for (int i = 0; i < numWorkers; ++i) { Worker<V> worker = new Worker<V>(problemClones.get(i), sharedQueue); workers.add(worker); worker.start(); } for (Worker<V> worker : workers) { try { worker.join(); } catch (InterruptedException e) { logger.severe(e.getLocalizedMessage()); logger.severe("Main thread cannot join to: " + worker.getId()); } } } @Override public void evaluate(Solution<V> solution) { logger.log(Level.SEVERE, this.getClass().getSimpleName() + "::evaluate() - I do not know why I am here, doing nothing to evaluate solution"); } @Override public Solutions<V> newRandomSetOfSolutions(int size) { return problem.newRandomSetOfSolutions(size); } public Solutions<V> execute() { algorithm.setProblem(this); algorithm.initialize(); return algorithm.execute(); } public void stop() { this.algorithm.stopExection(); } @Override public Problem<V> clone() { logger.severe("This master cannot be cloned."); return null; } public static void main(String[] args) { long begin = System.currentTimeMillis(); // First create the problem
GrammaticalEvolution_example problem = new GrammaticalEvolution_example("test/grammar_example.bnf");
2
witwall/sfntly-java
src/main/java/com/google/typography/font/tools/subsetter/CMapTableSubsetter.java
[ "public class Font {\n\n private static final Logger logger =\n Logger.getLogger(Font.class.getCanonicalName());\n\n /**\n * Offsets to specific elements in the underlying data. These offsets are relative to the\n * start of the table or the start of sub-blocks within the table.\n */\n private enum Offset {\n // Offsets within the main directory\n sfntVersion(0),\n numTables(4),\n searchRange(6),\n entrySelector(8),\n rangeShift(10),\n tableRecordBegin(12),\n sfntHeaderSize(12),\n\n // Offsets within a specific table record\n tableTag(0),\n tableCheckSum(4),\n tableOffset(8),\n tableLength(12),\n tableRecordSize(16);\n\n private final int offset;\n\n private Offset(int offset) {\n this.offset = offset;\n }\n }\n\n /**\n * Ordering of tables for different font types.\n */\n private final static List<Integer> CFF_TABLE_ORDERING;\n private final static List<Integer> TRUE_TYPE_TABLE_ORDERING;\n static {\n Integer[] cffArray = new Integer[] {Tag.head,\n Tag.hhea,\n Tag.maxp,\n Tag.OS_2,\n Tag.name,\n Tag.cmap,\n Tag.post,\n Tag.CFF};\n List<Integer> cffList = new ArrayList<Integer>(cffArray.length);\n Collections.addAll(cffList, cffArray);\n CFF_TABLE_ORDERING = Collections.unmodifiableList(cffList);\n\n Integer[] ttArray = new Integer[] {Tag.head,\n Tag.hhea,\n Tag.maxp,\n Tag.OS_2,\n Tag.hmtx,\n Tag.LTSH,\n Tag.VDMX,\n Tag.hdmx,\n Tag.cmap,\n Tag.fpgm,\n Tag.prep,\n Tag.cvt,\n Tag.loca,\n Tag.glyf,\n Tag.kern,\n Tag.name,\n Tag.post,\n Tag.gasp,\n Tag.PCLT,\n Tag.DSIG};\n List<Integer> ttList = new ArrayList<Integer>(ttArray.length);\n Collections.addAll(ttList, ttArray);\n TRUE_TYPE_TABLE_ORDERING = Collections.unmodifiableList(ttList);\n }\n\n /**\n * Platform ids. These are used in a number of places within the font whenever\n * the platform needs to be specified.\n *\n * @see NameTable\n * @see CMapTable\n */\n public enum PlatformId {\n Unknown(-1), Unicode(0), Macintosh(1), ISO(2), Windows(3), Custom(4);\n\n private final int value;\n\n private PlatformId(int value) {\n this.value = value;\n }\n\n public int value() {\n return this.value;\n }\n\n public boolean equals(int value) {\n return value == this.value;\n }\n\n public static PlatformId valueOf(int value) {\n for (PlatformId platform : PlatformId.values()) {\n if (platform.equals(value)) {\n return platform;\n }\n }\n return Unknown;\n }\n }\n\n /**\n * Unicode encoding ids. These are used in a number of places within the font\n * whenever character encodings need to be specified.\n *\n * @see NameTable\n * @see CMapTable\n */\n public enum UnicodeEncodingId {\n // Unicode Platform Encodings\n Unknown(-1),\n Unicode1_0(0),\n Unicode1_1(1),\n ISO10646(2),\n Unicode2_0_BMP(3),\n Unicode2_0(4),\n UnicodeVariationSequences(5);\n\n private final int value;\n\n private UnicodeEncodingId(int value) {\n this.value = value;\n }\n\n public int value() {\n return this.value;\n }\n\n public boolean equals(int value) {\n return value == this.value;\n }\n\n public static UnicodeEncodingId valueOf(int value) {\n for (UnicodeEncodingId encoding : UnicodeEncodingId.values()) {\n if (encoding.equals(value)) {\n return encoding;\n }\n }\n return Unknown;\n }\n }\n\n /**\n * Windows encoding ids. These are used in a number of places within the font\n * whenever character encodings need to be specified.\n *\n * @see NameTable\n * @see CMapTable\n */\n public enum WindowsEncodingId {\n // Windows Platform Encodings\n Unknown(-1),\n Symbol(0),\n UnicodeUCS2(1),\n ShiftJIS(2),\n PRC(3),\n Big5(4),\n Wansung(5),\n Johab(6),\n UnicodeUCS4(10);\n\n private final int value;\n\n private WindowsEncodingId(int value) {\n this.value = value;\n }\n\n public int value() {\n return this.value;\n }\n\n public boolean equals(int value) {\n return value == this.value;\n }\n\n public static WindowsEncodingId valueOf(int value) {\n for (WindowsEncodingId encoding : WindowsEncodingId.values()) {\n if (encoding.equals(value)) {\n return encoding;\n }\n }\n return Unknown;\n }\n }\n\n /**\n * Macintosh encoding ids. These are used in a number of places within the\n * font whenever character encodings need to be specified.\n *\n * @see NameTable\n * @see CMapTable\n */\n public enum MacintoshEncodingId {\n // Macintosh Platform Encodings\n Unknown(-1),\n Roman(0),\n Japanese(1),\n ChineseTraditional(2),\n Korean(3),\n Arabic(4),\n Hebrew(5),\n Greek(6),\n Russian(7),\n RSymbol(8),\n Devanagari(9),\n Gurmukhi(10),\n Gujarati(11),\n Oriya(12),\n Bengali(13),\n Tamil(14),\n Telugu(15),\n Kannada(16),\n Malayalam(17),\n Sinhalese(18),\n Burmese(19),\n Khmer(20),\n Thai(21),\n Laotian(22),\n Georgian(23),\n Armenian(24),\n ChineseSimplified(25),\n Tibetan(26),\n Mongolian(27),\n Geez(28),\n Slavic(29),\n Vietnamese(30),\n Sindhi(31),\n Uninterpreted(32);\n\n private final int value;\n\n private MacintoshEncodingId(int value) {\n this.value = value;\n }\n\n public int value() {\n return this.value;\n }\n\n public boolean equals(int value) {\n return value == this.value;\n }\n\n public static MacintoshEncodingId valueOf(int value) {\n for (MacintoshEncodingId encoding : MacintoshEncodingId.values()) {\n if (encoding.equals(value)) {\n return encoding;\n }\n }\n return Unknown;\n }\n }\n\n public static final int SFNTVERSION_1 = Fixed1616.fixed(1, 0);\n\n private final int sfntVersion;\n private final byte[] digest;\n private long checksum;\n\n private Map<Integer, ? extends Table> tables; // these get set in the builder\n\n /**\n * Constructor.\n *\n * @param sfntVersion the sfnt version\n * @param digest the computed digest for the font; null if digest was not\n * computed\n */\n private Font(int sfntVersion, byte[] digest) {\n this.sfntVersion = sfntVersion;\n this.digest = digest;\n }\n\n /**\n * Gets the sfnt version set in the sfnt wrapper of the font.\n *\n * @return the sfnt version\n */\n public int sfntVersion() {\n return this.sfntVersion;\n }\n\n /**\n * Gets a copy of the fonts digest that was created when the font was read. If\n * no digest was set at creation time then the return result will be null.\n *\n * @return a copy of the digest array or <code>null</code> if one wasn't set\n * at creation time\n */\n public byte[] digest() {\n if (this.digest == null) {\n return null;\n }\n return Arrays.copyOf(this.digest, this.digest.length);\n }\n\n /**\n * Get the checksum for this font.\n *\n * @return the font checksum\n */\n public long checksum() {\n return this.checksum;\n }\n\n /**\n * Get the number of tables in this font.\n *\n * @return the number of tables\n */\n public int numTables() {\n return this.tables.size();\n }\n\n /**\n * Get an iterator over all the tables in the font.\n *\n * @return a table iterator\n */\n public Iterator<? extends Table> iterator() {\n return this.tables.values().iterator();\n }\n\n /**\n * Does the font have a particular table.\n *\n * @param tag the table identifier\n * @return true if the table is in the font; false otherwise\n */\n public boolean hasTable(int tag) {\n return this.tables.containsKey(tag);\n }\n\n /**\n * Get the table in this font with the specified id.\n *\n * @param <T> the type of the table\n * @param tag the identifier of the table\n * @return the table specified if it exists; null otherwise\n */\n @SuppressWarnings(\"unchecked\")\n public <T extends Table> T getTable(int tag) {\n return (T) this.tables.get(tag);\n }\n\n /**\n * Get a map of the tables in this font accessed by table tag.\n *\n * @return an unmodifiable view of the tables in this font\n */\n public Map<Integer, ? extends Table> tableMap() {\n return Collections.unmodifiableMap(this.tables);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"digest = \");\n byte[] digest = this.digest();\n if (digest != null) {\n for (int i = 0; i < digest.length; i++) {\n int d = 0xff & digest[i];\n if (d < 0x10) {\n sb.append(\"0\");\n }\n sb.append(Integer.toHexString(d));\n }\n }\n sb.append(\"\\n[\");\n sb.append(Fixed1616.toString(sfntVersion));\n sb.append(\", \");\n sb.append(this.numTables());\n sb.append(\"]\\n\");\n Iterator<? extends Table> iter = this.iterator();\n while (iter.hasNext()) {\n FontDataTable table = iter.next();\n sb.append(\"\\t\");\n sb.append(table);\n sb.append(\"\\n\");\n }\n return sb.toString();\n }\n\n /**\n * Serialize the font to the output stream.\n *\n * @param os the destination for the font serialization\n * @param tableOrdering the table ordering to apply\n * @throws IOException\n */\n void serialize(OutputStream os, List<Integer> tableOrdering) throws IOException {\n List<Integer> finalTableOrdering = this.generateTableOrdering(tableOrdering);\n List<Header> tableRecords = buildTableHeadersForSerialization(finalTableOrdering);\n FontOutputStream fos = new FontOutputStream(os);\n this.serializeHeader(fos, tableRecords);\n this.serializeTables(fos, tableRecords);\n }\n\n /**\n * Build the table headers to be used for serialization. These headers will be\n * filled out with the data required for serialization. The headers will be\n * sorted in the order specified and only those specified will have headers\n * generated.\n *\n * @param tableOrdering the tables to generate headers for and the order to\n * sort them\n * @return a list of table headers ready for serialization\n */\n private List<Header> buildTableHeadersForSerialization(List<Integer> tableOrdering) {\n List<Integer> finalTableOrdering = this.generateTableOrdering(tableOrdering);\n\n List<Header> tableHeaders = new ArrayList<Header>(this.numTables());\n int tableOffset =\n Offset.tableRecordBegin.offset + this.numTables() * Offset.tableRecordSize.offset;\n for (Integer tag : finalTableOrdering) {\n Table table = this.tables.get(tag);\n if (table != null) {\n tableHeaders.add(new Header(\n tag, table.calculatedChecksum(), tableOffset, table.header().length()));\n // write on boundary of 4 bytes\n tableOffset += (table.dataLength() + 3) & ~3;\n }\n }\n return tableHeaders;\n }\n\n /**\n * Searialize the headers.\n *\n * @param fos the destination stream for the headers\n * @param tableHeaders the headers to serialize\n * @throws IOException\n */\n private void serializeHeader(FontOutputStream fos, List<Header> tableHeaders)\n throws IOException {\n fos.writeFixed(this.sfntVersion);\n fos.writeUShort(tableHeaders.size());\n int log2OfMaxPowerOf2 = FontMath.log2(tableHeaders.size());\n int searchRange = 2 << (log2OfMaxPowerOf2 - 1 + 4);\n fos.writeUShort(searchRange);\n fos.writeUShort(log2OfMaxPowerOf2);\n fos.writeUShort((tableHeaders.size() * 16) - searchRange);\n\n List<Header> sortedHeaders = new ArrayList<Header>(tableHeaders);\n Collections.sort(sortedHeaders, Header.COMPARATOR_BY_TAG);\n\n for (Header record : sortedHeaders) {\n fos.writeULong(record.tag());\n fos.writeULong(record.checksum());\n fos.writeULong(record.offset());\n fos.writeULong(record.length());\n }\n }\n\n /**\n * Serialize the tables.\n *\n * @param fos the destination stream for the headers\n * @param tableHeaders the headers for the tables to serialize\n * @throws IOException\n */\n private void serializeTables(FontOutputStream fos, List<Header> tableHeaders)\n throws IOException {\n\n for (Header record : tableHeaders) {\n Table table = this.getTable(record.tag());\n if (table == null) {\n throw new IOException(\"Table out of sync with font header.\");\n }\n int tableSize = table.serialize(fos);\n int fillerSize = ((tableSize + 3) & ~3) - tableSize;\n for (int i = 0; i < fillerSize; i++) {\n fos.write(0);\n }\n }\n }\n\n /**\n * Generate the full table ordering to used for serialization. The full\n * ordering uses the partial ordering as a seed and then adds all remaining\n * tables in the font in an undefined order.\n *\n * @param defaultTableOrdering the partial ordering to be used as a seed for\n * the full ordering\n * @return the full ordering for serialization\n */\n private List<Integer> generateTableOrdering(List<Integer> defaultTableOrdering) {\n List<Integer> tableOrdering = new ArrayList<Integer>(this.tables.size());\n if (defaultTableOrdering == null) {\n defaultTableOrdering = defaultTableOrdering();\n }\n\n Set<Integer> tablesInFont = new TreeSet<Integer>(this.tables.keySet());\n\n // add all the default ordering\n for (Integer tag : defaultTableOrdering) {\n if (this.hasTable(tag)) {\n tableOrdering.add(tag);\n tablesInFont.remove(tag);\n }\n }\n\n // add all the rest\n for (Integer tag : tablesInFont) {\n tableOrdering.add(tag);\n }\n\n return tableOrdering;\n }\n\n /**\n * Get the default table ordering based on the type of the font.\n *\n * @return the default table ordering\n */\n private List<Integer> defaultTableOrdering() {\n if (this.hasTable(Tag.CFF)) {\n return Font.CFF_TABLE_ORDERING;\n }\n return Font.TRUE_TYPE_TABLE_ORDERING;\n }\n\n /**\n * A builder for a font object. The builder allows the for the creation of\n * immutable {@link Font} objects. The builder is a one use non-thread safe\n * object and cnce the {@link Font} object has been created it is no longer\n * usable. To create a further {@link Font} object new builder will be\n * required.\n *\n * @author Stuart Gill\n *\n */\n public static final class Builder {\n\n private Map<Integer, Table.Builder<? extends Table>> tableBuilders;\n private FontFactory factory;\n private int sfntVersion = SFNTVERSION_1;\n private int numTables;\n @SuppressWarnings(\"unused\")\n private int searchRange;\n @SuppressWarnings(\"unused\")\n private int entrySelector;\n @SuppressWarnings(\"unused\")\n private int rangeShift;\n private Map<Header, WritableFontData> dataBlocks;\n private byte[] digest;\n\n private Builder(FontFactory factory) {\n this.factory = factory;\n this.tableBuilders = new HashMap<Integer, Table.Builder<? extends Table>>();\n }\n\n private void loadFont(InputStream is) throws IOException {\n if (is == null) {\n throw new IOException(\"No input stream for font.\");\n }\n FontInputStream fontIS = null;\n try {\n fontIS = new FontInputStream(is);\n SortedSet<Header> records = readHeader(fontIS);\n this.dataBlocks = loadTableData(records, fontIS);\n this.tableBuilders = buildAllTableBuilders(this.dataBlocks);\n } finally {\n fontIS.close();\n }\n }\n\n private void loadFont(WritableFontData wfd, int offsetToOffsetTable) throws IOException {\n if (wfd == null) {\n throw new IOException(\"No data for font.\");\n }\n SortedSet<Header> records = readHeader(wfd, offsetToOffsetTable);\n this.dataBlocks = loadTableData(records, wfd);\n this.tableBuilders = buildAllTableBuilders(this.dataBlocks);\n }\n\n static final Builder\n getOTFBuilder(FontFactory factory, InputStream is) throws IOException {\n Builder builder = new Builder(factory);\n builder.loadFont(is);\n return builder;\n }\n\n static final Builder getOTFBuilder(\n FontFactory factory, WritableFontData wfd, int offsetToOffsetTable) throws IOException {\n Builder builder = new Builder(factory);\n builder.loadFont(wfd, offsetToOffsetTable);\n return builder;\n }\n\n static final Builder getOTFBuilder(FontFactory factory) {\n return new Builder(factory);\n }\n\n /**\n * Get the font factory that created this font builder.\n *\n * @return the font factory\n */\n public FontFactory getFontFactory() {\n return this.factory;\n }\n\n /**\n * Is the font ready to build?\n *\n * @return true if ready to build; false otherwise\n */\n public boolean readyToBuild() {\n // just read in data with no manipulation\n if (this.tableBuilders == null && this.dataBlocks != null && this.dataBlocks.size() > 0) {\n return true;\n }\n\n for (Table.Builder<? extends Table> tableBuilder : this.tableBuilders.values()) {\n if (tableBuilder.readyToBuild() == false) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Build the {@link Font}. After this call this builder will no longer be\n * usable.\n *\n * @return a {@link Font}\n */\n public Font build() {\n Map<Integer, ? extends Table> tables = null;\n\n Font font = new Font(this.sfntVersion, this.digest);\n\n if (this.tableBuilders.size() > 0) {\n tables = buildTablesFromBuilders(font, this.tableBuilders);\n }\n font.tables = tables;\n this.tableBuilders = null;\n this.dataBlocks = null;\n return font;\n }\n\n /**\n * Set a unique fingerprint for the font object.\n *\n * @param digest a unique identifier for the font\n */\n public void setDigest(byte[] digest) {\n this.digest = digest;\n }\n\n /**\n * Clear all table builders.\n */\n public void clearTableBuilders() {\n this.tableBuilders.clear();\n }\n\n /**\n * Does this font builder have the specified table builder.\n *\n * @param tag the table builder tag\n * @return true if there is a builder for that table; false otherwise\n */\n public boolean hasTableBuilder(int tag) {\n return this.tableBuilders.containsKey(tag);\n }\n\n /**\n * Get the table builder for the given tag. If there is no builder for that\n * tag then return a null.\n *\n * @param tag the table builder tag\n * @return the builder for the tag; null if there is no builder for that tag\n */\n public Table.Builder<? extends Table> getTableBuilder(int tag) {\n Table.Builder<? extends Table> builder = this.tableBuilders.get(tag);\n return builder;\n }\n\n /**\n * Creates a new empty table builder for the table type given by the table\n * id tag.\n *\n * This new table will be added to the font and will replace any existing\n * builder for that table.\n *\n * @param tag\n * @return new empty table of the type specified by tag; if tag is not known\n * then a generic OpenTypeTable is returned\n */\n public Table.Builder<? extends Table> newTableBuilder(int tag) {\n Header header = new Header(tag);\n Table.Builder<? extends Table> builder = Table.Builder.getBuilder(header, null);\n this.tableBuilders.put(header.tag(), builder);\n\n return builder;\n }\n\n /**\n * Creates a new table builder for the table type given by the table id tag.\n * It makes a copy of the data provided and uses that copy for the table.\n *\n * This new table has been added to the font and will replace any existing\n * builder for that table.\n *\n * @param tag\n * @param srcData\n * @return new empty table of the type specified by tag; if tag is not known\n * then a generic OpenTypeTable is returned\n */\n public Table.Builder<? extends Table> newTableBuilder(int tag, ReadableFontData srcData) {\n WritableFontData data;\n data = WritableFontData.createWritableFontData(srcData.length());\n // TODO(stuartg): take over original data instead?\n srcData.copyTo(data);\n\n Header header = new Header(tag, data.length());\n Table.Builder<? extends Table> builder = Table.Builder.getBuilder(header, data);\n\n this.tableBuilders.put(tag, builder);\n\n return builder;\n }\n\n /**\n * Get a map of the table builders in this font builder accessed by table\n * tag.\n *\n * @return an unmodifiable view of the table builders in this font builder\n */\n public Map<Integer, Table.Builder<? extends Table>> tableBuilderMap() {\n return Collections.unmodifiableMap(this.tableBuilders);\n }\n\n /**\n * Remove the specified table builder from the font builder.\n *\n * @param tag the table builder to remove\n * @return the table builder removed\n */\n public Table.Builder<? extends Table> removeTableBuilder(int tag) {\n return this.tableBuilders.remove(tag);\n }\n\n /**\n * Get the number of table builders in the font builder.\n *\n * @return the number of table builders\n */\n public int tableBuilderCount() {\n return this.tableBuilders.size();\n }\n\n @SuppressWarnings(\"unused\")\n private int sfntWrapperSize() {\n return Offset.sfntHeaderSize.offset +\n (Offset.tableRecordSize.offset * this.tableBuilders.size());\n }\n\n private Map<Integer, Table.Builder<? extends Table>> buildAllTableBuilders(\n Map<Header, WritableFontData> tableData) {\n Map<Integer, Table.Builder<? extends Table>> builderMap = \n new HashMap<Integer, Table.Builder<? extends Table>>();\n Set<Header> records = tableData.keySet();\n for (Header record : records) {\n Table.Builder<? extends Table> builder = getTableBuilder(record, tableData.get(record));\n builderMap.put(record.tag(), builder);\n }\n interRelateBuilders(builderMap);\n return builderMap;\n }\n\n private Table.Builder<? extends Table> getTableBuilder(Header header, WritableFontData data) {\n Table.Builder<? extends Table> builder = Table.Builder.getBuilder(header, data);\n return builder;\n }\n\n private static Map<Integer, Table> buildTablesFromBuilders(Font font,\n Map<Integer, Table.Builder<? extends Table>> builderMap) {\n Map<Integer, Table> tableMap = new TreeMap<Integer, Table>();\n\n interRelateBuilders(builderMap);\n\n long fontChecksum = 0;\n boolean tablesChanged = false;\n FontHeaderTable.Builder headerTableBuilder = null;\n \n // now build all the tables\n for (Table.Builder<? extends Table> builder : builderMap.values()) {\n Table table = null;\n if (Tag.isHeaderTable(builder.header().tag())) {\n headerTableBuilder = (FontHeaderTable.Builder) builder;\n continue;\n }\n if (builder.readyToBuild()) {\n tablesChanged |= builder.changed();\n table = builder.build();\n }\n if (table == null) {\n throw new RuntimeException(\"Unable to build table - \" + builder);\n }\n long tableChecksum = table.calculatedChecksum();\n fontChecksum += tableChecksum;\n tableMap.put(table.header().tag(), table);\n }\n \n // now fix up the header table\n Table headerTable = null;\n if (headerTableBuilder != null) {\n if (tablesChanged) {\n headerTableBuilder.setFontChecksum(fontChecksum);\n }\n if (headerTableBuilder.readyToBuild()) {\n tablesChanged |= headerTableBuilder.changed();\n headerTable = headerTableBuilder.build();\n }\n if (headerTable == null) {\n throw new RuntimeException(\"Unable to build table - \" + headerTableBuilder);\n }\n fontChecksum += headerTable.calculatedChecksum();\n tableMap.put(headerTable.header().tag(), headerTable);\n }\n \n font.checksum = fontChecksum & 0xffffffffL;\n return tableMap;\n }\n\n private static void\n interRelateBuilders(Map<Integer, Table.Builder<? extends Table>> builderMap) {\n FontHeaderTable.Builder headerTableBuilder =\n (FontHeaderTable.Builder) builderMap.get(Tag.head);\n HorizontalHeaderTable.Builder horizontalHeaderBuilder =\n (HorizontalHeaderTable.Builder) builderMap.get(Tag.hhea);\n MaximumProfileTable.Builder maxProfileBuilder =\n (MaximumProfileTable.Builder) builderMap.get(Tag.maxp);\n LocaTable.Builder locaTableBuilder =\n (LocaTable.Builder) builderMap.get(Tag.loca);\n HorizontalMetricsTable.Builder horizontalMetricsBuilder =\n (HorizontalMetricsTable.Builder) builderMap.get(Tag.hmtx);\n HorizontalDeviceMetricsTable.Builder hdmxTableBuilder =\n (HorizontalDeviceMetricsTable.Builder) builderMap.get(Tag.hdmx);\n\n // set the inter table data required to build certain tables\n if (horizontalMetricsBuilder != null) {\n if (maxProfileBuilder != null) {\n horizontalMetricsBuilder.setNumGlyphs(maxProfileBuilder.numGlyphs());\n }\n if (horizontalHeaderBuilder != null) {\n horizontalMetricsBuilder.setNumberOfHMetrics(\n horizontalHeaderBuilder.numberOfHMetrics());\n }\n }\n\n if (locaTableBuilder != null) {\n if (maxProfileBuilder != null) {\n locaTableBuilder.setNumGlyphs(maxProfileBuilder.numGlyphs());\n }\n if (headerTableBuilder != null) {\n locaTableBuilder.setFormatVersion(headerTableBuilder.indexToLocFormat());\n }\n }\n\n if (hdmxTableBuilder != null) {\n if (maxProfileBuilder != null) {\n hdmxTableBuilder.setNumGlyphs(maxProfileBuilder.numGlyphs());\n }\n } \n }\n\n private SortedSet<Header> readHeader(FontInputStream is) throws IOException {\n SortedSet<Header> records =\n new TreeSet<Header>(Header.COMPARATOR_BY_OFFSET);\n\n this.sfntVersion = is.readFixed();\n this.numTables = is.readUShort();\n this.searchRange = is.readUShort();\n this.entrySelector = is.readUShort();\n this.rangeShift = is.readUShort();\n\n for (int tableNumber = 0; tableNumber < this.numTables; tableNumber++) {\n Header table = new Header(is.readULongAsInt(), // safe since the tag is ASCII\n is.readULong(), // checksum\n is.readULongAsInt(), // offset\n is.readULongAsInt()); // length\n records.add(table);\n }\n return records;\n }\n\n private Map<Header, WritableFontData> loadTableData(\n SortedSet<Header> headers, FontInputStream is) throws IOException {\n Map<Header, WritableFontData> tableData =\n new HashMap<Header, WritableFontData>(headers.size());\n logger.fine(\"######## Reading Table Data\");\n for (Header tableHeader : headers) {\n is.skip(tableHeader.offset() - is.position());\n logger.finer(\"\\t\" + tableHeader);\n logger.finest(\"\\t\\tStream Position = \" + Integer.toHexString((int) is.position()));\n // don't close this or the whole stream is gone\n FontInputStream tableIS = new FontInputStream(is, tableHeader.length());\n // TODO(stuartg): start tracking bad tables and other errors\n WritableFontData data = WritableFontData.createWritableFontData(tableHeader.length());\n data.copyFrom(tableIS, tableHeader.length());\n tableData.put(tableHeader, data);\n }\n return tableData;\n }\n\n private SortedSet<Header> readHeader(ReadableFontData fd, int offset) {\n SortedSet<Header> records =\n new TreeSet<Header>(Header.COMPARATOR_BY_OFFSET);\n\n this.sfntVersion = fd.readFixed(offset + Offset.sfntVersion.offset);\n this.numTables = fd.readUShort(offset + Offset.numTables.offset);\n this.searchRange = fd.readUShort(offset + Offset.searchRange.offset);\n this.entrySelector = fd.readUShort(offset + Offset.entrySelector.offset);\n this.rangeShift = fd.readUShort(offset + Offset.rangeShift.offset);\n\n int tableOffset = offset + Offset.tableRecordBegin.offset;\n for (int tableNumber = 0;\n tableNumber < this.numTables;\n tableNumber++, tableOffset += Offset.tableRecordSize.offset) {\n Header table =\n // safe since the tag is ASCII\n new Header(fd.readULongAsInt(tableOffset + Offset.tableTag.offset),\n fd.readULong(tableOffset + Offset.tableCheckSum.offset), // checksum\n fd.readULongAsInt(tableOffset + Offset.tableOffset.offset), // offset\n fd.readULongAsInt(tableOffset + Offset.tableLength.offset)); // length\n records.add(table);\n }\n return records;\n }\n\n private Map<Header, WritableFontData> loadTableData(\n SortedSet<Header> headers, WritableFontData fd) {\n Map<Header, WritableFontData> tableData =\n new HashMap<Header, WritableFontData>(headers.size());\n logger.fine(\"######## Reading Table Data\");\n for (Header tableHeader : headers) {\n WritableFontData data = fd.slice(tableHeader.offset(), tableHeader.length());\n tableData.put(tableHeader, data);\n }\n return tableData;\n }\n }\n}", "public static final class Builder {\n\n private Map<Integer, Table.Builder<? extends Table>> tableBuilders;\n private FontFactory factory;\n private int sfntVersion = SFNTVERSION_1;\n private int numTables;\n @SuppressWarnings(\"unused\")\n private int searchRange;\n @SuppressWarnings(\"unused\")\n private int entrySelector;\n @SuppressWarnings(\"unused\")\n private int rangeShift;\n private Map<Header, WritableFontData> dataBlocks;\n private byte[] digest;\n\n private Builder(FontFactory factory) {\n this.factory = factory;\n this.tableBuilders = new HashMap<Integer, Table.Builder<? extends Table>>();\n }\n\n private void loadFont(InputStream is) throws IOException {\n if (is == null) {\n throw new IOException(\"No input stream for font.\");\n }\n FontInputStream fontIS = null;\n try {\n fontIS = new FontInputStream(is);\n SortedSet<Header> records = readHeader(fontIS);\n this.dataBlocks = loadTableData(records, fontIS);\n this.tableBuilders = buildAllTableBuilders(this.dataBlocks);\n } finally {\n fontIS.close();\n }\n }\n\n private void loadFont(WritableFontData wfd, int offsetToOffsetTable) throws IOException {\n if (wfd == null) {\n throw new IOException(\"No data for font.\");\n }\n SortedSet<Header> records = readHeader(wfd, offsetToOffsetTable);\n this.dataBlocks = loadTableData(records, wfd);\n this.tableBuilders = buildAllTableBuilders(this.dataBlocks);\n }\n\n static final Builder\n getOTFBuilder(FontFactory factory, InputStream is) throws IOException {\n Builder builder = new Builder(factory);\n builder.loadFont(is);\n return builder;\n }\n\n static final Builder getOTFBuilder(\n FontFactory factory, WritableFontData wfd, int offsetToOffsetTable) throws IOException {\n Builder builder = new Builder(factory);\n builder.loadFont(wfd, offsetToOffsetTable);\n return builder;\n }\n\n static final Builder getOTFBuilder(FontFactory factory) {\n return new Builder(factory);\n }\n\n /**\n * Get the font factory that created this font builder.\n *\n * @return the font factory\n */\n public FontFactory getFontFactory() {\n return this.factory;\n }\n\n /**\n * Is the font ready to build?\n *\n * @return true if ready to build; false otherwise\n */\n public boolean readyToBuild() {\n // just read in data with no manipulation\n if (this.tableBuilders == null && this.dataBlocks != null && this.dataBlocks.size() > 0) {\n return true;\n }\n\n for (Table.Builder<? extends Table> tableBuilder : this.tableBuilders.values()) {\n if (tableBuilder.readyToBuild() == false) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Build the {@link Font}. After this call this builder will no longer be\n * usable.\n *\n * @return a {@link Font}\n */\n public Font build() {\n Map<Integer, ? extends Table> tables = null;\n\n Font font = new Font(this.sfntVersion, this.digest);\n\n if (this.tableBuilders.size() > 0) {\n tables = buildTablesFromBuilders(font, this.tableBuilders);\n }\n font.tables = tables;\n this.tableBuilders = null;\n this.dataBlocks = null;\n return font;\n }\n\n /**\n * Set a unique fingerprint for the font object.\n *\n * @param digest a unique identifier for the font\n */\n public void setDigest(byte[] digest) {\n this.digest = digest;\n }\n\n /**\n * Clear all table builders.\n */\n public void clearTableBuilders() {\n this.tableBuilders.clear();\n }\n\n /**\n * Does this font builder have the specified table builder.\n *\n * @param tag the table builder tag\n * @return true if there is a builder for that table; false otherwise\n */\n public boolean hasTableBuilder(int tag) {\n return this.tableBuilders.containsKey(tag);\n }\n\n /**\n * Get the table builder for the given tag. If there is no builder for that\n * tag then return a null.\n *\n * @param tag the table builder tag\n * @return the builder for the tag; null if there is no builder for that tag\n */\n public Table.Builder<? extends Table> getTableBuilder(int tag) {\n Table.Builder<? extends Table> builder = this.tableBuilders.get(tag);\n return builder;\n }\n\n /**\n * Creates a new empty table builder for the table type given by the table\n * id tag.\n *\n * This new table will be added to the font and will replace any existing\n * builder for that table.\n *\n * @param tag\n * @return new empty table of the type specified by tag; if tag is not known\n * then a generic OpenTypeTable is returned\n */\n public Table.Builder<? extends Table> newTableBuilder(int tag) {\n Header header = new Header(tag);\n Table.Builder<? extends Table> builder = Table.Builder.getBuilder(header, null);\n this.tableBuilders.put(header.tag(), builder);\n\n return builder;\n }\n\n /**\n * Creates a new table builder for the table type given by the table id tag.\n * It makes a copy of the data provided and uses that copy for the table.\n *\n * This new table has been added to the font and will replace any existing\n * builder for that table.\n *\n * @param tag\n * @param srcData\n * @return new empty table of the type specified by tag; if tag is not known\n * then a generic OpenTypeTable is returned\n */\n public Table.Builder<? extends Table> newTableBuilder(int tag, ReadableFontData srcData) {\n WritableFontData data;\n data = WritableFontData.createWritableFontData(srcData.length());\n // TODO(stuartg): take over original data instead?\n srcData.copyTo(data);\n\n Header header = new Header(tag, data.length());\n Table.Builder<? extends Table> builder = Table.Builder.getBuilder(header, data);\n\n this.tableBuilders.put(tag, builder);\n\n return builder;\n }\n\n /**\n * Get a map of the table builders in this font builder accessed by table\n * tag.\n *\n * @return an unmodifiable view of the table builders in this font builder\n */\n public Map<Integer, Table.Builder<? extends Table>> tableBuilderMap() {\n return Collections.unmodifiableMap(this.tableBuilders);\n }\n\n /**\n * Remove the specified table builder from the font builder.\n *\n * @param tag the table builder to remove\n * @return the table builder removed\n */\n public Table.Builder<? extends Table> removeTableBuilder(int tag) {\n return this.tableBuilders.remove(tag);\n }\n\n /**\n * Get the number of table builders in the font builder.\n *\n * @return the number of table builders\n */\n public int tableBuilderCount() {\n return this.tableBuilders.size();\n }\n\n @SuppressWarnings(\"unused\")\n private int sfntWrapperSize() {\n return Offset.sfntHeaderSize.offset +\n (Offset.tableRecordSize.offset * this.tableBuilders.size());\n }\n\n private Map<Integer, Table.Builder<? extends Table>> buildAllTableBuilders(\n Map<Header, WritableFontData> tableData) {\n Map<Integer, Table.Builder<? extends Table>> builderMap = \n new HashMap<Integer, Table.Builder<? extends Table>>();\n Set<Header> records = tableData.keySet();\n for (Header record : records) {\n Table.Builder<? extends Table> builder = getTableBuilder(record, tableData.get(record));\n builderMap.put(record.tag(), builder);\n }\n interRelateBuilders(builderMap);\n return builderMap;\n }\n\n private Table.Builder<? extends Table> getTableBuilder(Header header, WritableFontData data) {\n Table.Builder<? extends Table> builder = Table.Builder.getBuilder(header, data);\n return builder;\n }\n\n private static Map<Integer, Table> buildTablesFromBuilders(Font font,\n Map<Integer, Table.Builder<? extends Table>> builderMap) {\n Map<Integer, Table> tableMap = new TreeMap<Integer, Table>();\n\n interRelateBuilders(builderMap);\n\n long fontChecksum = 0;\n boolean tablesChanged = false;\n FontHeaderTable.Builder headerTableBuilder = null;\n \n // now build all the tables\n for (Table.Builder<? extends Table> builder : builderMap.values()) {\n Table table = null;\n if (Tag.isHeaderTable(builder.header().tag())) {\n headerTableBuilder = (FontHeaderTable.Builder) builder;\n continue;\n }\n if (builder.readyToBuild()) {\n tablesChanged |= builder.changed();\n table = builder.build();\n }\n if (table == null) {\n throw new RuntimeException(\"Unable to build table - \" + builder);\n }\n long tableChecksum = table.calculatedChecksum();\n fontChecksum += tableChecksum;\n tableMap.put(table.header().tag(), table);\n }\n \n // now fix up the header table\n Table headerTable = null;\n if (headerTableBuilder != null) {\n if (tablesChanged) {\n headerTableBuilder.setFontChecksum(fontChecksum);\n }\n if (headerTableBuilder.readyToBuild()) {\n tablesChanged |= headerTableBuilder.changed();\n headerTable = headerTableBuilder.build();\n }\n if (headerTable == null) {\n throw new RuntimeException(\"Unable to build table - \" + headerTableBuilder);\n }\n fontChecksum += headerTable.calculatedChecksum();\n tableMap.put(headerTable.header().tag(), headerTable);\n }\n \n font.checksum = fontChecksum & 0xffffffffL;\n return tableMap;\n }\n\n private static void\n interRelateBuilders(Map<Integer, Table.Builder<? extends Table>> builderMap) {\n FontHeaderTable.Builder headerTableBuilder =\n (FontHeaderTable.Builder) builderMap.get(Tag.head);\n HorizontalHeaderTable.Builder horizontalHeaderBuilder =\n (HorizontalHeaderTable.Builder) builderMap.get(Tag.hhea);\n MaximumProfileTable.Builder maxProfileBuilder =\n (MaximumProfileTable.Builder) builderMap.get(Tag.maxp);\n LocaTable.Builder locaTableBuilder =\n (LocaTable.Builder) builderMap.get(Tag.loca);\n HorizontalMetricsTable.Builder horizontalMetricsBuilder =\n (HorizontalMetricsTable.Builder) builderMap.get(Tag.hmtx);\n HorizontalDeviceMetricsTable.Builder hdmxTableBuilder =\n (HorizontalDeviceMetricsTable.Builder) builderMap.get(Tag.hdmx);\n\n // set the inter table data required to build certain tables\n if (horizontalMetricsBuilder != null) {\n if (maxProfileBuilder != null) {\n horizontalMetricsBuilder.setNumGlyphs(maxProfileBuilder.numGlyphs());\n }\n if (horizontalHeaderBuilder != null) {\n horizontalMetricsBuilder.setNumberOfHMetrics(\n horizontalHeaderBuilder.numberOfHMetrics());\n }\n }\n\n if (locaTableBuilder != null) {\n if (maxProfileBuilder != null) {\n locaTableBuilder.setNumGlyphs(maxProfileBuilder.numGlyphs());\n }\n if (headerTableBuilder != null) {\n locaTableBuilder.setFormatVersion(headerTableBuilder.indexToLocFormat());\n }\n }\n\n if (hdmxTableBuilder != null) {\n if (maxProfileBuilder != null) {\n hdmxTableBuilder.setNumGlyphs(maxProfileBuilder.numGlyphs());\n }\n } \n }\n\n private SortedSet<Header> readHeader(FontInputStream is) throws IOException {\n SortedSet<Header> records =\n new TreeSet<Header>(Header.COMPARATOR_BY_OFFSET);\n\n this.sfntVersion = is.readFixed();\n this.numTables = is.readUShort();\n this.searchRange = is.readUShort();\n this.entrySelector = is.readUShort();\n this.rangeShift = is.readUShort();\n\n for (int tableNumber = 0; tableNumber < this.numTables; tableNumber++) {\n Header table = new Header(is.readULongAsInt(), // safe since the tag is ASCII\n is.readULong(), // checksum\n is.readULongAsInt(), // offset\n is.readULongAsInt()); // length\n records.add(table);\n }\n return records;\n }\n\n private Map<Header, WritableFontData> loadTableData(\n SortedSet<Header> headers, FontInputStream is) throws IOException {\n Map<Header, WritableFontData> tableData =\n new HashMap<Header, WritableFontData>(headers.size());\n logger.fine(\"######## Reading Table Data\");\n for (Header tableHeader : headers) {\n is.skip(tableHeader.offset() - is.position());\n logger.finer(\"\\t\" + tableHeader);\n logger.finest(\"\\t\\tStream Position = \" + Integer.toHexString((int) is.position()));\n // don't close this or the whole stream is gone\n FontInputStream tableIS = new FontInputStream(is, tableHeader.length());\n // TODO(stuartg): start tracking bad tables and other errors\n WritableFontData data = WritableFontData.createWritableFontData(tableHeader.length());\n data.copyFrom(tableIS, tableHeader.length());\n tableData.put(tableHeader, data);\n }\n return tableData;\n }\n\n private SortedSet<Header> readHeader(ReadableFontData fd, int offset) {\n SortedSet<Header> records =\n new TreeSet<Header>(Header.COMPARATOR_BY_OFFSET);\n\n this.sfntVersion = fd.readFixed(offset + Offset.sfntVersion.offset);\n this.numTables = fd.readUShort(offset + Offset.numTables.offset);\n this.searchRange = fd.readUShort(offset + Offset.searchRange.offset);\n this.entrySelector = fd.readUShort(offset + Offset.entrySelector.offset);\n this.rangeShift = fd.readUShort(offset + Offset.rangeShift.offset);\n\n int tableOffset = offset + Offset.tableRecordBegin.offset;\n for (int tableNumber = 0;\n tableNumber < this.numTables;\n tableNumber++, tableOffset += Offset.tableRecordSize.offset) {\n Header table =\n // safe since the tag is ASCII\n new Header(fd.readULongAsInt(tableOffset + Offset.tableTag.offset),\n fd.readULong(tableOffset + Offset.tableCheckSum.offset), // checksum\n fd.readULongAsInt(tableOffset + Offset.tableOffset.offset), // offset\n fd.readULongAsInt(tableOffset + Offset.tableLength.offset)); // length\n records.add(table);\n }\n return records;\n }\n\n private Map<Header, WritableFontData> loadTableData(\n SortedSet<Header> headers, WritableFontData fd) {\n Map<Header, WritableFontData> tableData =\n new HashMap<Header, WritableFontData>(headers.size());\n logger.fine(\"######## Reading Table Data\");\n for (Header tableHeader : headers) {\n WritableFontData data = fd.slice(tableHeader.offset(), tableHeader.length());\n tableData.put(tableHeader, data);\n }\n return tableData;\n }\n}", "public final class Tag {\n public static final int ttcf = Tag.intValue(new byte[]{'t', 't', 'c', 'f'});\n\n /***********************************************************************************\n *\n * Table Type Tags\n *\n ***********************************************************************************/\n\n // required tables\n public static final int cmap = Tag.intValue(new byte[]{'c', 'm', 'a', 'p'});\n public static final int head = Tag.intValue(new byte[]{'h', 'e', 'a', 'd'});\n public static final int hhea = Tag.intValue(new byte[]{'h', 'h', 'e', 'a'});\n public static final int hmtx = Tag.intValue(new byte[]{'h', 'm', 't', 'x'});\n public static final int maxp = Tag.intValue(new byte[]{'m', 'a', 'x', 'p'});\n public static final int name = Tag.intValue(new byte[]{'n', 'a', 'm', 'e'});\n public static final int OS_2 = Tag.intValue(new byte[]{'O', 'S', '/', '2'});\n public static final int post = Tag.intValue(new byte[]{'p', 'o', 's', 't'});\n\n // truetype outline tables\n public static final int cvt = Tag.intValue(new byte[]{'c', 'v', 't', ' '});\n public static final int fpgm = Tag.intValue(new byte[]{'f', 'p', 'g', 'm'});\n public static final int glyf = Tag.intValue(new byte[]{'g', 'l', 'y', 'f'});\n public static final int loca = Tag.intValue(new byte[]{'l', 'o', 'c', 'a'});\n public static final int prep = Tag.intValue(new byte[]{'p', 'r', 'e', 'p'});\n\n // postscript outline tables\n public static final int CFF = Tag.intValue(new byte[]{'C', 'F', 'F', ' '});\n public static final int VORG = Tag.intValue(new byte[]{'V', 'O', 'R', 'G'});\n\n // opentype bitmap glyph outlines\n public static final int EBDT = Tag.intValue(new byte[]{'E', 'B', 'D', 'T'});\n public static final int EBLC = Tag.intValue(new byte[]{'E', 'B', 'L', 'C'});\n public static final int EBSC = Tag.intValue(new byte[]{'E', 'B', 'S', 'C'});\n\n // advanced typographic features\n public static final int BASE = Tag.intValue(new byte[]{'B', 'A', 'S', 'E'});\n public static final int GDEF = Tag.intValue(new byte[]{'G', 'D', 'E', 'F'});\n public static final int GPOS = Tag.intValue(new byte[]{'G', 'P', 'O', 'S'});\n public static final int GSUB = Tag.intValue(new byte[]{'G', 'S', 'U', 'B'});\n public static final int JSTF = Tag.intValue(new byte[]{'J', 'S', 'T', 'F'});\n\n // other\n public static final int DSIG = Tag.intValue(new byte[]{'D', 'S', 'I', 'G'});\n public static final int gasp = Tag.intValue(new byte[]{'g', 'a', 's', 'p'});\n public static final int hdmx = Tag.intValue(new byte[]{'h', 'd', 'm', 'x'});\n public static final int kern = Tag.intValue(new byte[]{'k', 'e', 'r', 'n'});\n public static final int LTSH = Tag.intValue(new byte[]{'L', 'T', 'S', 'H'});\n public static final int PCLT = Tag.intValue(new byte[]{'P', 'C', 'L', 'T'});\n public static final int VDMX = Tag.intValue(new byte[]{'V', 'D', 'M', 'X'});\n public static final int vhea = Tag.intValue(new byte[]{'v', 'h', 'e', 'a'});\n public static final int vmtx = Tag.intValue(new byte[]{'v', 'm', 't', 'x'});\n\n // AAT Tables\n // TODO(stuartg): some tables may be missing from this list\n public static final int bsln = Tag.intValue(new byte[]{'b', 's', 'l', 'n'});\n public static final int feat = Tag.intValue(new byte[]{'f', 'e', 'a', 't'});\n public static final int lcar = Tag.intValue(new byte[]{'l', 'c', 'a', 'r'});\n public static final int morx = Tag.intValue(new byte[]{'m', 'o', 'r', 'x'});\n public static final int opbd = Tag.intValue(new byte[]{'o', 'p', 'b', 'd'});\n public static final int prop = Tag.intValue(new byte[]{'p', 'r', 'o', 'p'});\n\n // Graphite tables\n public static final int Feat = Tag.intValue(new byte[]{'F', 'e', 'a', 't'});\n public static final int Glat = Tag.intValue(new byte[]{'G', 'l', 'a', 't'});\n public static final int Gloc = Tag.intValue(new byte[]{'G', 'l', 'o', 'c'});\n public static final int Sile = Tag.intValue(new byte[]{'S', 'i', 'l', 'e'});\n public static final int Silf = Tag.intValue(new byte[]{'S', 'i', 'l', 'f'});\n\n // truetype bitmap font tables\n public static final int bhed = Tag.intValue(new byte[]{'b', 'h', 'e', 'd'});\n public static final int bdat = Tag.intValue(new byte[]{'b', 'd', 'a', 't'});\n public static final int bloc = Tag.intValue(new byte[]{'b', 'l', 'o', 'c'});\n\n private Tag() {\n // Prevent construction.\n }\n\n public static int intValue(byte[] tag) {\n return tag[0] << 24 | tag[1] << 16 | tag[2] << 8 | tag[3];\n }\n\n public static byte[] byteValue(int tag) {\n byte[] b = new byte[4];\n b[0] = (byte) (0xff & (tag >> 24));\n b[1] = (byte) (0xff & (tag >> 16));\n b[2] = (byte) (0xff & (tag >> 8));\n b[3] = (byte) (0xff & tag);\n return b;\n }\n\n public static String stringValue(int tag) {\n String s;\n try {\n s = new String(Tag.byteValue(tag), \"US-ASCII\");\n } catch (UnsupportedEncodingException e) {\n // should never happen since US-ASCII is a guaranteed character set but...\n return \"\";\n }\n return s;\n }\n\n public static int intValue(String s) {\n byte[] b = null;\n try {\n b = s.substring(0, 4).getBytes(\"US-ASCII\");\n } catch (UnsupportedEncodingException e) {\n // should never happen since US-ASCII is a guaranteed character set but...\n return 0;\n }\n return intValue(b);\n }\n\n /**\n * Determines whether the tag is that for the header table.\n * @param tag table tag\n * @return true if the tag represents the font header table\n */\n public static boolean isHeaderTable(int tag) {\n if (tag == Tag.head || tag == Tag.bhed) {\n return true;\n }\n return false;\n }\n}", "public abstract class CMap extends SubTable implements Iterable<Integer> {\r\n protected final int format;\r\n protected final CMapId cmapId;\r\n\r\n /**\r\n * CMap subtable formats.\r\n *\r\n */\r\n public enum CMapFormat {\r\n Format0(0),\r\n Format2(2),\r\n Format4(4),\r\n Format6(6),\r\n Format8(8),\r\n Format10(10),\r\n Format12(12),\r\n Format13(13),\r\n Format14(14);\r\n\r\n final int value;\r\n\r\n private CMapFormat(int value) {\r\n this.value = value;\r\n }\r\n\r\n public int value() {\r\n return this.value;\r\n }\r\n\r\n public boolean equals(int value) {\r\n return value == this.value;\r\n }\r\n\r\n public static CMapFormat valueOf(int value) {\r\n for (CMapFormat format : CMapFormat.values()) {\r\n if (format.equals(value)) {\r\n return format;\r\n }\r\n }\r\n return null;\r\n }\r\n }\r\n \r\n /**\r\n * Constructor.\r\n *\r\n * @param data data for the cmap\r\n * @param format the format of the cmap\r\n * @param cmapId the id information of the cmap\r\n */\r\n protected CMap(ReadableFontData data, int format, CMapId cmapId) {\r\n super(data);\r\n this.format = format;\r\n this.cmapId = cmapId;\r\n }\r\n\r\n /**\r\n * Gets the format of the cmap.\r\n *\r\n * @return the format\r\n */\r\n public int format() {\r\n return this.format;\r\n }\r\n\r\n /**\r\n * Gets the cmap id for this cmap.\r\n *\r\n * @return cmap id\r\n */\r\n public CMapId cmapId() {\r\n return this.cmapId;\r\n }\r\n\r\n /**\r\n * Gets the platform id for this cmap.\r\n *\r\n * @return the platform id\r\n * @see PlatformId\r\n */\r\n public int platformId() {\r\n return this.cmapId().platformId();\r\n }\r\n\r\n /**\r\n * Gets the encoding id for this cmap.\r\n *\r\n * @return the encoding id\r\n * @see MacintoshEncodingId\r\n * @see WindowsEncodingId\r\n * @see UnicodeEncodingId\r\n */\r\n public int encodingId() {\r\n return this.cmapId().encodingId();\r\n }\r\n\r\n // TODO(stuartg): simple implementation until all subclasses define their\r\n // own more efficient version\r\n protected class CharacterIterator implements Iterator<Integer> {\r\n private int character = 0;\r\n private final int maxCharacter;\r\n\r\n CharacterIterator(int start, int end) {\r\n this.character = start;\r\n this.maxCharacter = end;\r\n }\r\n\r\n @Override\r\n public boolean hasNext() {\r\n if (character < maxCharacter) {\r\n return true;\r\n }\r\n return false;\r\n }\r\n\r\n @Override\r\n public Integer next() {\r\n if (!hasNext()) {\r\n throw new NoSuchElementException(\"No more characters to iterate.\");\r\n }\r\n return this.character++;\r\n }\r\n\r\n @Override\r\n public void remove() {\r\n throw new UnsupportedOperationException(\"Unable to remove a character from cmap.\");\r\n }\r\n }\r\n\r\n\r\n @Override\r\n public int hashCode() {\r\n return this.cmapId.hashCode();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (this == obj) {\r\n return true;\r\n }\r\n if (!(obj instanceof CMap)) {\r\n return false;\r\n }\r\n return this.cmapId.equals(((CMap) obj).cmapId);\r\n }\r\n\r\n /**\r\n * Gets the language of the cmap.\r\n *\r\n * Note on the language field in 'cmap' subtables: The language field must\r\n * be set to zero for all cmap subtables whose platform IDs are other than\r\n * Macintosh (platform ID 1). For cmap subtables whose platform IDs are\r\n * Macintosh, set this field to the Macintosh language ID of the cmap\r\n * subtable plus one, or to zero if the cmap subtable is not\r\n * language-specific. For example, a Mac OS Turkish cmap subtable must set\r\n * this field to 18, since the Macintosh language ID for Turkish is 17. A\r\n * Mac OS Roman cmap subtable must set this field to 0, since Mac OS Roman\r\n * is not a language-specific encoding.\r\n *\r\n * @return the language id\r\n */\r\n public abstract int language();\r\n\r\n /**\r\n * Gets the glyph id for the character code provided.\r\n *\r\n * The character code provided must be in the encoding used by the cmap table.\r\n *\r\n * @param character character value using the encoding of the cmap table\r\n * @return glyph id for the character code\r\n */\r\n public abstract int glyphId(int character);\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder builder = new StringBuilder();\r\n builder.append(\"cmap: \");\r\n builder.append(this.cmapId());\r\n builder.append(\", \");\r\n builder.append(CMapFormat.valueOf(this.format()));\r\n builder.append(\", Data Size=0x\");\r\n builder.append(Integer.toHexString(this.data.length()));\r\n return builder.toString();\r\n }\r\n\r\n public abstract static class Builder<T extends CMap> extends SubTable.Builder<T> {\r\n\r\n private final CMapFormat format;\r\n private final CMapId cmapId;\r\n private int language;\r\n\r\n /**\r\n * Constructor.\r\n *\r\n * @param data the data for the cmap\r\n * @param format cmap format\r\n * @param cmapId the id for this cmap\r\n */\r\n protected Builder(ReadableFontData data, CMapFormat format, CMapId cmapId) {\r\n super(data);\r\n this.format = format;\r\n this.cmapId = cmapId;\r\n }\r\n\r\n /**\r\n * @return the id for this cmap\r\n */\r\n public CMapId cmapId() {\r\n return this.cmapId;\r\n }\r\n\r\n /**\r\n * Gets the encoding id for the cmap. The encoding will from one of a\r\n * number of different sets depending on the platform id.\r\n *\r\n * @return the encoding id\r\n * @see MacintoshEncodingId\r\n * @see WindowsEncodingId\r\n * @see UnicodeEncodingId\r\n */\r\n public int encodingId() {\r\n return this.cmapId().encodingId();\r\n }\r\n\r\n /**\r\n * Gets the platform id for the cmap.\r\n *\r\n * @return the platform id\r\n * @see PlatformId\r\n */\r\n public int platformId() {\r\n return this.cmapId().platformId();\r\n }\r\n\r\n public CMapFormat format() {\r\n return this.format;\r\n }\r\n\r\n public int language() {\r\n return this.language;\r\n }\r\n\r\n public void setLanguage(int language) {\r\n this.language = language;\r\n }\r\n\r\n /**\r\n * @param data\r\n */\r\n protected Builder(WritableFontData data, CMapFormat format, CMapId cmapId) {\r\n super(data);\r\n this.format = format;\r\n this.cmapId = cmapId;\r\n }\r\n\r\n @Override\r\n protected void subDataSet() {\r\n // NOP\r\n }\r\n\r\n @Override\r\n protected int subDataSizeToSerialize() {\r\n return this.internalReadData().length();\r\n }\r\n\r\n @Override\r\n protected boolean subReadyToSerialize() {\r\n return true;\r\n }\r\n\r\n @Override\r\n protected int subSerialize(WritableFontData newData) {\r\n return this.internalReadData().copyTo(newData);\r\n }\r\n\r\n static CMap.Builder<? extends CMap> getBuilder(ReadableFontData data, int offset, CMapId cmapId) {\r\n // read from the front of the cmap - 1st entry is always the format\r\n int rawFormat = data.readUShort(offset);\r\n CMapFormat format = CMapFormat.valueOf(rawFormat);\r\n\r\n switch(format) {\r\n case Format0:\r\n return new CMapFormat0.Builder(data, offset, cmapId);\r\n case Format2:\r\n return new CMapFormat2.Builder(data, offset, cmapId);\r\n case Format4:\r\n return new CMapFormat4.Builder(data, offset, cmapId);\r\n case Format6:\r\n return new CMapFormat6.Builder(data, offset, cmapId);\r\n case Format8:\r\n return new CMapFormat8.Builder(data, offset, cmapId);\r\n case Format10:\r\n return new CMapFormat10.Builder(data, offset, cmapId);\r\n case Format12:\r\n return new CMapFormat12.Builder(data, offset, cmapId);\r\n case Format13:\r\n return new CMapFormat13.Builder(data, offset, cmapId);\r\n case Format14:\r\n return new CMapFormat14.Builder(data, offset, cmapId);\r\n default:\r\n break;\r\n }\r\n return null;\r\n }\r\n\r\n // TODO: Instead of a root factory method, the individual subtable\r\n // builders should get created\r\n // from static factory methods in each subclass\r\n static CMap.Builder<? extends CMap> getBuilder(CMapFormat cmapFormat, CMapId cmapId) {\r\n switch(cmapFormat) {\r\n // TODO: builders for other formats, as they're implemented\r\n case Format0:\r\n return new CMapFormat0.Builder(null, 0, cmapId);\r\n case Format4:\r\n return new CMapFormat4.Builder(null, 0, cmapId);\r\n default:\r\n break;\r\n }\r\n return null;\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return String.format(\"%s, format = %s\", this.cmapId(), this.format());\r\n }\r\n }\r\n}", "public final class CMapTable extends SubTableContainerTable implements Iterable<CMap> {\n\n /**\n * The .notdef glyph.\n */\n public static final int NOTDEF = 0;\n\n /**\n * Offsets to specific elements in the underlying data. These offsets are relative to the\n * start of the table or the start of sub-blocks within the table.\n */\n enum Offset {\n version(0),\n numTables(2),\n encodingRecordStart(4),\n\n // offsets relative to the encoding record\n encodingRecordPlatformId(0),\n encodingRecordEncodingId(2),\n encodingRecordOffset(4),\n encodingRecordSize(8),\n\n format(0),\n\n // Format 0: Byte encoding table\n format0Format(0),\n format0Length(2),\n format0Language(4),\n format0GlyphIdArray(6),\n\n // Format 2: High-byte mapping through table\n format2Format(0),\n format2Length(2),\n format2Language(4),\n format2SubHeaderKeys(6),\n format2SubHeaders(518),\n // offset relative to the subHeader structure\n format2SubHeader_firstCode(0),\n format2SubHeader_entryCount(2),\n format2SubHeader_idDelta(4),\n format2SubHeader_idRangeOffset(6),\n format2SubHeader_structLength(8),\n\n // Format 4: Segment mapping to delta values\n format4Format(0),\n format4Length(2),\n format4Language(4),\n format4SegCountX2(6),\n format4SearchRange(8),\n format4EntrySelector(10),\n format4RangeShift(12),\n format4EndCount(14),\n format4FixedSize(16),\n\n // format 6: Trimmed table mapping\n format6Format(0),\n format6Length(2),\n format6Language(4),\n format6FirstCode(6),\n format6EntryCount(8),\n format6GlyphIdArray(10),\n\n // Format 8: mixed 16-bit and 32-bit coverage\n format8Format(0),\n format8Length(4),\n format8Language(8),\n format8Is32(12),\n format8nGroups(8204),\n format8Groups(8208),\n // ofset relative to the group structure\n format8Group_startCharCode(0),\n format8Group_endCharCode(4),\n format8Group_startGlyphId(8),\n format8Group_structLength(12),\n\n // Format 10: Trimmed array\n format10Format(0),\n format10Length(4),\n format10Language(8),\n format10StartCharCode(12),\n format10NumChars(16),\n format10Glyphs(20),\n\n // Format 12: Segmented coverage\n format12Format(0),\n format12Length(4),\n format12Language(8),\n format12nGroups(12),\n format12Groups(16),\n format12Groups_structLength(12),\n // offsets within the group structure\n format12_startCharCode(0),\n format12_endCharCode(4),\n format12_startGlyphId(8),\n\n // Format 13: Last Resort Font\n format13Format(0),\n format13Length(4),\n format13Language(8),\n format13nGroups(12),\n format13Groups(16),\n format13Groups_structLength(12),\n // offsets within the group structure\n format13_startCharCode(0),\n format13_endCharCode(4),\n format13_glyphId(8),\n\n // TODO: finish support for format 14\n // Format 14: Unicode Variation Sequences\n format14Format(0),\n format14Length(2);\n\n final int offset;\n\n private Offset(int offset) {\n this.offset = offset;\n }\n }\n\n public static final class CMapId implements Comparable<CMapId> {\n\n public static final CMapId WINDOWS_BMP =\n CMapId.getInstance(PlatformId.Windows.value(), WindowsEncodingId.UnicodeUCS2.value());\n public static final CMapId WINDOWS_UCS4 =\n CMapId.getInstance(PlatformId.Windows.value(), WindowsEncodingId.UnicodeUCS4.value());\n public static final CMapId MAC_ROMAN =\n CMapId.getInstance(PlatformId.Macintosh.value(), MacintoshEncodingId.Roman.value());\n\n public static CMapId getInstance(int platformId, int encodingId) {\n return new CMapId(platformId, encodingId);\n }\n\n private final int platformId;\n private final int encodingId;\n\n private CMapId(int platformId, int encodingId) {\n this.platformId = platformId;\n this.encodingId = encodingId;\n }\n\n public int platformId() {\n return this.platformId;\n }\n\n public int encodingId() {\n return this.encodingId;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj == this) {\n return true;\n }\n if (!(obj instanceof CMapId)) {\n return false;\n }\n CMapId otherKey = (CMapId) obj;\n if ((otherKey.platformId == this.platformId) && (otherKey.encodingId == this.encodingId)) {\n return true;\n }\n return false;\n }\n\n @Override\n public int hashCode() {\n return this.platformId << 8 | this.encodingId;\n }\n\n @Override\n public int compareTo(CMapId o) {\n return this.hashCode() - o.hashCode();\n }\n\n @Override\n public String toString() {\n StringBuilder b = new StringBuilder();\n b.append(\"pid = \");\n b.append(this.platformId);\n b.append(\", eid = \");\n b.append(this.encodingId);\n return b.toString();\n }\n }\n \n /**\n * Constructor.\n *\n * @param header header for the table\n * @param data data for the table\n */\n private CMapTable(Header header, ReadableFontData data) {\n super(header, data);\n }\n\n /**\n * Get the table version.\n *\n * @return table version\n */\n public int version() {\n return this.data.readUShort(Offset.version.offset);\n }\n\n /**\n * Gets the number of cmaps within the CMap table.\n *\n * @return the number of cmaps\n */\n public int numCMaps() {\n return this.data.readUShort(Offset.numTables.offset);\n }\n\n /**\n * Returns the index of the cmap with the given CMapId in the table or -1 if a cmap with the\n * CMapId does not exist in the table.\n *\n * @param id the id of the cmap to get the index for; this value cannot be null\n * @return the index of the cmap in the table or -1 if the cmap with the CMapId does not exist in\n * the table\n */\n // TODO Modify the iterator to be index-based and used here\n public int getCmapIndex(CMapId id) {\n for (int index = 0; index < numCMaps(); index++) {\n if (id.equals(cmapId(index))) {\n return index;\n }\n }\n\n return -1;\n }\n\n /**\n * Gets the offset in the table data for the encoding record for the cmap with\n * the given index. The offset is from the beginning of the table.\n *\n * @param index the index of the cmap\n * @return offset in the table data\n */\n private static int offsetForEncodingRecord(int index) {\n return Offset.encodingRecordStart.offset + index * Offset.encodingRecordSize.offset;\n }\n\n /**\n * Gets the cmap id for the cmap with the given index.\n *\n * @param index the index of the cmap\n * @return the cmap id\n */\n public CMapId cmapId(int index) {\n return CMapId.getInstance(platformId(index), encodingId(index));\n }\n\n /**\n * Gets the platform id for the cmap with the given index.\n *\n * @param index the index of the cmap\n * @return the platform id\n */\n public int platformId(int index) {\n return this.data.readUShort(\n Offset.encodingRecordPlatformId.offset + CMapTable.offsetForEncodingRecord(index));\n }\n\n /**\n * Gets the encoding id for the cmap with the given index.\n *\n * @param index the index of the cmap\n * @return the encoding id\n */\n public int encodingId(int index) {\n return this.data.readUShort(\n Offset.encodingRecordEncodingId.offset + CMapTable.offsetForEncodingRecord(index));\n }\n\n /**\n * Gets the offset in the table data for the cmap table with the given index.\n * The offset is from the beginning of the table.\n *\n * @param index the index of the cmap\n * @return the offset in the table data\n */\n public int offset(int index) {\n return this.data.readULongAsInt(\n Offset.encodingRecordOffset.offset + CMapTable.offsetForEncodingRecord(index));\n }\n\n /**\n * Gets an iterator over all of the cmaps within this CMapTable.\n */\n @Override\n public Iterator<CMap> iterator() {\n return new CMapIterator();\n }\n\n /**\n * Gets an iterator over the cmaps within this CMap table using the provided\n * filter to select the cmaps returned.\n *\n * @param filter the filter\n * @return iterator over cmaps\n */\n public Iterator<CMap> iterator(CMapFilter filter) {\n return new CMapIterator(filter);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(super.toString());\n sb.append(\" = { \");\n for (int i = 0; i < this.numCMaps(); i++) {\n CMap cmap;\n try {\n cmap = this.cmap(i);\n } catch (IOException e) {\n continue;\n }\n sb.append(\"[0x\");\n sb.append(Integer.toHexString(this.offset(i)));\n sb.append(\" = \");\n sb.append(cmap);\n if (i < this.numCMaps() - 1) {\n sb.append(\"], \");\n } else {\n sb.append(\"]\");\n }\n }\n sb.append(\" }\");\n return sb.toString();\n }\n\n /**\n * A filter on cmaps.\n */\n public interface CMapFilter {\n /**\n * Test on whether the cmap is acceptable or not.\n *\n * @param cmapId the id of the cmap\n * @return true if the cmap is acceptable; false otherwise\n */\n boolean accept(CMapId cmapId);\n }\n\n private class CMapIterator implements Iterator<CMap> {\n private int tableIndex = 0;\n private CMapFilter filter;\n\n private CMapIterator() {\n // no filter - iterate over all cmap subtables\n }\n\n private CMapIterator(CMapFilter filter) {\n this.filter = filter;\n }\n\n @Override\n public boolean hasNext() {\n if (this.filter == null) {\n if (this.tableIndex < numCMaps()) {\n return true;\n }\n return false;\n }\n for (; this.tableIndex < numCMaps(); this.tableIndex++) {\n if (filter.accept(cmapId(this.tableIndex))) {\n return true;\n }\n }\n return false;\n }\n\n @Override\n public CMap next() {\n if (!hasNext()) {\n throw new NoSuchElementException();\n }\n try {\n return cmap(this.tableIndex++);\n } catch (IOException e) {\n NoSuchElementException newException =\n new NoSuchElementException(\"Error during the creation of the CMap.\");\n newException.initCause(e);\n throw newException;\n }\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException(\"Cannot remove a CMap table from an existing font.\");\n }\n }\n\n /**\n * Gets the cmap for the given index.\n *\n * @param index the index of the cmap\n * @return the cmap at the index\n * @throws IOException\n */\n public CMap cmap(int index) throws IOException {\n CMap.Builder<? extends CMap> builder =\n CMapTable.Builder.cmapBuilder(this.readFontData(), index);\n return builder.build();\n }\n\n /**\n * Gets the cmap with the given ids if it exists.\n *\n * @param platformId the platform id\n * @param encodingId the encoding id\n * @return the cmap if it exists; null otherwise\n */\n public CMap cmap(int platformId, int encodingId) {\n return cmap(CMapId.getInstance(platformId, encodingId));\n }\n\n public CMap cmap(final CMapId cmapId) {\n Iterator<CMap> cmapIter = this.iterator(new CMapFilter() {\n @Override\n public boolean accept(CMapId foundCMapId) {\n if (cmapId.equals(foundCMapId)) {\n return true;\n }\n return false;\n }\n });\n // can only be one cmap for each set of ids\n if (cmapIter.hasNext()) {\n return cmapIter.next();\n }\n return null;\n }\n\n /**\n * CMap Table Builder.\n *\n */\n public static class Builder extends SubTableContainerTable.Builder<CMapTable> {\n\n private int version = 0; // TODO(stuartg): make a CMapTable constant\n private Map<CMapId, CMap.Builder<? extends CMap>> cmapBuilders;\n\n /**\n * Creates a new builder using the header information and data provided.\n *\n * @param header the header information\n * @param data the data holding the table\n * @return a new builder\n */\n public static Builder createBuilder(Header header, WritableFontData data) {\n return new Builder(header, data);\n }\n\n /**\n * Constructor.\n *\n * @param header the table header\n * @param data the writable data for the table\n */\n protected Builder(Header header, WritableFontData data) {\n super(header, data);\n }\n\n /**\n * Constructor. This constructor will try to maintain the data as readable\n * but if editing operations are attempted then a writable copy will be made\n * the readable data will be discarded.\n *\n * @param header the table header\n * @param data the readable data for the table\n */\n protected Builder(Header header, ReadableFontData data) {\n super(header, data);\n }\n\n /**\n * Static factory method to create a cmap subtable builder.\n *\n * @param data the data for the whole cmap table\n * @param index the index of the cmap subtable within the table\n * @return the cmap subtable requested if it exists; null otherwise\n */\n protected static CMap.Builder<? extends CMap> cmapBuilder(ReadableFontData data, int index) {\n if (index < 0 || index > numCMaps(data)) {\n throw new IndexOutOfBoundsException(\n \"CMap table is outside the bounds of the known tables.\");\n }\n\n // read from encoding records\n int platformId = data.readUShort(\n Offset.encodingRecordPlatformId.offset + CMapTable.offsetForEncodingRecord(index));\n int encodingId = data.readUShort(\n Offset.encodingRecordEncodingId.offset + CMapTable.offsetForEncodingRecord(index));\n int offset = data.readULongAsInt(\n Offset.encodingRecordOffset.offset + CMapTable.offsetForEncodingRecord(index));\n CMapId cmapId = CMapId.getInstance(platformId, encodingId);\n\n CMap.Builder<? extends CMap> builder = CMap.Builder.getBuilder(data, offset, cmapId);\n return builder;\n }\n\n @Override\n protected void subDataSet() {\n this.cmapBuilders = null;\n super.setModelChanged(false);\n }\n\n private void initialize(ReadableFontData data) {\n this.cmapBuilders = new /*TreeMap*/ HashMap<CMapId, CMap.Builder<? extends CMap>>();\n\n int numCMaps = numCMaps(data);\n for (int i = 0; i < numCMaps; i++) {\n CMap.Builder<? extends CMap> cmapBuilder = cmapBuilder(data, i);\n cmapBuilders.put(cmapBuilder.cmapId(), cmapBuilder);\n }\n }\n\n private Map<CMapId, CMap.Builder<? extends CMap>> getCMapBuilders() {\n if (this.cmapBuilders != null) {\n return this.cmapBuilders;\n }\n this.initialize(this.internalReadData());\n this.setModelChanged();\n\n return this.cmapBuilders;\n }\n\n private static int numCMaps(ReadableFontData data) {\n if (data == null) {\n return 0;\n }\n return data.readUShort(Offset.numTables.offset);\n }\n\n public int numCMaps() {\n return this.getCMapBuilders().size();\n }\n\n @Override\n protected int subDataSizeToSerialize() {\n if (this.cmapBuilders == null || this.cmapBuilders.size() == 0) {\n return 0;\n }\n\n boolean variable = false;\n int size = CMapTable.Offset.encodingRecordStart.offset + this.cmapBuilders.size()\n * CMapTable.Offset.encodingRecordSize.offset;\n\n // calculate size of each table\n for (CMap.Builder<? extends CMap> b : this.cmapBuilders.values()) {\n int cmapSize = b.subDataSizeToSerialize();\n size += Math.abs(cmapSize);\n variable |= cmapSize <= 0;\n }\n return variable ? -size : size;\n }\n\n @Override\n protected boolean subReadyToSerialize() {\n if (this.cmapBuilders == null) {\n return false;\n }\n // check each table\n for (CMap.Builder<? extends CMap> b : this.cmapBuilders.values()) {\n if (!b.subReadyToSerialize()) {\n return false;\n }\n }\n return true;\n }\n\n @Override\n protected int subSerialize(WritableFontData newData) {\n int size = newData.writeUShort(CMapTable.Offset.version.offset, this.version());\n size += newData.writeUShort(CMapTable.Offset.numTables.offset, this.cmapBuilders.size());\n\n int indexOffset = size;\n size += this.cmapBuilders.size() * CMapTable.Offset.encodingRecordSize.offset;\n for (CMap.Builder<? extends CMap> b : this.cmapBuilders.values()) {\n // header entry\n indexOffset += newData.writeUShort(indexOffset, b.platformId());\n indexOffset += newData.writeUShort(indexOffset, b.encodingId());\n indexOffset += newData.writeULong(indexOffset, size);\n\n // cmap\n size += b.subSerialize(newData.slice(size));\n }\n return size;\n }\n\n @Override\n protected CMapTable subBuildTable(ReadableFontData data) {\n return new CMapTable(this.header(), data);\n }\n\n // public building API\n\n public Iterator<? extends CMap.Builder<? extends CMap>> iterator() {\n return this.getCMapBuilders().values().iterator();\n }\n\n public int version() {\n return this.version;\n }\n\n public void setVersion(int version) {\n this.version = version;\n }\n\n /**\n * Gets a new cmap builder for this cmap table. The new cmap builder will be\n * for the cmap id specified and initialized with the data given. The data\n * will be copied and the original data will not be modified.\n *\n * @param cmapId the id for the new cmap builder\n * @param data the data to copy for the new cmap builder\n * @return a new cmap builder initialized with the cmap id and a copy of the\n * data\n * @throws IOException\n */\n public CMap.Builder<? extends CMap> newCMapBuilder(CMapId cmapId, ReadableFontData data)\n throws IOException {\n WritableFontData wfd = WritableFontData.createWritableFontData(data.size());\n data.copyTo(wfd);\n CMap.Builder<? extends CMap> builder = CMap.Builder.getBuilder(wfd, 0, cmapId);\n Map<CMapId, CMap.Builder<? extends CMap>> cmapBuilders = this.getCMapBuilders();\n cmapBuilders.put(cmapId, builder);\n return builder;\n }\n\n public CMap.Builder<? extends CMap> newCMapBuilder(CMapId cmapId, CMapFormat cmapFormat) {\n CMap.Builder<? extends CMap> builder = CMap.Builder.getBuilder(cmapFormat, cmapId);\n Map<CMapId, CMap.Builder<? extends CMap>> cmapBuilders = this.getCMapBuilders();\n cmapBuilders.put(cmapId, builder);\n return builder;\n }\n\n public CMap.Builder<? extends CMap> cmapBuilder(CMapId cmapId) {\n Map<CMapId, CMap.Builder<? extends CMap>> cmapBuilders = this.getCMapBuilders();\n return cmapBuilders.get(cmapId);\n }\n\n }\n}" ]
import com.google.typography.font.sfntly.Font; import com.google.typography.font.sfntly.Font.Builder; import com.google.typography.font.sfntly.Tag; import com.google.typography.font.sfntly.table.core.CMap; import com.google.typography.font.sfntly.table.core.CMapTable; import java.io.IOException;
/* * Copyright 2011 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.typography.font.tools.subsetter; /** * @author Stuart Gill * */ public class CMapTableSubsetter extends TableSubsetterImpl { /** * Constructor. */ public CMapTableSubsetter() { super(Tag.cmap); } @Override public boolean subset(Subsetter subsetter, Font font, Builder fontBuilder) throws IOException {
CMapTable cmapTable = font.getTable(Tag.cmap);
4
henryblue/TeaCup
app/src/main/java/com/app/teacup/MoviePlayActivity.java
[ "public class TvPlayRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {\n\n private final Context mContext;\n private final List<TvItemInfo> mDatas;\n private OnItemClickListener mListener;\n\n public interface OnItemClickListener {\n void onItemClick(View view, int position);\n }\n\n public TvPlayRecyclerAdapter(Context context, List<TvItemInfo> datas) {\n mContext = context;\n mDatas = datas;\n }\n\n @Override\n public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n TextView textView = new TextView(mContext);\n return new TvViewHolder(textView);\n }\n\n @Override\n public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {\n TvViewHolder viewHolder = (TvViewHolder) holder;\n viewHolder.mTextView.setTextColor(Color.BLACK);\n TvItemInfo info = mDatas.get(position);\n viewHolder.mTextView.setText(info.getName());\n int playIndex = 0;\n if (mContext instanceof MoviePlayActivity) {\n playIndex = ((MoviePlayActivity) mContext).mPlayIndex;\n }\n if (position == playIndex) {\n viewHolder.mTextView.setTextColor(ContextCompat.getColor(mContext, R.color.deepYellow));\n }\n }\n\n public void setOnItemClickListener(OnItemClickListener listener) {\n mListener = listener;\n }\n\n\n @Override\n public int getItemCount() {\n return mDatas.size();\n }\n\n private class TvViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {\n\n private final TextView mTextView;\n private final int margin = mContext.getResources()\n .getDimensionPixelOffset(R.dimen.tv_series_textView_item_margin);\n private final int width = mContext.getResources()\n .getDimensionPixelOffset(R.dimen.tv_series_textView_item_width);\n private final int maxWidth = mContext.getResources()\n .getDimensionPixelOffset(R.dimen.tv_series_textView_item_max_width);\n private final int height = mContext.getResources()\n .getDimensionPixelOffset(R.dimen.tv_series_textView_item_height);\n private final int textSize = mContext.getResources().getDimensionPixelSize(R.dimen.tv_series_textView_item_textSize);\n\n public TvViewHolder(View itemView) {\n super(itemView);\n mTextView = (TextView) itemView;\n itemView.setOnClickListener(this);\n RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(\n ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);\n params.setMargins(margin, margin, margin, margin);\n mTextView.setMinHeight(height);\n mTextView.setMinWidth(width);\n mTextView.setMaxWidth(maxWidth);\n mTextView.setLayoutParams(params);\n mTextView.setGravity(Gravity.CENTER);\n mTextView.setTextColor(Color.BLACK);\n mTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);\n mTextView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.alpha_white));\n }\n\n @Override\n public void onClick(View v) {\n if (mListener != null) {\n mListener.onItemClick(v, getLayoutPosition());\n }\n }\n }\n}", "public class MoviePlayInfo {\n private String imgUrl;\n private String movieName;\n private String addTime;\n private String nextUrl;\n\n public String getNextUrl() {\n return nextUrl;\n }\n\n public void setNextUrl(String nextUrl) {\n this.nextUrl = nextUrl;\n }\n\n public String getAddTime() {\n return addTime;\n }\n\n public void setAddTime(String addTime) {\n this.addTime = addTime;\n }\n\n public String getImgUrl() {\n return imgUrl;\n }\n\n public void setImgUrl(String imgUrl) {\n this.imgUrl = imgUrl;\n }\n\n public String getMovieName() {\n return movieName;\n }\n\n public void setMovieName(String movieName) {\n this.movieName = movieName;\n }\n}", "public class TvItemInfo {\n private String name;\n private String nextUrl;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getNextUrl() {\n return nextUrl;\n }\n\n public void setNextUrl(String nextUrl) {\n this.nextUrl = nextUrl;\n }\n}", "public class MoreTextView extends LinearLayout implements View.OnClickListener {\n\n private static final int DEFAULT_MAX_LINE_COUNT = 9;\n\n private static final int COLLAPSIBLE_STATE_SHRINKUP = 1;\n private static final int COLLAPSIBLE_STATE_SPREAD = 2;\n private static final int DEFAULT_TEXT_SIZE = 15;\n\n private TextView mTextContent;\n private TextView mTextDesc;\n private String mShrinkup;\n private String mSpread;\n private int mState;\n private int mMaxLines;\n private boolean mIsChanged;\n\n public MoreTextView(Context context) {\n this(context, null);\n }\n\n public MoreTextView(Context context, AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public MoreTextView(Context context, AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n\n init(context);\n setAttributeSet(context, attrs);\n }\n\n private void init(Context context) {\n View.inflate(context, R.layout.stretch_view_layout, this);\n mTextContent = (TextView) findViewById(R.id.svl_text_content);\n mTextDesc = (TextView) findViewById(R.id.svl_text_desc);\n mTextDesc.setOnClickListener(this);\n mShrinkup = context.getResources().getString(R.string.desc_shrinkup);\n mSpread = context.getResources().getString(R.string.desc_spread);\n mState = COLLAPSIBLE_STATE_SPREAD;\n mIsChanged = false;\n mMaxLines = DEFAULT_MAX_LINE_COUNT;\n }\n\n private void setAttributeSet(Context context, AttributeSet attrs) {\n if (attrs == null) {\n mTextContent.setMaxLines(mMaxLines);\n return;\n }\n TypedArray typeArray = context.obtainStyledAttributes(attrs,\n R.styleable.MoreTextView);\n final int texSize = typeArray.getDimensionPixelOffset(R.styleable.MoreTextView_textSize, DEFAULT_TEXT_SIZE);\n setTextSize(texSize);\n\n int color = typeArray.getColor(R.styleable.MoreTextView_textColor, Color.BLACK);\n mTextContent.setTextColor(color);\n\n int size = typeArray.getDimensionPixelOffset(R.styleable.MoreTextView_desc_textSize, DEFAULT_TEXT_SIZE);\n mTextDesc.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);\n\n color = typeArray.getColor(R.styleable.MoreTextView_desc_textColor, Color.BLACK);\n mTextDesc.setTextColor(color);\n mMaxLines = typeArray.getInt(R.styleable.MoreTextView_maxLines, DEFAULT_MAX_LINE_COUNT);\n mTextContent.setMaxLines(mMaxLines);\n typeArray.recycle();\n }\n\n public void setTextSize(int texSize) {\n mTextContent.setTextSize(TypedValue.COMPLEX_UNIT_PX, texSize);\n }\n\n @Override\n public void onClick(View v) {\n mIsChanged = false;\n String desc = mTextDesc.getText().toString();\n if (desc.equals(mShrinkup)) {\n mState = COLLAPSIBLE_STATE_SPREAD;\n } else {\n mState = COLLAPSIBLE_STATE_SHRINKUP;\n }\n requestLayout();\n }\n\n public final void setContent(CharSequence charSequence) {\n mTextContent.setText(charSequence, TextView.BufferType.NORMAL);\n mState = COLLAPSIBLE_STATE_SPREAD;\n mIsChanged = false;\n requestLayout();\n }\n\n @SuppressLint(\"DrawAllocation\")\n @Override\n protected void onLayout(boolean changed, int l, int t, int r, int b) {\n super.onLayout(changed, l, t, r, b);\n if (mTextContent.getLineCount() <= mMaxLines) {\n mTextContent.setMaxLines(mMaxLines);\n mTextDesc.setVisibility(View.GONE);\n } else {\n post(new InnerRunnable());\n }\n }\n\n private class InnerRunnable implements Runnable {\n @Override\n public void run() {\n if (!mIsChanged) {\n changedLayout();\n }\n }\n }\n private void changedLayout() {\n if (mState == COLLAPSIBLE_STATE_SPREAD) {\n mTextContent.setMaxLines(mMaxLines);\n mTextDesc.setVisibility(View.VISIBLE);\n mTextDesc.setText(mSpread);\n mIsChanged = true;\n } else if (mState == COLLAPSIBLE_STATE_SHRINKUP) {\n mIsChanged = true;\n mTextContent.setMaxLines(Integer.MAX_VALUE);\n mTextDesc.setVisibility(View.VISIBLE);\n mTextDesc.setText(mShrinkup);\n }\n }\n}", "public class OkHttpUtils {\n private static OkHttpUtils mOkHttpUtils;\n private final OkHttpClient mOkHttpClient;\n private final Handler mDelivery;\n private final Gson mGson;\n private String mUserAgent;\n\n private OkHttpUtils() {\n mOkHttpClient = new OkHttpClient();\n mDelivery = new Handler(Looper.getMainLooper());\n mGson = new Gson();\n }\n\n private static OkHttpUtils getInstance() {\n if (mOkHttpUtils == null) {\n synchronized (OkHttpUtils.class) {\n if (mOkHttpUtils == null) {\n mOkHttpUtils = new OkHttpUtils();\n }\n }\n }\n return mOkHttpUtils;\n }\n\n /**\n * 同步的Get请求\n *\n * @param url url\n * @return Response\n */\n private Response _getAsyn(String url) throws IOException {\n final Request request = new Request.Builder()\n .url(url)\n .build();\n Call call = mOkHttpClient.newCall(request);\n return call.execute();\n }\n\n /**\n * 同步的Get请求\n *\n * @param url url\n * @return 字符串\n */\n private String _getAsString(String url) throws IOException {\n Response execute = _getAsyn(url);\n return execute.body().string();\n }\n\n\n /**\n * 异步的get请求\n *\n * @param url url\n * @param callback callback\n */\n private void _getAsyn(Context context, String url, final ResultCallback callback) {\n if (TextUtils.isEmpty(mUserAgent)) {\n mUserAgent = getUserAgent(context);\n }\n final Request request = new Request.Builder()\n .url(url)\n .removeHeader(\"User-Agent\")\n .addHeader(\"User-Agent\", mUserAgent)\n .build();\n deliveryResult(callback, request);\n }\n\n private void _getAsyn(String url, final ResultCallback callback) {\n final Request request = new Request.Builder()\n .url(url)\n .build();\n deliveryResult(callback, request);\n }\n\n private void _getAsynHeader(String url, final ResultCallback callback) {\n final Request request = new Request.Builder()\n .removeHeader(\"User-Agent\")\n .addHeader(\"User-Agent\", \"Mozilla/5.0 (Linux; U; Android 7.0; zh-CN; SM-G9550 Build/NRD90M) \" +\n \"AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/40.0.2214.89 UCBrowser/11.7.0.953 \" +\n \"Mobile Safari/537.36\")\n .url(url)\n .build();\n deliveryResult(callback, request);\n }\n\n public static Response getAsyn(String url) throws IOException {\n return getInstance()._getAsyn(url);\n }\n\n public static String getAsString(String url) throws IOException {\n return getInstance()._getAsString(url);\n }\n\n public static void getAsyn(String url, ResultCallback callback) {\n getInstance()._getAsyn(url, callback);\n }\n\n public static void getAsynHeader(String url, ResultCallback callback) {\n getInstance()._getAsynHeader(url, callback);\n }\n\n public static void getAsynWithHeader(Context context, String url, ResultCallback callback) {\n getInstance()._getAsyn(context, url, callback);\n }\n\n private void deliveryResult(final ResultCallback callback, Request request) {\n mOkHttpClient.newCall(request).enqueue(new Callback() {\n @Override\n public void onFailure(final Request request, final IOException e) {\n sendFailedStringCallback(request, e, callback);\n }\n\n @Override\n public void onResponse(final Response response) {\n try {\n final String string = response.body().string();\n if (callback.mType == String.class) {\n sendSuccessResultCallback(string, callback);\n } else {\n Object o = mGson.fromJson(string, callback.mType);\n sendSuccessResultCallback(o, callback);\n }\n\n } catch (IOException e) {\n sendFailedStringCallback(response.request(), e, callback);\n }\n }\n });\n }\n\n private static String getUserAgent(Context context) {\n String userAgent;\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {\n try {\n userAgent = WebSettings.getDefaultUserAgent(context);\n } catch (Exception e) {\n userAgent = System.getProperty(\"http.agent\");\n }\n } else {\n userAgent = System.getProperty(\"http.agent\");\n }\n StringBuffer sb = new StringBuffer();\n for (int i = 0, length = userAgent.length(); i < length; i++) {\n char c = userAgent.charAt(i);\n if (c <= '\\u001f' || c >= '\\u007f') {\n sb.append(String.format(\"\\\\u%04x\", (int) c));\n } else {\n sb.append(c);\n }\n }\n return sb.toString();\n }\n\n private void sendFailedStringCallback(final Request request, final Exception e, final ResultCallback callback) {\n mDelivery.post(new Runnable() {\n @Override\n public void run() {\n if (callback != null)\n callback.onError(request, e);\n }\n });\n }\n\n private void sendSuccessResultCallback(final Object object, final ResultCallback callback) {\n mDelivery.post(new Runnable() {\n @Override\n public void run() {\n if (callback != null) {\n callback.onResponse(object);\n }\n }\n });\n }\n\n public static abstract class ResultCallback<T> {\n final Type mType;\n\n public ResultCallback() {\n mType = getSuperclassTypeParameter(getClass());\n }\n\n static Type getSuperclassTypeParameter(Class<?> subclass) {\n Type superclass = subclass.getGenericSuperclass();\n if (superclass instanceof Class) {\n throw new RuntimeException(\"Missing type parameter.\");\n }\n ParameterizedType parameterized = (ParameterizedType) superclass;\n return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);\n }\n\n public abstract void onError(Request request, Exception e);\n\n public abstract void onResponse(T response);\n }\n}", "public class ToolUtils {\n\n private static final int[] mStyles = {R.style.AppTheme, R.style.greenTheme, R.style.pinkTheme,\n R.style.blackTheme, R.style.grayTheme, R.style.tealTheme, R.style.redTheme, R.style.purpleTheme};\n\n public static int getScreenHeight(Context context) {\n DisplayMetrics metrics = context.getResources().getDisplayMetrics();\n return metrics.heightPixels;\n }\n\n public static int getWeatherImage(String weather) {\n switch (weather) {\n case \"多云\":\n case \"多云转阴\":\n case \"多云转晴\":\n return R.drawable.biz_plugin_weather_duoyun;\n case \"中雨\":\n case \"中到大雨\":\n return R.drawable.biz_plugin_weather_zhongyu;\n case \"雷阵雨\":\n return R.drawable.biz_plugin_weather_leizhenyu;\n case \"阵雨\":\n case \"阵雨转多云\":\n return R.drawable.biz_plugin_weather_zhenyu;\n case \"暴雪\":\n return R.drawable.biz_plugin_weather_baoxue;\n case \"暴雨\":\n return R.drawable.biz_plugin_weather_baoyu;\n case \"大暴雨\":\n return R.drawable.biz_plugin_weather_dabaoyu;\n case \"大雪\":\n return R.drawable.biz_plugin_weather_daxue;\n case \"大雨\":\n case \"大雨转中雨\":\n return R.drawable.biz_plugin_weather_dayu;\n case \"雷阵雨冰雹\":\n return R.drawable.biz_plugin_weather_leizhenyubingbao;\n case \"晴\":\n return R.drawable.biz_plugin_weather_qing;\n case \"沙尘暴\":\n return R.drawable.biz_plugin_weather_shachenbao;\n case \"特大暴雨\":\n return R.drawable.biz_plugin_weather_tedabaoyu;\n case \"雾\":\n case \"雾霾\":\n return R.drawable.biz_plugin_weather_wu;\n case \"小雪\":\n return R.drawable.biz_plugin_weather_xiaoxue;\n case \"小雨\":\n return R.drawable.biz_plugin_weather_xiaoyu;\n case \"阴\":\n return R.drawable.biz_plugin_weather_yin;\n case \"雨夹雪\":\n return R.drawable.biz_plugin_weather_yujiaxue;\n case \"阵雪\":\n return R.drawable.biz_plugin_weather_zhenxue;\n case \"中雪\":\n return R.drawable.biz_plugin_weather_zhongxue;\n default:\n return R.drawable.biz_plugin_weather_duoyun;\n }\n }\n\n public static String getTotalCacheSize(Context context) throws Exception {\n long cacheSize = getFolderSize(context.getCacheDir());\n if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {\n cacheSize += getFolderSize(context.getExternalCacheDir());\n }\n return Formatter.formatFileSize(context, cacheSize);\n }\n\n private static long getFolderSize(File file) {\n long size = 0;\n try {\n File[] fileList = file.listFiles();\n for (int i = 0; i < fileList.length; i++) {\n // 如果下面还有文件\n if (fileList[i].isDirectory()) {\n size = size + getFolderSize(fileList[i]);\n } else {\n size = size + fileList[i].length();\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n return size;\n }\n\n public static void clearAllCache(Context context) {\n deleteDir(context.getCacheDir());\n if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {\n deleteDir(context.getExternalCacheDir());\n }\n }\n\n private static boolean deleteDir(File dir) {\n if (dir != null && dir.isDirectory()) {\n String[] children = dir.list();\n for (int i = 0; i < children.length; i++) {\n boolean success = deleteDir(new File(dir, children[i]));\n if (!success) {\n return false;\n }\n }\n }\n return dir != null && dir.delete();\n }\n\n private static byte [] getHash(String password) {\n MessageDigest digest = null ;\n try {\n digest = MessageDigest. getInstance( \"SHA-256\");\n } catch (NoSuchAlgorithmException e1) {\n e1.printStackTrace();\n }\n if (digest != null) {\n digest.reset();\n return digest.digest(password.getBytes());\n } else {\n return null;\n }\n\n }\n\n //SHA-256加密算法\n public static String SHA256Encrypt(String strForEncrypt) {\n byte [] data = getHash(strForEncrypt);\n return String.format( \"%0\" + (data.length * 2) + \"X\", new BigInteger(1, data)).toLowerCase();\n }\n\n public static void copyFile(String oldPath, String newPath) {\n try {\n int byteRead;\n File oldFile = new File(oldPath);\n if (oldFile.exists()) {\n InputStream inStream = new FileInputStream(oldPath);\n FileOutputStream fs = new FileOutputStream(newPath);\n byte[] buffer = new byte[1444];\n while ( (byteRead = inStream.read(buffer)) != -1) {\n fs.write(buffer, 0, byteRead);\n }\n inStream.close();\n }\n }\n catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n public static void changeFilePermission(File file) {\n try {\n String command = \"chmod 666 \" + file.getAbsolutePath();\n Runtime.getRuntime().exec(command);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public static void changeToTheme(Activity activity, boolean isChange) {\n if (isChange) {\n Intent reIntent = new Intent();\n reIntent.putExtra(\"isChangeTheme\", isChange);\n activity.setResult(RESULT_OK, reIntent);\n }\n activity.finish();\n Intent intent = new Intent(activity, activity.getClass());\n activity.startActivity(intent);\n activity.overridePendingTransition(0, 0);\n }\n\n public static void onActivityCreateSetTheme(Context context) {\n SharedPreferences pf = context.getSharedPreferences(\"config\", Context.MODE_PRIVATE);\n int pos = pf.getInt(\"themePos\", 0);\n context.setTheme(mStyles[pos]);\n }\n\n public static int getThemeColorPrimary(Context context){\n TypedValue typedValue = new TypedValue();\n context.getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);\n return typedValue.data;\n }\n}", "public class urlUtils {\n public static final String DOUBAN_URL_ADDR = \"https://api.douban.com/v2/book/search?q=你好&amp;fields=all\";\n public static final String DOUBAN_URL_SEARCH = \"https://api.douban.com/v2/book/\";\n\n public static final String WEATHER_URL = \"http://wthrcdn.etouch.cn/weather_mini?city=\";\n\n public static final String MUSIC_URL = \"http://www.luoo.net/music/\";\n public static final String MUSIC_NEXT_URL = \"http://www.luoo.net/tag/?p=\";\n public static final String MUSIC_PLAYER_URL = \"http://mp3-cdn.luoo.net/low/luoo/radio\";\n\n public static final String DOUBAN_MEINV_URL = \"http://www.dbmeinv.com/dbgroup/show.htm?pager_offset=1\";\n public static final String DOUBAN_MEINV_NEXT_URL = \"http://www.dbmeinv.com/dbgroup/show.htm?pager_offset=\";\n\n public static final String GAOXIAO_URL = \"http://www.qiushibaike.com/pic/\";\n public static final String GAOXIAO_URL_NEXT = \"http://www.qiushibaike.com/pic/page/\";\n\n public static final String JIANDAN_URL = \"http://jandan.net/ooxx\";\n public static final String JIANDAN_NEXT_URL = \"http://jandan.net/ooxx/page-\";\n\n public static final String QIUBAI18_URL = \"http://m.qiubaichengren.net/gif/\";\n public static final String QIUBAI18_NEXT_URL = \"http://www.qiushibaike18.com/gif/page/\";\n\n public static final String MOVIE_URL = \"http://www.15yc.com\";\n public static final String MOVIE_SEARCH_URL = \"http://www.15yc.com/search?wd=\";\n\n public static final String NEWS_JIANDAN_URL = \"http://jandan.net\";\n public static final String NEWS_NEXT_URL = \"http://jandan.net/page/\";\n public static final String VIDEO_DIYIDAN_URL = \"http://www.diyidan.com/main/area/120001/1\";\n public static final String VIDEO_DIYIDAN_URL_NEXT = \"http://www.diyidan.com/main/area/120001/\";\n\n}" ]
import android.annotation.SuppressLint; import android.content.Intent; import android.content.pm.ActivityInfo; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.webkit.WebChromeClient; import android.webkit.WebResourceError; import android.webkit.WebResourceRequest; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.app.teacup.adapter.TvPlayRecyclerAdapter; import com.app.teacup.bean.movie.MoviePlayInfo; import com.app.teacup.bean.movie.TvItemInfo; import com.app.teacup.ui.MoreTextView; import com.app.teacup.util.OkHttpUtils; import com.app.teacup.util.ToolUtils; import com.app.teacup.util.urlUtils; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.squareup.okhttp.Request; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List;
TextView nameView = (TextView) itemView.findViewById(R.id.movie_play_name); TextView timeView = (TextView) itemView.findViewById(R.id.movie_play_addTime); MoviePlayInfo info = mMoreDatas.get(position); timeView.setText(info.getAddTime()); nameView.setText(info.getMovieName()); loadImageResource(info.getImgUrl(), imageView); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MoviePlayActivity.this, MoviePlayActivity.class); intent.putExtra("moviePlayUrl", mMoreDatas.get(position).getNextUrl()); intent.putExtra("moviePlayName", mMoreDatas.get(position).getMovieName()); startActivity(intent); } }); container.addView(itemView); } private void loadImageResource(String url, ImageView imageView) { if (!MainActivity.mIsLoadPhoto) { Glide.with(MoviePlayActivity.this).load(url).asBitmap() .error(R.drawable.photo_loaderror) .placeholder(R.drawable.main_load_bg) .diskCacheStrategy(DiskCacheStrategy.ALL) .dontAnimate() .into(imageView); } else { if (MainActivity.mIsWIFIState) { Glide.with(MoviePlayActivity.this).load(url).asBitmap() .error(R.drawable.photo_loaderror) .placeholder(R.drawable.main_load_bg) .diskCacheStrategy(DiskCacheStrategy.ALL) .dontAnimate() .into(imageView); } else { imageView.setImageResource(R.drawable.main_load_bg); } } } @Override protected void onLoadDataError() { Toast.makeText(MoviePlayActivity.this, getString(R.string.not_have_more_data), Toast.LENGTH_SHORT).show(); mRefreshLayout.setRefreshing(false); } @Override protected void onLoadDataFinish() { if (mTmpLayout.getVisibility() == View.VISIBLE) { mTmpLayout.setVisibility(View.GONE); } initData(); mRefreshLayout.setEnabled(false); } @Override protected void onRefreshError() { } @Override protected void onRefreshFinish() { } @Override protected void onRefreshStart() { } private void setupRefreshLayout() { mRefreshLayout.setColorSchemeColors(ToolUtils.getThemeColorPrimary(this)); mRefreshLayout.setSize(SwipeRefreshLayout.DEFAULT); mRefreshLayout.setProgressViewEndTarget(true, 100); StartRefreshPage(); } private void StartRefreshPage() { mRefreshLayout.post(new Runnable() { @Override public void run() { mRefreshLayout.setRefreshing(true); startRefreshData(); } }); } private void startRefreshData() { mMoreDatas.clear(); if (getIntent() == null) { return; } String videoUrl = getIntent().getStringExtra("moviePlayUrl"); if (!TextUtils.isEmpty(videoUrl)) { OkHttpUtils.getAsyn(videoUrl, new OkHttpUtils.ResultCallback<String>() { @Override public void onError(Request request, Exception e) { sendParseDataMessage(LOAD_DATA_ERROR); } @Override public void onResponse(String response) { parseMoreVideoData(response); } }); } } private void parseMoreVideoData(String response) { Document document = Jsoup.parse(response); try { if (document != null) { Element container = document.getElementsByClass("container").get(3); //parse tv data Element colMd = container.getElementsByClass("container-fluid").get(0) .getElementsByClass("col-md-12").get(0); Element group = colMd.getElementsByClass("dslist-group").get(0); Elements groupItems = group.getElementsByClass("dslist-group-item"); for (Element groupItem : groupItems) { TvItemInfo tvItemInfo = new TvItemInfo(); Element a = groupItem.getElementsByTag("a").get(0);
String nextUrl = urlUtils.MOVIE_URL + a.attr("href");
6
optimaize/command4j
src/test/java/com/optimaize/command4j/impl/DefaultCommandExecutorTest.java
[ "public interface CommandExecutor {\n\n /**\n * Executes it in the current thread, and blocks until it either finishes successfully or aborts by\n * throwing an exception.\n *\n * @param <A> argument\n * @param <R> Result\n */\n @NotNull\n <A, R> Optional<R> execute(@NotNull Command<A, R> cmd, @NotNull Mode mode, @Nullable A arg) throws Exception;\n\n /**\n * Creates a new command executor service based on your <code>executorService</code> and returns it.\n */\n @NotNull\n CommandExecutorService service(@NotNull final ExecutorService executorService);\n\n /**\n * @return The same default executor service on each call. It is a simple single-threaded service.\n * For anything beyond testing you should use {@link #service(java.util.concurrent.ExecutorService)}.\n */\n @NotNull\n CommandExecutorService service();\n\n}", "public class CommandExecutorBuilder {\n\n private static final Logger defaultLogger = LoggerFactory.getLogger(CommandExecutor.class); //yes, the class is CommandExecutor.class\n\n private Logger logger;\n private ExecutorCache cache;\n private List<ModeExtension> extensions;\n\n\n /**\n * If not set then <code>LoggerFactory.getLogger(CommandExecutor.class)</code> is used.\n */\n @NotNull\n public CommandExecutorBuilder logger(@NotNull Logger logger) {\n this.logger = logger;\n return this;\n }\n\n /**\n * If not set then <code>new ExecutorCache()</code> is used.\n */\n @NotNull\n public CommandExecutorBuilder cache(@NotNull ExecutorCache cache) {\n this.cache = cache;\n return this;\n }\n\n /**\n * Adds an extension to the executor. This is used for intercepting commands executed by the executor\n * built by this builder.\n *\n * <p>The extension is added in the order of the call; the first added extension will be the first executed,\n * and so on.</p>\n *\n * It is perfectly valid to add the same extension more than once. Such situations occur when there are\n * multiple extensions in use. Example cases:\n * <pre>\n * - logging\n * - once inside, right around the actual command execution,\n * - and once outside, before returning the result.\n * If there was an auto-retry extension in between then we can see in the logs later that\n * a command failed (the inner logger logged it), but in the end it succeeded (the outer\n * logger records the success).\n * - timeout (give up if it takes too long)\n * - once inside, right around the actual command execution,\n * - and once outside, before returning the result.\n * If there was an auto-retry extension in between then we can use a per-execution timeout,\n * and a total execution timeout. If this is a remove method invocation then we could\n * switch the destination server in between and try again, but still enforce a total maximal\n * permitted execution time.\n * </pre>\n *\n * <p>No method for removing extensions is provided. For two reasons.\n * <ol>\n * <li>First, because this is a builder and you're just about assembling it, so your code\n * logic should not need it. (If it was added, then adding extensions would also require the\n * feature to add in a specific position and not just append at the end. And that's all way\n * above the scope of this. We would then use a separate builder class just for making the\n * list of extensions.)</li>\n * <li>Second, it would be a difficult api. In case the same extension is added more than once,\n * then it must be possible to specify which to remove.</li>\n * </ol>\n * </p>\n *\n * <p>If never called then no extensions are used.</p>\n */\n @NotNull\n public CommandExecutorBuilder withExtension(@NotNull ModeExtension extension) {\n if (extensions==null) {\n extensions = new ArrayList<>();\n }\n extensions.add(extension);\n return this;\n }\n\n /**\n * Constructs the object with the added extensions. Uses defaults for the {@link #logger logger}\n * and {@link #cache cache}.\n */\n @NotNull\n public CommandExecutor build() {\n return new DefaultCommandExecutor(\n logger!=null ? logger : defaultLogger,\n cache!=null ? cache : new ExecutorCache(),\n extensions==null ? Collections.<ModeExtension>emptyList() : extensions\n );\n }\n\n}", "public interface CommandExecutorService {\n\n /**\n * Submits a command and returns instantly with a Future as the result.\n */\n @NotNull\n <A, V> ListenableFuture<Optional<V>> submit(@NotNull Command<A, V> cmd,\n @NotNull Mode mode,\n @Nullable A arg);\n\n /**\n * Executes a command and blocks until the command finishes successfully, aborts by throwing an exception,\n * the timeout occurs (which throws an exception too), or the command is cancelled before any of these occur.\n */\n @NotNull\n <A, V> Optional<V> submitAndWait(@NotNull Command<A, V> cmd,\n @NotNull Mode mode,\n @Nullable A arg,\n @NotNull Duration timeout) throws InterruptedException, TimeoutException, Exception;\n\n /**\n * Returns the service on which this command executor operates.\n * Things like shutdown() and awaitTermination() can be done on it.\n *\n * <p>This is beta api. It is not well defined yet whether access to it remains, or methods such as shutdown()\n * well be added to this interface. One argument is that the userland has access to this object anyway since\n * he's the one putting it in.</p>\n */\n @Beta\n ListeningExecutorService getUnderlyingExecutor();\n}", "@Immutable\npublic final class Mode {\n\n /**\n * Because it's immutable anyway it does not need to be created over and over again.\n */\n private static final Mode INITIAL_MODE = new Mode();\n\n /**\n * Does not contain null values.\n */\n @NotNull\n private final Map<Key<?>, Object> defs = Maps.newHashMap();\n\n private Mode() {\n }\n\n private Mode(@NotNull Map<Key<?>, Object> defs) {\n this.defs.putAll(defs);\n }\n\n @NotNull\n public static Mode create() {\n return INITIAL_MODE;\n }\n\n /**\n * @return The Optional's value is <code>absent</code> only if there was no such key because the mode\n * class does not allow <code>null</code> values.\n */\n @NotNull\n public <V> Optional<V> get(@NotNull Key<V> key) {\n //noinspection unchecked\n return (Optional<V>) Optional.fromNullable(defs.get(key));\n }\n\n /**\n * Returns {@code true} if the given key exists and does not map to a boolean value of {@code false}.\n *\n * <p>So any other object, such as a string for example (even if empty) or an Integer\n * (even with value 0) will return true.\n *\n * <p>Remember that this object contains no <code>null</code> values, see {@link #with}, thus\n * after \"adding\" <code>null</code> this <code>'is'</code> check returns false.</p>\n */\n public boolean is(@NotNull Key<?> key) {\n final Optional<?> v = get(key);\n return v.isPresent() && !v.get().equals(Boolean.FALSE);\n }\n\n /**\n * Creates and returns a new mode object of the current list of options together with\n * the given one.\n *\n * <p>If {@code value} is {@code null} the option key is removed (same as\n * calling {@link #without(Key)}.</p>\n *\n * <p>If there is a value for that <code>key</code> already then this overrides\n * the previously used value.</p>\n */\n @NotNull\n public <T> Mode with(@NotNull Key<T> key, @Nullable T value) {\n return new Mode(Map(this.defs, key, value));\n }\n\n /**\n * Short for {@link #with(Key, Object) with(Key, true)}\n */\n @NotNull\n public Mode with(@NotNull Key<Boolean> key) {\n return new Mode(Map(this.defs, key, true));\n }\n\n /**\n * Creates and returns a new mode object of the current list of options but without\n * the value for the given <code>key</code>.\n *\n * <p>It causes no exception in case it wasn't there.</p>\n */\n @NotNull\n public Mode without(@NotNull Key<?> key) {\n return new Mode(Map(this.defs, key, null));\n }\n\n\n @NotNull\n private static <T> Map<Key<?>, Object> Map(@NotNull Key<T> key, T value) {\n return Map(Maps.<Key<?>, Object>newHashMap(), key, value);\n }\n\n @NotNull\n private static <T> Map<Key<?>, Object> Map(@NotNull Map<Key<?>, Object> values, @NotNull Key<T> key1, @Nullable T value1) {\n Map<Key<?>, Object> defs = Maps.newHashMap();\n defs.putAll(values);\n if (value1 == null) {\n defs.remove(key1);\n } else {\n if (!key1.type().isAssignableFrom(value1.getClass())) {\n throw new IllegalArgumentException(\"Value '\" + value1 + \"' not appropriate for key '\" + key1 + \"'\");\n }\n defs.put(key1, value1);\n }\n return defs;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n Mode mode = (Mode) o;\n\n if (!defs.equals(mode.defs)) return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n return defs.hashCode();\n }\n\n @Override\n public String toString() {\n return \"Mode{\" + defs + '}';\n }\n}", "public abstract class BaseCommand<A, R> implements CombinableCommand<A,R> {\n\n @NotNull @Override\n public final <C> BaseCommand<A, C> andThen(@NotNull Command<R, C> cmd) {\n return new ComposedCommand<>(this, cmd);\n }\n\n @NotNull @Override\n public final BaseCommand<A, R> ifTrueOr(Predicate<R> cond, Command<A, R> alternative) {\n return Commands.firstIfTrue(this, cond, alternative);\n }\n\n @NotNull @Override\n public final BaseCommand<A, R> ifNotNullOr(Command<A, R> alternative) {\n return Commands.firstIfTrue(this, Predicates.<R>notNull(), alternative);\n }\n\n @NotNull @Override\n public final BaseListCommand<A, R> and(Command<A, R> cmd) {\n return Commands.and(this, cmd);\n }\n\n @NotNull @Override\n public final BaseListCommand<Iterable<A>, R> concat(Command<A, R> cmd) {\n return Commands.concat(this, cmd);\n }\n\n /**\n * @see Commands#withValue(Command, Key, Object)\n */\n public final <V> BaseCommand<A, R> withValue(@NotNull Key<V> key, V value) {\n return Commands.withValue(this, key, value);\n }\n\n @Override\n public String toString() {\n return getClass().getSimpleName();\n }\n\n @Override\n public String getName() {\n return getClass().getSimpleName();\n }\n}", "public class Sleep extends BaseCommand<Void, Void> {\n\n private final long sleepMs;\n public Sleep(long sleepMs) {\n this.sleepMs = sleepMs;\n }\n\n @Override\n public Void call(@NotNull Optional<Void> arg, @NotNull ExecutionContext ec) throws Exception {\n Thread.sleep(sleepMs);\n return null;\n }\n\n}" ]
import com.google.common.base.Stopwatch; import com.optimaize.command4j.CommandExecutor; import com.optimaize.command4j.CommandExecutorBuilder; import com.optimaize.command4j.CommandExecutorService; import com.optimaize.command4j.Mode; import com.optimaize.command4j.commands.BaseCommand; import com.optimaize.command4j.commands.Sleep; import org.testng.annotations.Test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static org.testng.Assert.assertTrue;
package com.optimaize.command4j.impl; /** * @author Fabian Kessler */ public class DefaultCommandExecutorTest { @Test public void runSingleThreaded() throws Exception { int commandSleepMillis = 100; int numExecutions = 10; int numThreads = 1; int allowedMargin = 100; run(commandSleepMillis, numExecutions, numThreads, allowedMargin); } @Test public void runMultiThreaded() throws Exception { int commandSleepMillis = 100; int numExecutions = 10; int numThreads = 2; int allowedMargin = 100; run(commandSleepMillis, numExecutions, numThreads, allowedMargin); } private void run(int commandSleepMillis, int numExecutions, int numThreads, int allowedMargin) throws InterruptedException { int delta = 2; //stopwatch timing can differ slightly... CommandExecutor commandExecutor = new CommandExecutorBuilder().build(); ExecutorService javaExecutor = Executors.newFixedThreadPool(numThreads); CommandExecutorService executorService = commandExecutor.service(javaExecutor); Mode mode = Mode.create();
BaseCommand<Void,Void> cmd = new Sleep(commandSleepMillis);
5
danimahardhika/wallpaperboard
library/src/main/java/com/dm/wallpaper/board/fragments/WallpaperSearchFragment.java
[ "public class WallpapersAdapter extends RecyclerView.Adapter<WallpapersAdapter.ViewHolder> {\r\n\r\n private final Context mContext;\r\n private final DisplayImageOptions.Builder mOptions;\r\n private List<Wallpaper> mWallpapers;\r\n private List<Wallpaper> mWallpapersAll;\r\n\r\n private final boolean mIsFavoriteMode;\r\n\r\n public WallpapersAdapter(@NonNull Context context, @NonNull List<Wallpaper> wallpapers,\r\n boolean isFavoriteMode, boolean isSearchMode) {\r\n mContext = context;\r\n mWallpapers = wallpapers;\r\n mIsFavoriteMode = isFavoriteMode;\r\n WallpaperBoardApplication.sIsClickable = true;\r\n\r\n if (isSearchMode) {\r\n mWallpapersAll = new ArrayList<>();\r\n mWallpapersAll.addAll(mWallpapers);\r\n }\r\n\r\n mOptions = ImageConfig.getRawDefaultImageOptions();\r\n mOptions.resetViewBeforeLoading(true);\r\n mOptions.cacheInMemory(true);\r\n mOptions.cacheOnDisk(true);\r\n mOptions.displayer(new FadeInBitmapDisplayer(700));\r\n }\r\n\r\n @Override\r\n public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\r\n View view = LayoutInflater.from(mContext).inflate(\r\n R.layout.fragment_wallpapers_item_grid, parent, false);\r\n return new ViewHolder(view);\r\n }\r\n\r\n @Override\r\n public void onBindViewHolder(ViewHolder holder, int position) {\r\n Wallpaper wallpaper = mWallpapers.get(position);\r\n holder.name.setText(wallpaper.getName());\r\n\r\n if (wallpaper.getAuthor() == null) {\r\n holder.author.setVisibility(View.GONE);\r\n } else {\r\n holder.author.setText(wallpaper.getAuthor());\r\n holder.author.setVisibility(View.VISIBLE);\r\n }\r\n\r\n int color = ColorHelper.getAttributeColor(mContext, android.R.attr.textColorPrimary);\r\n if (wallpaper.getColor() != 0) {\r\n color = ColorHelper.getTitleTextColor(wallpaper.getColor());\r\n }\r\n\r\n setFavorite(holder.favorite, color, position, false);\r\n\r\n ImageLoader.getInstance().displayImage(wallpaper.getThumbUrl(), new ImageViewAware(holder.image),\r\n mOptions.build(), ImageConfig.getThumbnailSize(), new SimpleImageLoadingListener() {\r\n @Override\r\n public void onLoadingStarted(String imageUri, View view) {\r\n super.onLoadingStarted(imageUri, view);\r\n int color;\r\n if (wallpaper.getColor() == 0) {\r\n color = ColorHelper.getAttributeColor(\r\n mContext, R.attr.card_background);\r\n } else {\r\n color = wallpaper.getColor();\r\n }\r\n\r\n int text = ColorHelper.getTitleTextColor(color);\r\n holder.name.setTextColor(text);\r\n holder.author.setTextColor(ColorHelper.setColorAlpha(text, 0.7f));\r\n holder.card.setCardBackgroundColor(color);\r\n }\r\n\r\n @Override\r\n public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {\r\n super.onLoadingComplete(imageUri, view, loadedImage);\r\n if (loadedImage != null && wallpaper.getColor() == 0) {\r\n Palette.from(loadedImage).generate(palette -> {\r\n if (mContext == null) return;\r\n if (((Activity) mContext).isFinishing()) return;\r\n \r\n int vibrant = ColorHelper.getAttributeColor(\r\n mContext, R.attr.card_background);\r\n int color = palette.getVibrantColor(vibrant);\r\n if (color == vibrant)\r\n color = palette.getMutedColor(vibrant);\r\n holder.card.setCardBackgroundColor(color);\r\n\r\n int text = ColorHelper.getTitleTextColor(color);\r\n holder.name.setTextColor(text);\r\n holder.author.setTextColor(ColorHelper.setColorAlpha(text, 0.7f));\r\n\r\n wallpaper.setColor(color);\r\n setFavorite(holder.favorite, text, holder.getAdapterPosition(), false);\r\n\r\n Database.get(mContext).updateWallpaper(wallpaper);\r\n });\r\n }\r\n }\r\n }, null);\r\n }\r\n\r\n @Override\r\n public int getItemCount() {\r\n return mWallpapers.size();\r\n }\r\n\r\n class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {\r\n\r\n @BindView(R2.id.card)\r\n CardView card;\r\n @BindView(R2.id.image)\r\n HeaderView image;\r\n @BindView(R2.id.name)\r\n TextView name;\r\n @BindView(R2.id.author)\r\n TextView author;\r\n @BindView(R2.id.favorite)\r\n ImageView favorite;\r\n\r\n ViewHolder(View itemView) {\r\n super(itemView);\r\n ButterKnife.bind(this, itemView);\r\n setCardViewToFlat(card);\r\n\r\n if (!Preferences.get(mContext).isShadowEnabled()) {\r\n card.setCardElevation(0f);\r\n }\r\n\r\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\r\n StateListAnimator stateListAnimator = AnimatorInflater\r\n .loadStateListAnimator(mContext, R.animator.card_lift_long);\r\n card.setStateListAnimator(stateListAnimator);\r\n }\r\n\r\n card.setOnClickListener(this);\r\n card.setOnLongClickListener(this);\r\n favorite.setOnClickListener(this);\r\n }\r\n\r\n @Override\r\n public void onClick(View view) {\r\n int id = view.getId();\r\n int position = getAdapterPosition();\r\n if (id == R.id.card) {\r\n if (WallpaperBoardApplication.sIsClickable) {\r\n WallpaperBoardApplication.sIsClickable = false;\r\n try {\r\n Bitmap bitmap = null;\r\n if (image.getDrawable() != null) {\r\n bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();\r\n }\r\n\r\n final Intent intent = new Intent(mContext, WallpaperBoardPreviewActivity.class);\r\n intent.putExtra(Extras.EXTRA_URL, mWallpapers.get(position).getUrl());\r\n intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);\r\n intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);\r\n\r\n ActivityTransitionLauncher.with((AppCompatActivity) mContext)\r\n .from(image, Extras.EXTRA_IMAGE)\r\n .image(bitmap)\r\n .launch(intent);\r\n } catch (Exception e) {\r\n WallpaperBoardApplication.sIsClickable = true;\r\n }\r\n }\r\n } else if (id == R.id.favorite) {\r\n if (position < 0 || position > mWallpapers.size()) return;\r\n\r\n boolean isFavorite = mWallpapers.get(position).isFavorite();\r\n Database.get(mContext).favoriteWallpaper(\r\n mWallpapers.get(position).getUrl(), !isFavorite);\r\n\r\n if (mIsFavoriteMode) {\r\n mWallpapers.remove(position);\r\n notifyItemRemoved(position);\r\n return;\r\n }\r\n\r\n mWallpapers.get(position).setFavorite(!isFavorite);\r\n setFavorite(favorite, name.getCurrentTextColor(), position, true);\r\n\r\n CafeBar.builder(mContext)\r\n .theme(Preferences.get(mContext).isDarkTheme() ? CafeBarTheme.LIGHT : CafeBarTheme.DARK)\r\n .fitSystemWindow()\r\n .floating(true)\r\n .typeface(TypefaceHelper.getRegular(mContext), TypefaceHelper.getBold(mContext))\r\n .content(String.format(\r\n mContext.getResources().getString(mWallpapers.get(position).isFavorite() ?\r\n R.string.wallpaper_favorite_added : R.string.wallpaper_favorite_removed),\r\n mWallpapers.get(position).getName()))\r\n .icon(mWallpapers.get(position).isFavorite() ?\r\n R.drawable.ic_toolbar_love : R.drawable.ic_toolbar_unlove)\r\n .show();\r\n }\r\n }\r\n\r\n @Override\r\n public boolean onLongClick(View view) {\r\n int id = view.getId();\r\n int position = getAdapterPosition();\r\n if (id == R.id.card) {\r\n if (position < 0 || position > mWallpapers.size()) {\r\n return false;\r\n }\r\n\r\n Popup popup = Popup.Builder(mContext)\r\n .to(favorite)\r\n .list(PopupItem.getApplyItems(mContext))\r\n .callback((applyPopup, i) -> {\r\n PopupItem item = applyPopup.getItems().get(i);\r\n if (item.getType() == PopupItem.Type.WALLPAPER_CROP) {\r\n Preferences.get(mContext).setCropWallpaper(!item.getCheckboxValue());\r\n item.setCheckboxValue(Preferences.get(mContext).isCropWallpaper());\r\n\r\n applyPopup.updateItem(i, item);\r\n return;\r\n } else if (item.getType() == PopupItem.Type.LOCKSCREEN) {\r\n WallpaperApplyTask.prepare(mContext)\r\n .wallpaper(mWallpapers.get(position))\r\n .to(WallpaperApplyTask.Apply.LOCKSCREEN)\r\n .start(AsyncTask.THREAD_POOL_EXECUTOR);\r\n } else if (item.getType() == PopupItem.Type.HOMESCREEN) {\r\n WallpaperApplyTask.prepare(mContext)\r\n .wallpaper(mWallpapers.get(position))\r\n .to(WallpaperApplyTask.Apply.HOMESCREEN)\r\n .start(AsyncTask.THREAD_POOL_EXECUTOR);\r\n\r\n } else if (item.getType() == PopupItem.Type.HOMESCREEN_LOCKSCREEN) {\r\n WallpaperApplyTask.prepare(mContext)\r\n .wallpaper(mWallpapers.get(position))\r\n .to(WallpaperApplyTask.Apply.HOMESCREEN_LOCKSCREEN)\r\n .start(AsyncTask.THREAD_POOL_EXECUTOR);\r\n\r\n } else if (item.getType() == PopupItem.Type.DOWNLOAD) {\r\n if (PermissionHelper.isStorageGranted(mContext)) {\r\n WallpaperDownloader.prepare(mContext)\r\n .wallpaper(mWallpapers.get(position))\r\n .start();\r\n } else {\r\n PermissionHelper.requestStorage(mContext);\r\n }\r\n }\r\n applyPopup.dismiss();\r\n })\r\n .build();\r\n\r\n popup.show();\r\n return true;\r\n }\r\n return false;\r\n }\r\n }\r\n\r\n private void setFavorite(@NonNull ImageView imageView, @ColorInt int color, int position, boolean animate) {\r\n if (position < 0 || position > mWallpapers.size()) return;\r\n\r\n if (mIsFavoriteMode) {\r\n imageView.setImageDrawable(DrawableHelper.getTintedDrawable(mContext, R.drawable.ic_toolbar_love, color));\r\n return;\r\n }\r\n\r\n boolean isFavorite = mWallpapers.get(position).isFavorite();\r\n\r\n if (animate) {\r\n AnimationHelper.show(imageView)\r\n .interpolator(new LinearOutSlowInInterpolator())\r\n .callback(new AnimationHelper.Callback() {\r\n @Override\r\n public void onAnimationStart() {\r\n imageView.setImageDrawable(DrawableHelper.getTintedDrawable(mContext,\r\n isFavorite ? R.drawable.ic_toolbar_love : R.drawable.ic_toolbar_unlove, color));\r\n }\r\n\r\n @Override\r\n public void onAnimationEnd() {\r\n\r\n }\r\n })\r\n .start();\r\n return;\r\n }\r\n\r\n imageView.setImageDrawable(DrawableHelper.getTintedDrawable(mContext,\r\n isFavorite ? R.drawable.ic_toolbar_love : R.drawable.ic_toolbar_unlove, color));\r\n }\r\n\r\n public void setWallpapers(@NonNull List<Wallpaper> wallpapers) {\r\n mWallpapers = wallpapers;\r\n notifyDataSetChanged();\r\n }\r\n\r\n public List<Wallpaper> getWallpapers() {\r\n return mWallpapers;\r\n }\r\n\r\n public void clearItems() {\r\n int size = mWallpapers.size();\r\n mWallpapers.clear();\r\n notifyItemRangeRemoved(0, size);\r\n }\r\n\r\n public void search(String string) {\r\n String query = string.toLowerCase(Locale.getDefault()).trim();\r\n mWallpapers.clear();\r\n if (query.length() == 0) mWallpapers.addAll(mWallpapersAll);\r\n else {\r\n for (int i = 0; i < mWallpapersAll.size(); i++) {\r\n Wallpaper wallpaper = mWallpapersAll.get(i);\r\n String name = wallpaper.getName().toLowerCase(Locale.getDefault());\r\n String author = wallpaper.getAuthor().toLowerCase(Locale.getDefault());\r\n if (name.contains(query) || author.contains(query)) {\r\n mWallpapers.add(wallpaper);\r\n }\r\n }\r\n }\r\n notifyDataSetChanged();\r\n }\r\n}\r", "public abstract class WallpaperBoardApplication extends Application implements ApplicationCallback {\r\n\r\n public static boolean sIsClickable = true;\r\n private static boolean mIsLatestWallpapersLoaded;\r\n private static WallpaperBoardConfiguration mConfiguration;\r\n\r\n private Thread.UncaughtExceptionHandler mHandler;\r\n\r\n @Override\r\n public void onCreate() {\r\n super.onCreate();\r\n Database.get(this).openDatabase();\r\n Preferences.get(this);\r\n\r\n if (!ImageLoader.getInstance().isInited())\r\n ImageLoader.getInstance().init(ImageConfig.getImageLoaderConfiguration(this));\r\n\r\n CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()\r\n .setDefaultFontPath(\"fonts/Font-Regular.ttf\")\r\n .setFontAttrId(R.attr.fontPath)\r\n .build());\r\n\r\n //Enable logging\r\n LogUtil.setLoggingTag(getString(R.string.app_name));\r\n LogUtil.setLoggingEnabled(true);\r\n\r\n mConfiguration = onInit();\r\n\r\n if (mConfiguration.isCrashReportEnabled()) {\r\n String[] urls = getResources().getStringArray(R.array.about_social_links);\r\n boolean isContainsValidEmail = false;\r\n for (String url : urls) {\r\n if (UrlHelper.getType(url) == UrlHelper.Type.EMAIL) {\r\n isContainsValidEmail = true;\r\n mConfiguration.setCrashReportEmail(url);\r\n break;\r\n }\r\n }\r\n\r\n if (isContainsValidEmail) {\r\n mHandler = Thread.getDefaultUncaughtExceptionHandler();\r\n Thread.setDefaultUncaughtExceptionHandler(this::handleUncaughtException);\r\n } else {\r\n mConfiguration.setCrashReportEnabled(false);\r\n mConfiguration.setCrashReportEmail(null);\r\n }\r\n }\r\n\r\n LocaleHelper.setLocale(this);\r\n }\r\n\r\n public static WallpaperBoardConfiguration getConfig() {\r\n if (mConfiguration == null) {\r\n mConfiguration = new WallpaperBoardConfiguration();\r\n }\r\n return mConfiguration;\r\n }\r\n\r\n public static boolean isLatestWallpapersLoaded() {\r\n return mIsLatestWallpapersLoaded;\r\n }\r\n\r\n public static void setLatestWallpapersLoaded(boolean loaded) {\r\n mIsLatestWallpapersLoaded = loaded;\r\n }\r\n\r\n private void handleUncaughtException(Thread thread, Throwable throwable) {\r\n try {\r\n StringBuilder sb = new StringBuilder();\r\n SimpleDateFormat dateFormat = TimeHelper.getDefaultShortDateTimeFormat();\r\n String dateTime = dateFormat.format(new Date());\r\n sb.append(\"Crash Time : \").append(dateTime).append(\"\\n\");\r\n sb.append(\"Class Name : \").append(throwable.getClass().getName()).append(\"\\n\");\r\n sb.append(\"Caused By : \").append(throwable.toString()).append(\"\\n\");\r\n\r\n for (StackTraceElement element : throwable.getStackTrace()) {\r\n sb.append(\"\\n\");\r\n sb.append(element.toString());\r\n }\r\n\r\n Intent intent = new Intent(this, WallpaperBoardCrashReport.class);\r\n intent.putExtra(WallpaperBoardCrashReport.EXTRA_STACKTRACE, sb.toString());\r\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\r\n intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);\r\n startActivity(intent);\r\n } catch (Exception e) {\r\n if (mHandler != null) {\r\n mHandler.uncaughtException(thread, throwable);\r\n return;\r\n }\r\n }\r\n System.exit(1);\r\n }\r\n}\r", "public class WallpaperBoardConfiguration {\r\n\r\n private @NavigationIcon int mNavigationIcon = NavigationIcon.DEFAULT;\r\n private @NavigationViewHeader int mNavigationViewHeader = NavigationViewHeader.NORMAL;\r\n private @GridStyle int mWallpapersGrid = GridStyle.CARD;\r\n\r\n private boolean mIsHighQualityPreviewEnabled = false;\r\n private boolean mIsCropWallpaperEnabledByDefault = false;\r\n private boolean mIsDashboardThemingEnabled = true;\r\n private boolean mIsShadowEnabled = true;\r\n private int mLatestWallpapersDisplayMax = 15;\r\n\r\n @ColorInt private int mAppLogoColor = -1;\r\n\r\n private boolean mIsCrashReportEnabled = true;\r\n private String mCrashReportEmail = null;\r\n\r\n private JsonStructure mJsonStructure = new JsonStructure.Builder().build();\r\n\r\n public WallpaperBoardConfiguration setNavigationIcon(@NavigationIcon int navigationIcon) {\r\n mNavigationIcon = navigationIcon;\r\n return this;\r\n }\r\n\r\n public WallpaperBoardConfiguration setAppLogoColor(@ColorInt int color) {\r\n mAppLogoColor = color;\r\n return this;\r\n }\r\n\r\n public WallpaperBoardConfiguration setNavigationViewHeaderStyle(@NavigationViewHeader int navigationViewHeader) {\r\n mNavigationViewHeader = navigationViewHeader;\r\n return this;\r\n }\r\n\r\n public WallpaperBoardConfiguration setWallpapersGridStyle(@GridStyle int gridStyle) {\r\n mWallpapersGrid = gridStyle;\r\n return this;\r\n }\r\n\r\n public WallpaperBoardConfiguration setDashboardThemingEnabled(boolean dashboardThemingEnabled) {\r\n mIsDashboardThemingEnabled = dashboardThemingEnabled;\r\n return this;\r\n }\r\n\r\n public WallpaperBoardConfiguration setShadowEnabled(boolean shadowEnabled) {\r\n mIsShadowEnabled = shadowEnabled;\r\n return this;\r\n }\r\n\r\n public WallpaperBoardConfiguration setLatestWallpapersDisplayMax(@IntRange(from = 5, to = 15) int count) {\r\n int finalCount = count;\r\n if (finalCount < 5) {\r\n finalCount = 5;\r\n } else if (finalCount > 15) {\r\n finalCount = 15;\r\n }\r\n mLatestWallpapersDisplayMax = finalCount;\r\n return this;\r\n }\r\n\r\n public WallpaperBoardConfiguration setHighQualityPreviewEnabled(boolean highQualityPreviewEnabled) {\r\n mIsHighQualityPreviewEnabled = highQualityPreviewEnabled;\r\n return this;\r\n }\r\n\r\n public WallpaperBoardConfiguration setCropWallpaperEnabledByDefault(boolean enabled) {\r\n mIsCropWallpaperEnabledByDefault = enabled;\r\n return this;\r\n }\r\n\r\n public WallpaperBoardConfiguration setCrashReportEnabled(boolean crashReportEnabled) {\r\n mIsCrashReportEnabled = crashReportEnabled;\r\n return this;\r\n }\r\n\r\n public WallpaperBoardConfiguration setCrashReportEmail(String email) {\r\n mCrashReportEmail = email;\r\n return this;\r\n }\r\n\r\n public WallpaperBoardConfiguration setJsonStructure(@NonNull JsonStructure jsonStructure) {\r\n mJsonStructure = jsonStructure;\r\n return this;\r\n }\r\n\r\n public @NavigationIcon int getNavigationIcon() {\r\n return mNavigationIcon;\r\n }\r\n\r\n public int getAppLogoColor() {\r\n return mAppLogoColor;\r\n }\r\n\r\n public @NavigationViewHeader int getNavigationViewHeader() {\r\n return mNavigationViewHeader;\r\n }\r\n\r\n public @GridStyle int getWallpapersGrid() {\r\n return mWallpapersGrid;\r\n }\r\n\r\n public boolean isDashboardThemingEnabled() {\r\n return mIsDashboardThemingEnabled;\r\n }\r\n\r\n public boolean isShadowEnabled() {\r\n return mIsShadowEnabled;\r\n }\r\n\r\n public int getLatestWallpapersDisplayMax() {\r\n return mLatestWallpapersDisplayMax;\r\n }\r\n\r\n public boolean isHighQualityPreviewEnabled() {\r\n return mIsHighQualityPreviewEnabled;\r\n }\r\n\r\n public boolean isCropWallpaperEnabledByDefault() {\r\n return mIsCropWallpaperEnabledByDefault;\r\n }\r\n\r\n public boolean isCrashReportEnabled() {\r\n return mIsCrashReportEnabled;\r\n }\r\n\r\n public String getCrashReportEmail() {\r\n return mCrashReportEmail;\r\n }\r\n\r\n public JsonStructure getJsonStructure() {\r\n return mJsonStructure;\r\n }\r\n\r\n @IntDef({NavigationIcon.DEFAULT,\r\n NavigationIcon.STYLE_1,\r\n NavigationIcon.STYLE_2,\r\n NavigationIcon.STYLE_3,\r\n NavigationIcon.STYLE_4})\r\n @Retention(RetentionPolicy.SOURCE)\r\n public @interface NavigationIcon {\r\n int DEFAULT = 0;\r\n int STYLE_1 = 1;\r\n int STYLE_2 = 2;\r\n int STYLE_3 = 3;\r\n int STYLE_4 = 4;\r\n }\r\n\r\n @IntDef({NavigationViewHeader.NORMAL, NavigationViewHeader.MINI, NavigationViewHeader.NONE})\r\n @Retention(RetentionPolicy.SOURCE)\r\n public @interface NavigationViewHeader {\r\n int NORMAL = 0;\r\n int MINI = 1;\r\n int NONE = 2;\r\n }\r\n\r\n @IntDef({GridStyle.CARD, GridStyle.FLAT})\r\n @Retention(RetentionPolicy.SOURCE)\r\n public @interface GridStyle {\r\n int CARD = 0;\r\n int FLAT = 1;\r\n }\r\n}\r", "public class Database extends SQLiteOpenHelper {\r\n\r\n private static final String DATABASE_NAME = \"wallpaper_board_database\";\r\n private static final int DATABASE_VERSION = 5;\r\n\r\n private static final String TABLE_WALLPAPERS = \"wallpapers\";\r\n private static final String TABLE_CATEGORIES = \"categories\";\r\n\r\n private static final String KEY_URL = \"url\";\r\n private static final String KEY_THUMB_URL = \"thumbUrl\";\r\n private static final String KEY_MIME_TYPE = \"mimeType\";\r\n private static final String KEY_SIZE = \"size\";\r\n private static final String KEY_COLOR = \"color\";\r\n private static final String KEY_WIDTH = \"width\";\r\n private static final String KEY_HEIGHT = \"height\";\r\n private static final String KEY_COUNT = \"count\";\r\n\r\n public static final String KEY_ID = \"id\";\r\n public static final String KEY_NAME = \"name\";\r\n public static final String KEY_AUTHOR = \"author\";\r\n public static final String KEY_CATEGORY = \"category\";\r\n\r\n private static final String KEY_FAVORITE = \"favorite\";\r\n private static final String KEY_SELECTED = \"selected\";\r\n private static final String KEY_MUZEI_SELECTED = \"muzeiSelected\";\r\n private static final String KEY_ADDED_ON = \"addedOn\";\r\n\r\n private final Context mContext;\r\n\r\n private static WeakReference<Database> mDatabase;\r\n private SQLiteDatabase mSQLiteDatabase;\r\n private static List<String> mFavoriteUrlsBackup;\r\n\r\n public static Database get(@NonNull Context context) {\r\n if (mDatabase == null || mDatabase.get() == null) {\r\n mDatabase = new WeakReference<>(new Database(context));\r\n }\r\n return mDatabase.get();\r\n }\r\n\r\n private Database(Context context) {\r\n super(context, DATABASE_NAME, null, DATABASE_VERSION);\r\n mContext = context;\r\n }\r\n\r\n @Override\r\n public void onCreate(SQLiteDatabase db) {\r\n String CREATE_TABLE_CATEGORY = \"CREATE TABLE \" +TABLE_CATEGORIES+ \"(\" +\r\n KEY_ID + \" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\" +\r\n KEY_NAME + \" TEXT NOT NULL,\" +\r\n KEY_SELECTED + \" INTEGER DEFAULT 1,\" +\r\n KEY_MUZEI_SELECTED + \" INTEGER DEFAULT 1, \" +\r\n \"UNIQUE (\" +KEY_NAME+ \"))\";\r\n String CREATE_TABLE_WALLPAPER = \"CREATE TABLE IF NOT EXISTS \" +TABLE_WALLPAPERS+ \"(\" +\r\n KEY_ID + \" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, \" +\r\n KEY_NAME+ \" TEXT NOT NULL, \" +\r\n KEY_AUTHOR + \" TEXT, \" +\r\n KEY_URL + \" TEXT NOT NULL, \" +\r\n KEY_THUMB_URL + \" TEXT NOT NULL, \" +\r\n KEY_MIME_TYPE + \" TEXT, \" +\r\n KEY_SIZE + \" INTEGER DEFAULT 0, \" +\r\n KEY_COLOR + \" INTEGER DEFAULT 0, \" +\r\n KEY_WIDTH + \" INTEGER DEFAULT 0, \" +\r\n KEY_HEIGHT + \" INTEGER DEFAULT 0, \" +\r\n KEY_CATEGORY + \" TEXT NOT NULL,\" +\r\n KEY_FAVORITE + \" INTEGER DEFAULT 0,\" +\r\n KEY_ADDED_ON + \" TEXT NOT NULL, \" +\r\n \"UNIQUE (\" +KEY_URL+ \"))\";\r\n db.execSQL(CREATE_TABLE_CATEGORY);\r\n db.execSQL(CREATE_TABLE_WALLPAPER);\r\n }\r\n\r\n @Override\r\n public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\r\n /*\r\n * Need to clear shared preferences with version 1.5.0b-3\r\n */\r\n if (newVersion == 5) {\r\n Preferences.get(mContext).clearPreferences();\r\n }\r\n resetDatabase(db);\r\n }\r\n\r\n @Override\r\n public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {\r\n resetDatabase(db);\r\n }\r\n\r\n private void resetDatabase(SQLiteDatabase db) {\r\n List<String> tables = new ArrayList<>();\r\n Cursor cursor = db.rawQuery(\"SELECT name FROM sqlite_master WHERE type=\\'table\\'\", null);\r\n if (cursor.moveToFirst()) {\r\n do {\r\n tables.add(cursor.getString(0));\r\n } while (cursor.moveToNext());\r\n }\r\n cursor.close();\r\n\r\n mFavoriteUrlsBackup = new ArrayList<>();\r\n cursor = db.query(TABLE_WALLPAPERS, new String[]{KEY_URL}, KEY_FAVORITE +\" = ?\",\r\n new String[]{\"1\"}, null, null, null);\r\n if (cursor.moveToFirst()) {\r\n do {\r\n mFavoriteUrlsBackup.add(cursor.getString(0));\r\n } while (cursor.moveToNext());\r\n }\r\n cursor.close();\r\n\r\n for (int i = 0; i < tables.size(); i++) {\r\n try {\r\n String dropQuery = \"DROP TABLE IF EXISTS \" + tables.get(i);\r\n if (!tables.get(i).equalsIgnoreCase(\"SQLITE_SEQUENCE\"))\r\n db.execSQL(dropQuery);\r\n } catch (Exception ignored) {}\r\n }\r\n onCreate(db);\r\n }\r\n\r\n public void restoreFavorites() {\r\n if (mFavoriteUrlsBackup == null) return;\r\n\r\n for (String url : mFavoriteUrlsBackup) {\r\n ContentValues values = new ContentValues();\r\n values.put(KEY_FAVORITE, 1);\r\n mDatabase.get().mSQLiteDatabase.update(TABLE_WALLPAPERS,\r\n values, KEY_URL +\" = ?\", new String[]{url});\r\n }\r\n\r\n mFavoriteUrlsBackup.clear();\r\n mFavoriteUrlsBackup = null;\r\n }\r\n\r\n public boolean openDatabase() {\r\n try {\r\n if (mDatabase == null || mDatabase.get() == null) {\r\n LogUtil.e(\"Database error: openDatabase() database instance is null\");\r\n return false;\r\n }\r\n\r\n if (mDatabase.get().mSQLiteDatabase == null) {\r\n mDatabase.get().mSQLiteDatabase = mDatabase.get().getWritableDatabase();\r\n }\r\n\r\n if (!mDatabase.get().mSQLiteDatabase.isOpen()) {\r\n LogUtil.e(\"Database error: database openable false, trying to open the database again\");\r\n mDatabase.get().mSQLiteDatabase = mDatabase.get().getWritableDatabase();\r\n }\r\n return mDatabase.get().mSQLiteDatabase.isOpen();\r\n } catch (SQLiteException | NullPointerException e) {\r\n LogUtil.e(Log.getStackTraceString(e));\r\n return false;\r\n }\r\n }\r\n\r\n public boolean closeDatabase() {\r\n try {\r\n if (mDatabase == null || mDatabase.get() == null) {\r\n LogUtil.e(\"Database error: closeDatabase() database instance is null\");\r\n return false;\r\n }\r\n\r\n if (mDatabase.get().mSQLiteDatabase == null) {\r\n LogUtil.e(\"Database error: trying to close database which is not opened\");\r\n return false;\r\n }\r\n mDatabase.get().mSQLiteDatabase.close();\r\n return true;\r\n } catch (SQLiteException | NullPointerException e) {\r\n LogUtil.e(Log.getStackTraceString(e));\r\n return false;\r\n }\r\n }\r\n\r\n public void add(@NonNull List<?> categoryLIst, @NonNull List<?> wallpaperList) {\r\n if (!openDatabase()) {\r\n LogUtil.e(\"Database error: add() failed to open database\");\r\n return;\r\n }\r\n\r\n Iterator categoryIterator = categoryLIst.iterator();\r\n Iterator wallpaperIterator = wallpaperList.iterator();\r\n int size = categoryLIst.size() > wallpaperList.size() ? categoryLIst.size() : wallpaperList.size();\r\n\r\n String categoryQuery = \"INSERT OR IGNORE INTO \" +TABLE_CATEGORIES+ \" (\" +KEY_NAME+ \") VALUES (?);\";\r\n String wallpaperQuery = \"INSERT OR IGNORE INTO \" +TABLE_WALLPAPERS+ \" (\" +KEY_NAME+ \",\" +KEY_AUTHOR+ \",\" +KEY_URL+ \",\"\r\n +KEY_THUMB_URL+ \",\" +KEY_CATEGORY+ \",\" +KEY_ADDED_ON+ \") VALUES (?,?,?,?,?,?);\";\r\n\r\n SQLiteStatement categoryStatements = mDatabase.get().mSQLiteDatabase.compileStatement(categoryQuery);\r\n SQLiteStatement wallpaperStatements = mDatabase.get().mSQLiteDatabase.compileStatement(wallpaperQuery);\r\n mDatabase.get().mSQLiteDatabase.beginTransaction();\r\n\r\n int i = 0;\r\n do {\r\n categoryStatements.clearBindings();\r\n wallpaperStatements.clearBindings();\r\n\r\n if (categoryIterator.hasNext()) {\r\n Category category;\r\n if (categoryIterator.next() instanceof Category) {\r\n category = (Category) categoryLIst.get(i);\r\n } else {\r\n category = JsonHelper.getCategory(categoryLIst.get(i));\r\n }\r\n\r\n if (category != null) {\r\n categoryStatements.bindString(1, category.getName());\r\n categoryStatements.execute();\r\n }\r\n }\r\n\r\n if (wallpaperIterator.hasNext()) {\r\n Wallpaper wallpaper;\r\n if (wallpaperIterator.next() instanceof Wallpaper) {\r\n wallpaper = (Wallpaper) wallpaperList.get(i);\r\n } else {\r\n wallpaper = JsonHelper.getWallpaper(wallpaperList.get(i));\r\n }\r\n\r\n if (wallpaper != null) {\r\n if (wallpaper.getUrl() != null) {\r\n String name = wallpaper.getName();\r\n if (name == null) name = \"\";\r\n\r\n wallpaperStatements.bindString(1, name);\r\n\r\n if (wallpaper.getAuthor() != null) {\r\n wallpaperStatements.bindString(2, wallpaper.getAuthor());\r\n } else {\r\n wallpaperStatements.bindNull(2);\r\n }\r\n\r\n wallpaperStatements.bindString(3, wallpaper.getUrl());\r\n wallpaperStatements.bindString(4, wallpaper.getThumbUrl());\r\n wallpaperStatements.bindString(5, wallpaper.getCategory());\r\n wallpaperStatements.bindString(6, TimeHelper.getLongDateTime());\r\n wallpaperStatements.execute();\r\n }\r\n }\r\n }\r\n i++;\r\n } while (i < size);\r\n\r\n mDatabase.get().mSQLiteDatabase.setTransactionSuccessful();\r\n mDatabase.get().mSQLiteDatabase.endTransaction();\r\n }\r\n\r\n public void addCategories(List<?> list) {\r\n if (!openDatabase()) {\r\n LogUtil.e(\"Database error: addCategories() failed to open database\");\r\n return;\r\n }\r\n\r\n String query = \"INSERT OR IGNORE INTO \" +TABLE_CATEGORIES+ \" (\" +KEY_NAME+ \") VALUES (?);\";\r\n SQLiteStatement statement = mDatabase.get().mSQLiteDatabase.compileStatement(query);\r\n mDatabase.get().mSQLiteDatabase.beginTransaction();\r\n\r\n for (int i = 0; i < list.size(); i++) {\r\n statement.clearBindings();\r\n\r\n Category category;\r\n if (list.get(i) instanceof Category) {\r\n category = (Category) list.get(i);\r\n } else {\r\n category = JsonHelper.getCategory(list.get(i));\r\n }\r\n\r\n if (category != null) {\r\n statement.bindString(1, category.getName());\r\n statement.execute();\r\n }\r\n }\r\n mDatabase.get().mSQLiteDatabase.setTransactionSuccessful();\r\n mDatabase.get().mSQLiteDatabase.endTransaction();\r\n }\r\n\r\n public void addWallpapers(@NonNull List<?> list) {\r\n if (!openDatabase()) {\r\n LogUtil.e(\"Database error: addWallpapers() failed to open database\");\r\n return;\r\n }\r\n\r\n String query = \"INSERT OR IGNORE INTO \" +TABLE_WALLPAPERS+ \" (\" +KEY_NAME+ \",\" +KEY_AUTHOR+ \",\" +KEY_URL+ \",\"\r\n +KEY_THUMB_URL+ \",\" +KEY_CATEGORY+ \",\" +KEY_ADDED_ON+ \") VALUES (?,?,?,?,?,?);\";\r\n SQLiteStatement statement = mDatabase.get().mSQLiteDatabase.compileStatement(query);\r\n mDatabase.get().mSQLiteDatabase.beginTransaction();\r\n\r\n for (int i = 0; i < list.size(); i++) {\r\n statement.clearBindings();\r\n\r\n Wallpaper wallpaper;\r\n if (list.get(i) instanceof Wallpaper) {\r\n wallpaper = (Wallpaper) list.get(i);\r\n } else {\r\n wallpaper = JsonHelper.getWallpaper(list.get(i));\r\n }\r\n\r\n if (wallpaper != null) {\r\n if (wallpaper.getUrl() != null) {\r\n String name = wallpaper.getName();\r\n if (name == null) name = \"\";\r\n\r\n statement.bindString(1, name);\r\n\r\n if (wallpaper.getAuthor() != null) {\r\n statement.bindString(2, wallpaper.getAuthor());\r\n } else {\r\n statement.bindNull(2);\r\n }\r\n\r\n statement.bindString(3, wallpaper.getUrl());\r\n statement.bindString(4, wallpaper.getThumbUrl());\r\n statement.bindString(5, wallpaper.getCategory());\r\n statement.bindString(6, TimeHelper.getLongDateTime());\r\n statement.execute();\r\n }\r\n }\r\n }\r\n mDatabase.get().mSQLiteDatabase.setTransactionSuccessful();\r\n mDatabase.get().mSQLiteDatabase.endTransaction();\r\n }\r\n\r\n public void updateWallpaper(Wallpaper wallpaper) {\r\n if (!openDatabase()) {\r\n LogUtil.e(\"Database error: updateWallpaper() failed to open database\");\r\n return;\r\n }\r\n\r\n if (wallpaper == null) return;\r\n\r\n ContentValues values = new ContentValues();\r\n if (wallpaper.getSize() > 0) {\r\n values.put(KEY_SIZE, wallpaper.getSize());\r\n }\r\n\r\n if (wallpaper.getMimeType() != null) {\r\n values.put(KEY_MIME_TYPE, wallpaper.getMimeType());\r\n }\r\n\r\n if (wallpaper.getDimensions() != null) {\r\n values.put(KEY_WIDTH, wallpaper.getDimensions().getWidth());\r\n values.put(KEY_HEIGHT, wallpaper.getDimensions().getHeight());\r\n }\r\n\r\n if (wallpaper.getColor() != 0) {\r\n values.put(KEY_COLOR, wallpaper.getColor());\r\n }\r\n\r\n if (values.size() > 0) {\r\n mDatabase.get().mSQLiteDatabase.update(TABLE_WALLPAPERS,\r\n values, KEY_URL +\" = ?\", new String[]{wallpaper.getUrl()});\r\n }\r\n }\r\n\r\n public void updateWallpapers(@NonNull List<Wallpaper> wallpapers) {\r\n if (!openDatabase()) {\r\n LogUtil.e(\"Database error: updateWallpapers() failed to open database\");\r\n return;\r\n }\r\n\r\n String query = \"UPDATE \" +TABLE_WALLPAPERS+ \" SET \" +KEY_FAVORITE+ \" = ?, \" +KEY_SIZE+ \" = ?, \"\r\n +KEY_MIME_TYPE+ \" = ?, \" +KEY_WIDTH+ \" = ?,\" +KEY_HEIGHT+ \" = ?, \" +KEY_COLOR+ \" = ? \"\r\n +\"WHERE \" +KEY_URL+ \" = ?\";\r\n SQLiteStatement statement = mDatabase.get().mSQLiteDatabase.compileStatement(query);\r\n mDatabase.get().mSQLiteDatabase.beginTransaction();\r\n\r\n for (Wallpaper wallpaper : wallpapers) {\r\n statement.clearBindings();\r\n\r\n statement.bindLong(1, wallpaper.isFavorite() ? 1 : 0);\r\n statement.bindLong(2, wallpaper.getSize());\r\n\r\n String mimeType = wallpaper.getMimeType();\r\n if (mimeType != null) {\r\n statement.bindString(3, mimeType);\r\n } else {\r\n statement.bindNull(3);\r\n }\r\n\r\n ImageSize dimension = wallpaper.getDimensions();\r\n int width = dimension == null ? 0 : dimension.getWidth();\r\n int height = dimension == null ? 0 : dimension.getHeight();\r\n statement.bindLong(4, width);\r\n statement.bindLong(5, height);\r\n\r\n statement.bindLong(6, wallpaper.getColor());\r\n statement.bindString(7, wallpaper.getUrl());\r\n statement.execute();\r\n }\r\n\r\n mDatabase.get().mSQLiteDatabase.setTransactionSuccessful();\r\n mDatabase.get().mSQLiteDatabase.endTransaction();\r\n }\r\n\r\n public void selectCategory(int id, boolean isSelected) {\r\n if (!openDatabase()) {\r\n LogUtil.e(\"Database error: selectCategory() failed to open database\");\r\n return;\r\n }\r\n\r\n ContentValues values = new ContentValues();\r\n values.put(KEY_SELECTED, isSelected ? 1 : 0);\r\n mDatabase.get().mSQLiteDatabase.update(TABLE_CATEGORIES, values, KEY_ID +\" = ?\", new String[]{String.valueOf(id)});\r\n }\r\n\r\n public void selectCategoryForMuzei(int id, boolean isSelected) {\r\n if (!openDatabase()) {\r\n LogUtil.e(\"Database error: selectCategoryForMuzei() failed to open database\");\r\n return;\r\n }\r\n\r\n ContentValues values = new ContentValues();\r\n values.put(KEY_MUZEI_SELECTED, isSelected ? 1 : 0);\r\n mDatabase.get().mSQLiteDatabase.update(TABLE_CATEGORIES, values, KEY_ID +\" = ?\", new String[]{String.valueOf(id)});\r\n }\r\n\r\n public void favoriteWallpaper(String url, boolean isFavorite) {\r\n if (!openDatabase()) {\r\n LogUtil.e(\"Database error: favoriteWallpaper() failed to open database\");\r\n return;\r\n }\r\n\r\n ContentValues values = new ContentValues();\r\n values.put(KEY_FAVORITE, isFavorite ? 1 : 0);\r\n mDatabase.get().mSQLiteDatabase.update(TABLE_WALLPAPERS, values,\r\n KEY_URL +\" = ?\", new String[]{url});\r\n }\r\n\r\n private List<String> getSelectedCategories(boolean isMuzei) {\r\n if (!openDatabase()) {\r\n LogUtil.e(\"Database error: getSelectedCategories() failed to open database\");\r\n return new ArrayList<>();\r\n }\r\n\r\n List<String> categories = new ArrayList<>();\r\n String column = isMuzei ? KEY_MUZEI_SELECTED : KEY_SELECTED;\r\n Cursor cursor = mDatabase.get().mSQLiteDatabase.query(TABLE_CATEGORIES, new String[]{KEY_NAME}, column +\" = ?\",\r\n new String[]{\"1\"}, null, null, KEY_NAME);\r\n if (cursor.moveToFirst()) {\r\n do {\r\n categories.add(cursor.getString(0));\r\n } while (cursor.moveToNext());\r\n }\r\n cursor.close();\r\n return categories;\r\n }\r\n\r\n public List<Category> getCategories() {\r\n if (!openDatabase()) {\r\n LogUtil.e(\"Database error: getCategories() failed to open database\");\r\n return new ArrayList<>();\r\n }\r\n\r\n List<Category> categories = new ArrayList<>();\r\n Cursor cursor = mDatabase.get().mSQLiteDatabase.query(TABLE_CATEGORIES,\r\n null, null, null, null, null, KEY_NAME);\r\n if (cursor.moveToFirst()) {\r\n do {\r\n Category category = Category.Builder()\r\n .id(cursor.getInt(cursor.getColumnIndex(KEY_ID)))\r\n .name(cursor.getString(cursor.getColumnIndex(KEY_NAME)))\r\n .selected(cursor.getInt(cursor.getColumnIndex(KEY_SELECTED)) == 1)\r\n .muzeiSelected(cursor.getInt(cursor.getColumnIndex(KEY_MUZEI_SELECTED)) == 1)\r\n .build();\r\n categories.add(category);\r\n } while (cursor.moveToNext());\r\n }\r\n cursor.close();\r\n return categories;\r\n }\r\n\r\n public Category getCategoryPreview(@NonNull Category category) {\r\n String name = category.getName().toLowerCase(Locale.getDefault());\r\n String query = \"SELECT wallpapers.thumbUrl, wallpapers.color, \" +\r\n \"(SELECT COUNT(*) FROM wallpapers WHERE LOWER(wallpapers.category) LIKE ?) AS \" +KEY_COUNT+\r\n \" FROM wallpapers WHERE LOWER(wallpapers.category) LIKE ? ORDER BY RANDOM() LIMIT 1\";\r\n Cursor cursor = mDatabase.get().mSQLiteDatabase.rawQuery(query, new String[]{\"%\" +name+ \"%\", \"%\" +name+ \"%\"});\r\n if (cursor.moveToFirst()) {\r\n do {\r\n category.setColor(cursor.getInt(cursor.getColumnIndex(KEY_COLOR)));\r\n category.setThumbUrl(cursor.getString(cursor.getColumnIndex(KEY_THUMB_URL)));\r\n category.setCount(cursor.getInt(cursor.getColumnIndex(KEY_COUNT)));\r\n } while (cursor.moveToNext());\r\n }\r\n cursor.close();\r\n return category;\r\n }\r\n\r\n public List<Category> getWallpaperCategories(String category) {\r\n if (!openDatabase()) {\r\n LogUtil.e(\"Database error: getWallpaperCategories() failed to open database\");\r\n return new ArrayList<>();\r\n }\r\n\r\n List<Category> categories = new ArrayList<>();\r\n String[] strings = category.split(\"[,;]\");\r\n for (String string : strings) {\r\n String s = string.toLowerCase(Locale.getDefault());\r\n String query = \"SELECT categories.id, categories.name, \" +\r\n \"(SELECT wallpapers.thumbUrl FROM wallpapers WHERE LOWER(wallpapers.category) LIKE ? ORDER BY RANDOM() LIMIT 1) AS thumbUrl, \" +\r\n \"(SELECT COUNT(*) FROM wallpapers WHERE LOWER(wallpapers.category) LIKE ?) AS \" +KEY_COUNT+\r\n \" FROM categories WHERE LOWER(categories.name) = ? LIMIT 1\";\r\n Cursor cursor = mDatabase.get().mSQLiteDatabase.rawQuery(query, new String[]{\"%\" +s+ \"%\", \"%\" +s+ \"%\", s});\r\n if (cursor.moveToFirst()) {\r\n do {\r\n Category c = Category.Builder()\r\n .id(cursor.getInt(cursor.getColumnIndex(KEY_ID)))\r\n .name(cursor.getString(cursor.getColumnIndex(KEY_NAME)))\r\n .thumbUrl(cursor.getString(2))\r\n .count(cursor.getInt(cursor.getColumnIndex(KEY_COUNT)))\r\n .build();\r\n categories.add(c);\r\n } while (cursor.moveToNext());\r\n }\r\n cursor.close();\r\n }\r\n return categories;\r\n }\r\n\r\n public int getCategoryCount(String category) {\r\n if (!openDatabase()) {\r\n LogUtil.e(\"Database error: getCategoryCount() failed to open database\");\r\n return 0;\r\n }\r\n\r\n Cursor cursor = mDatabase.get().mSQLiteDatabase.query(TABLE_WALLPAPERS, null, \"LOWER(\" +KEY_CATEGORY+ \") LIKE ?\",\r\n new String[]{\"%\" +category.toLowerCase(Locale.getDefault())+ \"%\"}, null, null, null);\r\n int count = cursor.getCount();\r\n cursor.close();\r\n return count;\r\n }\r\n\r\n @Nullable\r\n public Wallpaper getWallpaper(String url) {\r\n if (!openDatabase()) {\r\n LogUtil.e(\"Database error: getWallpaper() failed to open database\");\r\n return null;\r\n }\r\n\r\n Wallpaper wallpaper = null;\r\n Cursor cursor = mDatabase.get().mSQLiteDatabase.query(TABLE_WALLPAPERS,\r\n null, KEY_URL +\" = ?\", new String[]{url}, null, null, null, \"1\");\r\n if (cursor.moveToFirst()) {\r\n do {\r\n int width = cursor.getInt(cursor.getColumnIndex(KEY_WIDTH));\r\n int height = cursor.getInt(cursor.getColumnIndex(KEY_HEIGHT));\r\n ImageSize dimensions = null;\r\n if (width > 0 && height > 0) {\r\n dimensions = new ImageSize(width, height);\r\n }\r\n\r\n int wId = cursor.getInt(cursor.getColumnIndex(KEY_ID));\r\n String name = cursor.getString(cursor.getColumnIndex(KEY_NAME));\r\n if (name.length() == 0) {\r\n name = \"Wallpaper \"+ wId;\r\n }\r\n\r\n wallpaper = Wallpaper.Builder()\r\n .id(wId)\r\n .name(name)\r\n .author(cursor.getString(cursor.getColumnIndex(KEY_AUTHOR)))\r\n .url(cursor.getString(cursor.getColumnIndex(KEY_URL)))\r\n .thumbUrl(cursor.getString(cursor.getColumnIndex(KEY_THUMB_URL)))\r\n .category(cursor.getString(cursor.getColumnIndex(KEY_CATEGORY)))\r\n .favorite(cursor.getInt(cursor.getColumnIndex(KEY_FAVORITE)) == 1)\r\n .dimensions(dimensions)\r\n .mimeType(cursor.getString(cursor.getColumnIndex(KEY_MIME_TYPE)))\r\n .size(cursor.getInt(cursor.getColumnIndex(KEY_SIZE)))\r\n .color(cursor.getInt(cursor.getColumnIndex(KEY_COLOR)))\r\n .build();\r\n } while (cursor.moveToNext());\r\n }\r\n cursor.close();\r\n return wallpaper;\r\n }\r\n\r\n public List<Wallpaper> getFilteredWallpapers(Filter filter) {\r\n if (!openDatabase()) {\r\n LogUtil.e(\"Database error: getFilteredWallpapers() failed to open database\");\r\n return new ArrayList<>();\r\n }\r\n\r\n List<Wallpaper> wallpapers = new ArrayList<>();\r\n\r\n StringBuilder condition = new StringBuilder();\r\n List<String> selection = new ArrayList<>();\r\n for (int i = 0; i < filter.size(); i++) {\r\n Filter.Options options = filter.get(i);\r\n if (options != null) {\r\n if (condition.length() > 0 ) {\r\n condition.append(\" OR \").append(\"LOWER(\")\r\n .append(options.getColumn().getName())\r\n .append(\")\").append(\" LIKE ?\");\r\n } else {\r\n condition.append(\"LOWER(\")\r\n .append(options.getColumn().getName()).append(\")\")\r\n .append(\" LIKE ?\");\r\n }\r\n selection.add(\"%\" +options.getQuery().toLowerCase(Locale.getDefault())+ \"%\");\r\n }\r\n }\r\n\r\n Cursor cursor = mDatabase.get().mSQLiteDatabase.query(TABLE_WALLPAPERS, null, condition.toString(),\r\n selection.toArray(new String[selection.size()]),\r\n null, null, KEY_NAME);\r\n if (cursor.moveToFirst()) {\r\n do {\r\n int id = cursor.getInt(cursor.getColumnIndex(KEY_ID));\r\n String name = cursor.getString(cursor.getColumnIndex(KEY_NAME));\r\n if (name.length() == 0) {\r\n name = \"Wallpaper \"+ id;\r\n }\r\n\r\n Wallpaper wallpaper = Wallpaper.Builder()\r\n .id(id)\r\n .name(name)\r\n .author(cursor.getString(cursor.getColumnIndex(KEY_AUTHOR)))\r\n .url(cursor.getString(cursor.getColumnIndex(KEY_URL)))\r\n .thumbUrl(cursor.getString(cursor.getColumnIndex(KEY_THUMB_URL)))\r\n .category(cursor.getString(cursor.getColumnIndex(KEY_CATEGORY)))\r\n .addedOn(cursor.getString(cursor.getColumnIndex(KEY_ADDED_ON)))\r\n .favorite(cursor.getInt(cursor.getColumnIndex(KEY_FAVORITE)) == 1)\r\n .color(cursor.getInt(cursor.getColumnIndex(KEY_COLOR)))\r\n .build();\r\n wallpapers.add(wallpaper);\r\n } while (cursor.moveToNext());\r\n }\r\n cursor.close();\r\n\r\n Collections.sort(wallpapers, new AlphanumComparator() {\r\n\r\n @Override\r\n public int compare(Object o1, Object o2) {\r\n String s1 = ((Wallpaper) o1).getName();\r\n String s2 = ((Wallpaper) o2).getName();\r\n return super.compare(s1, s2);\r\n }\r\n });\r\n return wallpapers;\r\n }\r\n\r\n public List<Wallpaper> getWallpapers() {\r\n if (!openDatabase()) {\r\n LogUtil.e(\"Database error: getWallpapers() failed to open database\");\r\n return new ArrayList<>();\r\n }\r\n\r\n List<Wallpaper> wallpapers = new ArrayList<>();\r\n Cursor cursor = mDatabase.get().mSQLiteDatabase.query(TABLE_WALLPAPERS,\r\n null, null, null, null, null, getSortBy(Preferences.get(mContext).getSortBy()));\r\n if (cursor.moveToFirst()) {\r\n do {\r\n int colorIndex = cursor.getColumnIndex(KEY_COLOR);\r\n int id = cursor.getInt(cursor.getColumnIndex(KEY_ID));\r\n String name = cursor.getString(cursor.getColumnIndex(KEY_NAME));\r\n if (name.length() == 0) {\r\n name = \"Wallpaper \"+ id;\r\n }\r\n\r\n Wallpaper.Builder builder = Wallpaper.Builder()\r\n .id(id)\r\n .name(name)\r\n .author(cursor.getString(cursor.getColumnIndex(KEY_AUTHOR)))\r\n .url(cursor.getString(cursor.getColumnIndex(KEY_URL)))\r\n .thumbUrl(cursor.getString(cursor.getColumnIndex(KEY_THUMB_URL)))\r\n .category(cursor.getString(cursor.getColumnIndex(KEY_CATEGORY)))\r\n .favorite(cursor.getInt(cursor.getColumnIndex(KEY_FAVORITE)) == 1);\r\n if (colorIndex > -1) {\r\n builder.color(cursor.getInt(colorIndex));\r\n }\r\n wallpapers.add(builder.build());\r\n } while (cursor.moveToNext());\r\n }\r\n cursor.close();\r\n\r\n if (Preferences.get(mContext).getSortBy() == PopupItem.Type.SORT_NAME) {\r\n Collections.sort(wallpapers, new AlphanumComparator() {\r\n\r\n @Override\r\n public int compare(Object o1, Object o2) {\r\n String s1 = ((Wallpaper) o1).getName();\r\n String s2 = ((Wallpaper) o2).getName();\r\n return super.compare(s1, s2);\r\n }\r\n });\r\n }\r\n return wallpapers;\r\n }\r\n\r\n public List<Wallpaper> getLatestWallpapers() {\r\n if (!openDatabase()) {\r\n LogUtil.e(\"Database error: getLatestWallpapers() failed to open database\");\r\n return new ArrayList<>();\r\n }\r\n\r\n List<Wallpaper> wallpapers = new ArrayList<>();\r\n Cursor cursor = mDatabase.get().mSQLiteDatabase.query(TABLE_WALLPAPERS, null, null, null, null, null,\r\n KEY_ADDED_ON+ \" DESC, \" +KEY_ID,\r\n String.valueOf(WallpaperBoardApplication.getConfig().getLatestWallpapersDisplayMax()));\r\n if (cursor.moveToFirst()) {\r\n do {\r\n int width = cursor.getInt(cursor.getColumnIndex(KEY_WIDTH));\r\n int height = cursor.getInt(cursor.getColumnIndex(KEY_HEIGHT));\r\n ImageSize dimensions = null;\r\n if (width > 0 && height > 0) {\r\n dimensions = new ImageSize(width, height);\r\n }\r\n\r\n int id = cursor.getInt(cursor.getColumnIndex(KEY_ID));\r\n String name = cursor.getString(cursor.getColumnIndex(KEY_NAME));\r\n if (name.length() == 0) {\r\n name = \"Wallpaper \"+ id;\r\n }\r\n\r\n Wallpaper wallpaper = Wallpaper.Builder()\r\n .id(id)\r\n .name(name)\r\n .author(cursor.getString(cursor.getColumnIndex(KEY_AUTHOR)))\r\n .url(cursor.getString(cursor.getColumnIndex(KEY_URL)))\r\n .thumbUrl(cursor.getString(cursor.getColumnIndex(KEY_THUMB_URL)))\r\n .category(cursor.getString(cursor.getColumnIndex(KEY_CATEGORY)))\r\n .favorite(cursor.getInt(cursor.getColumnIndex(KEY_FAVORITE)) == 1)\r\n .dimensions(dimensions)\r\n .mimeType(cursor.getString(cursor.getColumnIndex(KEY_MIME_TYPE)))\r\n .size(cursor.getInt(cursor.getColumnIndex(KEY_SIZE)))\r\n .color(cursor.getInt(cursor.getColumnIndex(KEY_COLOR)))\r\n .build();\r\n wallpapers.add(wallpaper);\r\n } while (cursor.moveToNext());\r\n }\r\n cursor.close();\r\n return wallpapers;\r\n }\r\n\r\n @Nullable\r\n public Wallpaper getRandomWallpaper() {\r\n if (!openDatabase()) {\r\n LogUtil.e(\"Database error: getRandomWallpaper() failed to open database\");\r\n return null;\r\n }\r\n\r\n Wallpaper wallpaper = null;\r\n List<String> selected = getSelectedCategories(true);\r\n List<String> selection = new ArrayList<>();\r\n if (selected.size() == 0) return null;\r\n\r\n StringBuilder CONDITION = new StringBuilder();\r\n for (String item : selected) {\r\n if (CONDITION.length() > 0 ) {\r\n CONDITION.append(\" OR \").append(\"LOWER(\").append(KEY_CATEGORY).append(\")\").append(\" LIKE ?\");\r\n } else {\r\n CONDITION.append(\"LOWER(\").append(KEY_CATEGORY).append(\")\").append(\" LIKE ?\");\r\n }\r\n selection.add(\"%\" +item.toLowerCase(Locale.getDefault())+ \"%\");\r\n }\r\n\r\n Cursor cursor = mDatabase.get().mSQLiteDatabase.query(TABLE_WALLPAPERS, null, CONDITION.toString(),\r\n selection.toArray(new String[selection.size()]), null, null, \"RANDOM()\", \"1\");\r\n if (cursor.moveToFirst()) {\r\n do {\r\n int id = cursor.getInt(cursor.getColumnIndex(KEY_ID));\r\n String name = cursor.getString(cursor.getColumnIndex(KEY_NAME));\r\n if (name.length() == 0) {\r\n name = \"Wallpaper \"+ id;\r\n }\r\n\r\n wallpaper = Wallpaper.Builder()\r\n .name(name)\r\n .author(cursor.getString(cursor.getColumnIndex(KEY_AUTHOR)))\r\n .url(cursor.getString(cursor.getColumnIndex(KEY_URL)))\r\n .thumbUrl(cursor.getString(cursor.getColumnIndex(KEY_THUMB_URL)))\r\n .category(cursor.getString(cursor.getColumnIndex(KEY_CATEGORY)))\r\n .build();\r\n } while (cursor.moveToNext());\r\n }\r\n cursor.close();\r\n return wallpaper;\r\n }\r\n\r\n public int getWallpapersCount() {\r\n if (!openDatabase()) {\r\n LogUtil.e(\"Database error: getWallpapersCount() failed to open database\");\r\n return 0;\r\n }\r\n\r\n Cursor cursor = mDatabase.get().mSQLiteDatabase.query(TABLE_WALLPAPERS, null, null, null, null, null, null, null);\r\n int rowCount = cursor.getCount();\r\n cursor.close();\r\n return rowCount;\r\n }\r\n\r\n public List<Wallpaper> getFavoriteWallpapers() {\r\n if (!openDatabase()) {\r\n LogUtil.e(\"Database error: getFavoriteWallpapers() failed to open database\");\r\n return new ArrayList<>();\r\n }\r\n\r\n List<Wallpaper> wallpapers = new ArrayList<>();\r\n Cursor cursor = mDatabase.get().mSQLiteDatabase.query(TABLE_WALLPAPERS, null, KEY_FAVORITE +\" = ?\",\r\n new String[]{\"1\"}, null, null, KEY_NAME +\", \"+ KEY_ID);\r\n if (cursor.moveToFirst()) {\r\n do {\r\n int width = cursor.getInt(cursor.getColumnIndex(KEY_WIDTH));\r\n int height = cursor.getInt(cursor.getColumnIndex(KEY_HEIGHT));\r\n ImageSize dimensions = null;\r\n if (width > 0 && height > 0) {\r\n dimensions = new ImageSize(width, height);\r\n }\r\n\r\n int id = cursor.getInt(cursor.getColumnIndex(KEY_ID));\r\n String name = cursor.getString(cursor.getColumnIndex(KEY_NAME));\r\n if (name.length() == 0) {\r\n name = \"Wallpaper \"+ id;\r\n }\r\n\r\n Wallpaper wallpaper = Wallpaper.Builder()\r\n .id(id)\r\n .name(name)\r\n .author(cursor.getString(cursor.getColumnIndex(KEY_AUTHOR)))\r\n .url(cursor.getString(cursor.getColumnIndex(KEY_URL)))\r\n .thumbUrl(cursor.getString(cursor.getColumnIndex(KEY_THUMB_URL)))\r\n .category(cursor.getString(cursor.getColumnIndex(KEY_CATEGORY)))\r\n .favorite(cursor.getInt(cursor.getColumnIndex(KEY_FAVORITE)) == 1)\r\n .dimensions(dimensions)\r\n .mimeType(cursor.getString(cursor.getColumnIndex(KEY_MIME_TYPE)))\r\n .size(cursor.getInt(cursor.getColumnIndex(KEY_SIZE)))\r\n .color(cursor.getInt(cursor.getColumnIndex(KEY_COLOR)))\r\n .build();\r\n wallpapers.add(wallpaper);\r\n } while (cursor.moveToNext());\r\n }\r\n cursor.close();\r\n\r\n if (Preferences.get(mContext).getSortBy() == PopupItem.Type.SORT_NAME) {\r\n Collections.sort(wallpapers, new AlphanumComparator() {\r\n\r\n @Override\r\n public int compare(Object o1, Object o2) {\r\n String s1 = ((Wallpaper) o1).getName();\r\n String s2 = ((Wallpaper) o2).getName();\r\n return super.compare(s1, s2);\r\n }\r\n });\r\n }\r\n return wallpapers;\r\n }\r\n\r\n public void deleteWallpapers(@NonNull List<Wallpaper> wallpapers) {\r\n if (!openDatabase()) {\r\n LogUtil.e(\"Database error: deleteWallpapers() failed to open database\");\r\n return;\r\n }\r\n\r\n String query = \"DELETE FROM \" +TABLE_WALLPAPERS+ \" WHERE \" +KEY_URL+ \" = ?\";\r\n SQLiteStatement statement = mDatabase.get().mSQLiteDatabase.compileStatement(query);\r\n mDatabase.get().mSQLiteDatabase.beginTransaction();\r\n\r\n for (Wallpaper wallpaper : wallpapers) {\r\n statement.clearBindings();\r\n statement.bindString(1, wallpaper.getUrl());\r\n statement.execute();\r\n }\r\n\r\n mDatabase.get().mSQLiteDatabase.setTransactionSuccessful();\r\n mDatabase.get().mSQLiteDatabase.endTransaction();\r\n }\r\n\r\n public void resetAutoIncrement() {\r\n if (!openDatabase()) {\r\n LogUtil.e(\"Database error: resetAutoIncrement() failed to open database\");\r\n return;\r\n }\r\n\r\n mSQLiteDatabase.delete(\"SQLITE_SEQUENCE\", \"NAME = ?\", new String[]{TABLE_WALLPAPERS});\r\n }\r\n\r\n public void deleteCategories(@NonNull List<Category> categories) {\r\n if (!openDatabase()) {\r\n LogUtil.e(\"Database error: deleteCategories() failed to open database\");\r\n return;\r\n }\r\n\r\n String query = \"DELETE FROM \" +TABLE_CATEGORIES+ \" WHERE \" +KEY_NAME+ \" = ?\";\r\n SQLiteStatement statement = mDatabase.get().mSQLiteDatabase.compileStatement(query);\r\n mDatabase.get().mSQLiteDatabase.beginTransaction();\r\n\r\n for (Category category : categories) {\r\n statement.clearBindings();\r\n statement.bindString(1, category.getName());\r\n statement.execute();\r\n }\r\n\r\n mDatabase.get().mSQLiteDatabase.setTransactionSuccessful();\r\n mDatabase.get().mSQLiteDatabase.endTransaction();\r\n }\r\n\r\n private String getSortBy(PopupItem.Type type) {\r\n switch (type) {\r\n case SORT_LATEST:\r\n return KEY_ADDED_ON +\" DESC, \"+ KEY_ID;\r\n case SORT_OLDEST:\r\n return KEY_ADDED_ON +\", \"+ KEY_ID +\" DESC\";\r\n case SORT_NAME:\r\n return KEY_NAME;\r\n case SORT_RANDOM:\r\n return \"RANDOM()\";\r\n default:\r\n return KEY_ADDED_ON +\" DESC, \"+ KEY_ID;\r\n }\r\n }\r\n}\r", "public class Filter {\r\n\r\n private List<Options> mOptions;\r\n\r\n public Filter() {\r\n mOptions = new ArrayList<>();\r\n }\r\n\r\n public Filter add(Options options) {\r\n if (mOptions.contains(options)) {\r\n LogUtil.e(\"filter already contains options\");\r\n return this;\r\n }\r\n mOptions.add(options);\r\n return this;\r\n }\r\n\r\n @Nullable\r\n public Options get(int index) {\r\n if (index < 0 || index > mOptions.size()) {\r\n LogUtil.e(\"filter: index out of bounds\");\r\n return null;\r\n }\r\n return mOptions.get(index);\r\n }\r\n\r\n public int size() {\r\n return mOptions.size();\r\n }\r\n\r\n public static Options Create(Column column) {\r\n return new Options(column);\r\n }\r\n\r\n public static class Options {\r\n\r\n private Column mColumn;\r\n private String mQuery;\r\n\r\n private Options(Column column) {\r\n mColumn = column;\r\n mQuery = \"\";\r\n }\r\n\r\n public Options setQuery(String query) {\r\n mQuery = query;\r\n return this;\r\n }\r\n\r\n public Column getColumn() {\r\n return mColumn;\r\n }\r\n\r\n public String getQuery() {\r\n return mQuery;\r\n }\r\n\r\n @Override\r\n public boolean equals(Object object) {\r\n boolean equals = false;\r\n if (object != null && object instanceof Options) {\r\n equals = mColumn == ((Options) object).getColumn() &&\r\n mQuery.equals(((Options) object).getQuery());\r\n }\r\n return equals;\r\n }\r\n }\r\n\r\n public enum Column {\r\n ID(Database.KEY_ID),\r\n NAME(Database.KEY_NAME),\r\n AUTHOR(Database.KEY_AUTHOR),\r\n CATEGORY(Database.KEY_CATEGORY);\r\n\r\n private String mName;\r\n\r\n Column(String name) {\r\n mName = name;\r\n }\r\n\r\n public String getName() {\r\n return mName;\r\n }\r\n }\r\n}\r", "public class Wallpaper {\r\n\r\n private int mId;\r\n private final String mName;\r\n private final String mAuthor;\r\n private final String mThumbUrl;\r\n private final String mUrl;\r\n private final String mCategory;\r\n private final String mAddedOn;\r\n private int mColor;\r\n private String mMimeType;\r\n private int mSize;\r\n private boolean mIsFavorite;\r\n private ImageSize mDimensions;\r\n\r\n private Wallpaper(String name, String author, String url, String thumbUrl, String category, String addedOn) {\r\n mName = name;\r\n mAuthor = author;\r\n mUrl = url;\r\n mThumbUrl = thumbUrl;\r\n mCategory = category;\r\n mAddedOn = addedOn;\r\n }\r\n\r\n public int getId() {\r\n return mId;\r\n }\r\n\r\n public String getName() {\r\n return mName;\r\n }\r\n\r\n public String getAuthor() {\r\n return mAuthor;\r\n }\r\n\r\n public String getUrl() {\r\n return mUrl;\r\n }\r\n\r\n public String getThumbUrl() {\r\n return mThumbUrl;\r\n }\r\n\r\n public String getCategory() {\r\n return mCategory;\r\n }\r\n\r\n public String getAddedOn() {\r\n return mAddedOn;\r\n }\r\n\r\n public int getColor() {\r\n return mColor;\r\n }\r\n\r\n public String getMimeType() {\r\n return mMimeType;\r\n }\r\n\r\n public int getSize() {\r\n return mSize;\r\n }\r\n\r\n public ImageSize getDimensions() {\r\n return mDimensions;\r\n }\r\n\r\n public boolean isFavorite() {\r\n return mIsFavorite;\r\n }\r\n\r\n public void setId(int id) {\r\n mId = id;\r\n }\r\n\r\n public void setColor(int color) {\r\n mColor = color;\r\n }\r\n\r\n public void setMimeType(String mimeType) {\r\n mMimeType = mimeType;\r\n }\r\n\r\n public void setSize(int size) {\r\n mSize = size;\r\n }\r\n\r\n public void setDimensions(ImageSize dimensions) {\r\n mDimensions = dimensions;\r\n }\r\n\r\n public void setFavorite(boolean isFavorite) {\r\n mIsFavorite = isFavorite;\r\n }\r\n\r\n @Override\r\n public boolean equals(Object object) {\r\n boolean equals = false;\r\n if (object != null && object instanceof Wallpaper) {\r\n equals = mAuthor.equals(((Wallpaper) object).getAuthor()) &&\r\n mUrl.equals(((Wallpaper) object).getUrl()) &&\r\n mThumbUrl.equals(((Wallpaper) object).getThumbUrl()) &&\r\n mCategory.equals(((Wallpaper) object).getCategory());\r\n }\r\n return equals;\r\n }\r\n\r\n public static Builder Builder() {\r\n return new Builder();\r\n }\r\n\r\n public static class Builder {\r\n\r\n private int mId;\r\n private String mName;\r\n private String mAuthor;\r\n private String mThumbUrl;\r\n private String mUrl;\r\n private String mCategory;\r\n private String mAddedOn;\r\n private int mColor;\r\n private String mMimeType;\r\n private int mSize;\r\n private boolean mIsFavorite;\r\n private ImageSize mDimensions;\r\n\r\n private Builder() {\r\n mId = -1;\r\n mSize = 0;\r\n mColor = 0;\r\n }\r\n\r\n public Builder id(int id) {\r\n mId = id;\r\n return this;\r\n }\r\n\r\n public Builder name(String name) {\r\n mName = name;\r\n return this;\r\n }\r\n\r\n public Builder author(String author) {\r\n mAuthor = author;\r\n return this;\r\n }\r\n\r\n public Builder url(String url) {\r\n mUrl = url;\r\n return this;\r\n }\r\n\r\n public Builder thumbUrl(String thumbUrl) {\r\n mThumbUrl = thumbUrl;\r\n return this;\r\n }\r\n\r\n public Builder category(String category) {\r\n mCategory = category;\r\n return this;\r\n }\r\n\r\n public Builder addedOn(String addedOn) {\r\n mAddedOn = addedOn;\r\n return this;\r\n }\r\n\r\n public Builder favorite(boolean isFavorite) {\r\n mIsFavorite = isFavorite;\r\n return this;\r\n }\r\n\r\n public Builder dimensions(ImageSize dimensions) {\r\n mDimensions = dimensions;\r\n return this;\r\n }\r\n\r\n public Builder mimeType(String mimeType) {\r\n mMimeType = mimeType;\r\n return this;\r\n }\r\n\r\n public Builder size(int size) {\r\n mSize = size;\r\n return this;\r\n }\r\n\r\n public Builder color(int color) {\r\n mColor = color;\r\n return this;\r\n }\r\n\r\n public Wallpaper build() {\r\n Wallpaper wallpaper = new Wallpaper(mName, mAuthor, mUrl, mThumbUrl, mCategory, mAddedOn);\r\n wallpaper.setId(mId);\r\n wallpaper.setDimensions(mDimensions);\r\n wallpaper.setFavorite(mIsFavorite);\r\n wallpaper.setMimeType(mMimeType);\r\n wallpaper.setSize(mSize);\r\n wallpaper.setColor(mColor);\r\n return wallpaper;\r\n }\r\n }\r\n}\r", "public class Preferences {\r\n\r\n private static final String PREFERENCES_NAME = \"wallpaper_board_preferences\";\r\n\r\n private static final String KEY_LICENSED = \"licensed\";\r\n private static final String KEY_FIRST_RUN = \"first_run\";\r\n private static final String KEY_DARK_THEME = \"dark_theme\";\r\n private static final String KEY_ROTATE_TIME = \"rotate_time\";\r\n private static final String KEY_ROTATE_MINUTE = \"rotate_minute\";\r\n private static final String KEY_WIFI_ONLY = \"wifi_only\";\r\n private static final String KEY_WALLS_DIRECTORY = \"wallpaper_download_directory\";\r\n private static final String KEY_CROP_WALLPAPER = \"crop_wallpaper\";\r\n private static final String KEY_WALLPAPER_PREVIEW_INTRO = \"wallpaper_preview_intro\";\r\n private static final String KEY_CURRENT_LOCALE = \"current_locale\";\r\n private static final String KEY_LOCALE_DEFAULT = \"localeDefault\";\r\n private static final String KEY_WALLPAPER_TOOLTIP = \"wallpaper_tooltip\";\r\n private static final String KEY_SORT_BY = \"sort_by\";\r\n private static final String KEY_HIGH_QUALITY_PREVIEW = \"high_quality_preview\";\r\n private static final String KEY_BACKUP = \"backup\";\r\n private static final String KEY_PREVIOUS_BACKUP = \"previousBackup\";\r\n\r\n private static WeakReference<Preferences> mPreferences;\r\n private final Context mContext;\r\n\r\n private Preferences(@NonNull Context context) {\r\n mContext = context;\r\n }\r\n\r\n @NonNull\r\n public static Preferences get(@NonNull Context context) {\r\n if (mPreferences == null || mPreferences.get() == null) {\r\n mPreferences = new WeakReference<>(new Preferences(context));\r\n }\r\n return mPreferences.get();\r\n }\r\n\r\n private SharedPreferences getSharedPreferences() {\r\n return mPreferences.get().mContext.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);\r\n }\r\n\r\n public void clearPreferences() {\r\n boolean isLicensed = isLicensed();\r\n getSharedPreferences().edit().clear().apply();\r\n\r\n if (isLicensed) {\r\n setFirstRun(false);\r\n setLicensed(true);\r\n }\r\n }\r\n\r\n public boolean isLicensed() {\r\n return getSharedPreferences().getBoolean(KEY_LICENSED, false);\r\n }\r\n\r\n public void setLicensed(boolean bool) {\r\n getSharedPreferences().edit().putBoolean(KEY_LICENSED, bool).apply();\r\n }\r\n\r\n public boolean isFirstRun() {\r\n return getSharedPreferences().getBoolean(KEY_FIRST_RUN, true);\r\n }\r\n\r\n public void setFirstRun(boolean bool) {\r\n getSharedPreferences().edit().putBoolean(KEY_FIRST_RUN, bool).apply();\r\n }\r\n\r\n public boolean isDarkTheme() {\r\n boolean useDarkTheme = mPreferences.get().mContext.getResources().getBoolean(R.bool.use_dark_theme);\r\n boolean isThemingEnabled = WallpaperBoardApplication.getConfig().isDashboardThemingEnabled();\r\n if (!isThemingEnabled) return useDarkTheme;\r\n return getSharedPreferences().getBoolean(KEY_DARK_THEME, useDarkTheme);\r\n }\r\n\r\n public void setDarkTheme(boolean bool) {\r\n getSharedPreferences().edit().putBoolean(KEY_DARK_THEME, bool).apply();\r\n }\r\n\r\n public boolean isShadowEnabled() {\r\n return WallpaperBoardApplication.getConfig().isShadowEnabled();\r\n }\r\n\r\n public boolean isTimeToShowWallpaperPreviewIntro() {\r\n return getSharedPreferences().getBoolean(KEY_WALLPAPER_PREVIEW_INTRO, true);\r\n }\r\n\r\n public void setTimeToShowWallpaperPreviewIntro(boolean bool) {\r\n getSharedPreferences().edit().putBoolean(KEY_WALLPAPER_PREVIEW_INTRO, bool).apply();\r\n }\r\n\r\n public void setRotateTime (int time) {\r\n getSharedPreferences().edit().putInt(KEY_ROTATE_TIME, time).apply();\r\n }\r\n\r\n public int getRotateTime() {\r\n return getSharedPreferences().getInt(KEY_ROTATE_TIME, 3600000);\r\n }\r\n\r\n public void setRotateMinute (boolean bool) {\r\n getSharedPreferences().edit().putBoolean(KEY_ROTATE_MINUTE, bool).apply();\r\n }\r\n\r\n public boolean isRotateMinute() {\r\n return getSharedPreferences().getBoolean(KEY_ROTATE_MINUTE, false);\r\n }\r\n\r\n public boolean isWifiOnly() {\r\n return getSharedPreferences().getBoolean(KEY_WIFI_ONLY, false);\r\n }\r\n\r\n public void setWifiOnly (boolean bool) {\r\n getSharedPreferences().edit().putBoolean(KEY_WIFI_ONLY, bool).apply();\r\n }\r\n\r\n void setWallsDirectory(String directory) {\r\n getSharedPreferences().edit().putString(KEY_WALLS_DIRECTORY, directory).apply();\r\n }\r\n\r\n public String getWallsDirectory() {\r\n return getSharedPreferences().getString(KEY_WALLS_DIRECTORY, \"\");\r\n }\r\n\r\n public boolean isCropWallpaper() {\r\n return getSharedPreferences().getBoolean(KEY_CROP_WALLPAPER,\r\n WallpaperBoardApplication.getConfig().isCropWallpaperEnabledByDefault());\r\n }\r\n\r\n public void setCropWallpaper(boolean bool) {\r\n getSharedPreferences().edit().putBoolean(KEY_CROP_WALLPAPER, bool).apply();\r\n }\r\n\r\n public boolean isShowWallpaperTooltip() {\r\n return getSharedPreferences().getBoolean(KEY_WALLPAPER_TOOLTIP, true);\r\n }\r\n\r\n public void setShowWallpaperTooltip(boolean bool) {\r\n getSharedPreferences().edit().putBoolean(KEY_WALLPAPER_TOOLTIP, bool).apply();\r\n }\r\n\r\n public boolean isHighQualityPreviewEnabled() {\r\n return getSharedPreferences().getBoolean(KEY_HIGH_QUALITY_PREVIEW,\r\n WallpaperBoardApplication.getConfig().isHighQualityPreviewEnabled());\r\n }\r\n\r\n public void setHighQualityPreviewEnabled(boolean bool) {\r\n getSharedPreferences().edit().putBoolean(KEY_HIGH_QUALITY_PREVIEW, bool).apply();\r\n }\r\n\r\n public boolean isBackupRestored() {\r\n return getSharedPreferences().getBoolean(KEY_BACKUP, false);\r\n }\r\n\r\n public void setBackupRestored(boolean bool) {\r\n getSharedPreferences().edit().putBoolean(KEY_BACKUP, bool).apply();\r\n }\r\n\r\n public boolean isPreviousBackupExist() {\r\n return getSharedPreferences().getBoolean(KEY_PREVIOUS_BACKUP, false);\r\n }\r\n\r\n public void setPreviousBackupExist(boolean bool) {\r\n getSharedPreferences().edit().putBoolean(KEY_PREVIOUS_BACKUP, bool).apply();\r\n }\r\n\r\n public Locale getCurrentLocale() {\r\n if (isLocaleDefault()) {\r\n Locale defaultLocale = getDefaultLocale();\r\n if (defaultLocale != null) {\r\n return defaultLocale;\r\n }\r\n }\r\n\r\n String code = getSharedPreferences().getString(KEY_CURRENT_LOCALE, \"en_US\");\r\n return LocaleHelper.getLocale(code);\r\n }\r\n\r\n public void setCurrentLocale(String code) {\r\n getSharedPreferences().edit().putString(KEY_CURRENT_LOCALE, code).apply();\r\n }\r\n\r\n public boolean isLocaleDefault() {\r\n return getSharedPreferences().getBoolean(KEY_LOCALE_DEFAULT, true);\r\n }\r\n\r\n public void setLocaleDefault(boolean bool) {\r\n getSharedPreferences().edit().putBoolean(KEY_LOCALE_DEFAULT, bool).apply();\r\n }\r\n\r\n @Nullable\r\n private Locale getDefaultLocale() {\r\n Locale locale = LocaleHelper.getSystem();\r\n List<Language> languages = LocaleHelper.getAvailableLanguages(mContext);\r\n\r\n Locale currentLocale = null;\r\n for (Language language : languages) {\r\n Locale l = language.getLocale();\r\n if (locale.toString().equals(l.toString())) {\r\n currentLocale = l;\r\n break;\r\n }\r\n }\r\n\r\n if (currentLocale == null) {\r\n for (Language language : languages) {\r\n Locale l = language.getLocale();\r\n if (locale.getLanguage().equals(l.getLanguage())) {\r\n currentLocale = l;\r\n break;\r\n }\r\n }\r\n }\r\n return currentLocale;\r\n }\r\n\r\n public void setSortBy(PopupItem.Type type) {\r\n getSharedPreferences().edit().putInt(KEY_SORT_BY, getSortByOrder(type)).apply();\r\n }\r\n\r\n public int getSortByOrder(PopupItem.Type type) {\r\n switch (type) {\r\n case SORT_LATEST:\r\n return 0;\r\n case SORT_OLDEST:\r\n return 1;\r\n case SORT_NAME:\r\n return 2;\r\n case SORT_RANDOM:\r\n return 3;\r\n default:\r\n return 2;\r\n }\r\n }\r\n\r\n public PopupItem.Type getSortBy(){\r\n int sort = getSharedPreferences().getInt(KEY_SORT_BY, 2);\r\n if (sort == 0) {\r\n return PopupItem.Type.SORT_LATEST;\r\n } else if (sort == 1) {\r\n return PopupItem.Type.SORT_OLDEST;\r\n } else if (sort == 2) {\r\n return PopupItem.Type.SORT_NAME;\r\n } else if (sort == 3) {\r\n return PopupItem.Type.SORT_RANDOM;\r\n }\r\n return PopupItem.Type.SORT_NAME;\r\n }\r\n\r\n public boolean isConnectedToNetwork() {\r\n try {\r\n ConnectivityManager connectivityManager = (ConnectivityManager)\r\n mPreferences.get().mContext.getSystemService(Context.CONNECTIVITY_SERVICE);\r\n NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();\r\n return activeNetworkInfo != null && activeNetworkInfo.isConnected();\r\n } catch (Exception e) {\r\n return false;\r\n }\r\n }\r\n\r\n public boolean isConnectedAsPreferred() {\r\n try {\r\n if (isWifiOnly()) {\r\n ConnectivityManager connectivityManager = (ConnectivityManager)\r\n mPreferences.get().mContext.getSystemService(Context.CONNECTIVITY_SERVICE);\r\n NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();\r\n return activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI &&\r\n activeNetworkInfo.isConnected();\r\n }\r\n return true;\r\n } catch (Exception e) {\r\n return false;\r\n }\r\n }\r\n}\r", "public static void resetViewBottomPadding(@Nullable View view, boolean scroll) {\r\n if (view == null) return;\r\n\r\n Context context = ContextHelper.getBaseContext(view);\r\n int orientation = context.getResources().getConfiguration().orientation;\r\n\r\n int left = view.getPaddingLeft();\r\n int right = view.getPaddingRight();\r\n int bottom = view.getPaddingTop();\r\n int top = view.getPaddingTop();\r\n int navBar = 0;\r\n\r\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\r\n boolean tabletMode = context.getResources().getBoolean(R.bool.android_helpers_tablet_mode);\r\n if (tabletMode || orientation == Configuration.ORIENTATION_PORTRAIT) {\r\n navBar = getNavigationBarHeight(context);\r\n }\r\n\r\n if (!scroll) {\r\n navBar += getStatusBarHeight(context);\r\n }\r\n }\r\n\r\n if (!scroll) {\r\n navBar += getToolbarHeight(context);\r\n }\r\n view.setPadding(left, top, right, (bottom + navBar));\r\n}\r" ]
import android.content.res.Configuration; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.view.animation.LinearOutSlowInInterpolator; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.TextView; import com.danimahardhika.android.helpers.animation.AnimationHelper; import com.danimahardhika.android.helpers.core.ColorHelper; import com.danimahardhika.android.helpers.core.DrawableHelper; import com.danimahardhika.android.helpers.core.SoftKeyboardHelper; import com.danimahardhika.android.helpers.core.ViewHelper; import com.dm.wallpaper.board.R; import com.dm.wallpaper.board.R2; import com.dm.wallpaper.board.adapters.WallpapersAdapter; import com.dm.wallpaper.board.applications.WallpaperBoardApplication; import com.dm.wallpaper.board.applications.WallpaperBoardConfiguration; import com.dm.wallpaper.board.databases.Database; import com.dm.wallpaper.board.items.Filter; import com.dm.wallpaper.board.items.Wallpaper; import com.dm.wallpaper.board.preferences.Preferences; import com.danimahardhika.android.helpers.core.utils.LogUtil; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import static com.dm.wallpaper.board.helpers.ViewHelper.resetViewBottomPadding;
mRecyclerView.setItemAnimator(new DefaultItemAnimator()); mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), getActivity().getResources().getInteger(R.integer.wallpapers_column_count))); mRecyclerView.setHasFixedSize(false); if (WallpaperBoardApplication.getConfig().getWallpapersGrid() == WallpaperBoardConfiguration.GridStyle.FLAT) { int padding = getActivity().getResources().getDimensionPixelSize(R.dimen.card_margin); mRecyclerView.setPadding(padding, padding, 0, 0); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.menu_wallpaper_search, menu); MenuItem search = menu.findItem(R.id.menu_search); int color = ColorHelper.getAttributeColor(getActivity(), R.attr.toolbar_icon); search.setIcon(DrawableHelper.getTintedDrawable(getActivity(), R.drawable.ic_toolbar_search, color)); mSearchView = (SearchView) search.getActionView(); mSearchView.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI | EditorInfo.IME_ACTION_SEARCH); mSearchView.setQueryHint(getActivity().getResources().getString(R.string.menu_search)); mSearchView.setMaxWidth(Integer.MAX_VALUE); search.expandActionView(); mSearchView.setIconifiedByDefault(false); mSearchView.requestFocus(); ViewHelper.setSearchViewTextColor(mSearchView, color); ViewHelper.setSearchViewBackgroundColor(mSearchView, Color.TRANSPARENT); ViewHelper.setSearchViewCloseIcon(mSearchView, DrawableHelper.getTintedDrawable(getActivity(), R.drawable.ic_toolbar_close, color)); ViewHelper.setSearchViewSearchIcon(mSearchView, null); mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextChange(String string) { if (string.length() == 0) { clearAdapter(); return false; } if (mAsyncTask != null) { mAsyncTask.cancel(true); } mAsyncTask = new WallpapersLoader(string.trim()) .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); return true; } @Override public boolean onQueryTextSubmit(String string) { mSearchView.clearFocus(); mAsyncTask = new WallpapersLoader(string.trim()) .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); return true; } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { getActivity().finish(); getActivity().overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); return true; } return super.onOptionsItemSelected(item); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); ViewHelper.resetSpanCount(mRecyclerView, getActivity().getResources().getInteger( R.integer.wallpapers_column_count)); resetViewBottomPadding(mRecyclerView, true); } @Override public void onDestroy() { if (mAsyncTask != null) mAsyncTask.cancel(true); super.onDestroy(); } private void initSearchResult() { Drawable drawable = DrawableHelper.getTintedDrawable( getActivity(), R.drawable.ic_toolbar_search_large, Color.WHITE); mSearchResult.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null); } public boolean isSearchQueryEmpty() { return mSearchView.getQuery() == null || mSearchView.getQuery().length() == 0; } public void filterSearch(String query) { mAsyncTask = new WallpapersLoader(query).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } private void clearAdapter() { if (mAdapter == null) return; mAdapter.clearItems(); if (mSearchResult.getVisibility() == View.VISIBLE) { AnimationHelper.fade(mSearchResult).start(); } AnimationHelper.setBackgroundColor(mRecyclerView, ((ColorDrawable) mRecyclerView.getBackground()).getColor(), Color.TRANSPARENT) .interpolator(new LinearOutSlowInInterpolator()) .start(); } private class WallpapersLoader extends AsyncTask<Void, Void, Boolean> {
private List<Wallpaper> wallpapers;
5
yuqirong/NewsPublish
src/com/cjlu/newspublish/services/impl/RoleServiceImpl.java
[ "@Repository(\"roleDao\")\npublic class RoleDaoImpl extends BaseDaoImpl<Role> {\n\n\tpublic List<Role> findRolesNotInRange(Set<Role> set) {\n\t\tString hql = \"from Role r where r.id not in (\"\n\t\t\t\t+ DataUtils.extractRoleIds(set) + \")\";\n\t\treturn this.findEntityByHQL(hql);\n\t}\n\n\tpublic List<Role> findRolesInRange(Integer[] ownRoleIds) {\n\t\tString hql = \"from Role r where r.id in (\"\n\t\t\t\t+ StringUtils.arr2String(ownRoleIds) + \")\";\n\t\treturn this.findEntityByHQL(hql);\n\t}\n\n}", "public class Right extends BaseEntity{\n\t\n\tprivate static final long serialVersionUID = -7550772473227188714L;\n\tprivate String rightName = \"δÃüÃû\";\n\tprivate String rightUrl;\n\tprivate boolean common;\n\tprivate String rightDesc;\n\tprivate long rightCode;// ȨÏÞÂë,1<<n\n\tprivate int rightPos; // ȨÏÞλ,Ï൱ÓÚ¶ÔȨÏÞ·Ö×é,´Ó0¿ªÊ¼\n\t\n\tpublic String getRightName() {\n\t\treturn rightName;\n\t}\n\tpublic void setRightName(String rightName) {\n\t\tthis.rightName = rightName;\n\t}\n\tpublic String getRightUrl() {\n\t\treturn rightUrl;\n\t}\n\tpublic void setRightUrl(String rightUrl) {\n\t\tthis.rightUrl = rightUrl;\n\t}\n\tpublic String getRightDesc() {\n\t\treturn rightDesc;\n\t}\n\tpublic void setRightDesc(String rightDesc) {\n\t\tthis.rightDesc = rightDesc;\n\t}\n\tpublic long getRightCode() {\n\t\treturn rightCode;\n\t}\n\tpublic void setRightCode(long rightCode) {\n\t\tthis.rightCode = rightCode;\n\t}\n\tpublic int getRightPos() {\n\t\treturn rightPos;\n\t}\n\tpublic void setRightPos(int rightPos) {\n\t\tthis.rightPos = rightPos;\n\t}\n\tpublic boolean isCommon() {\n\t\treturn common;\n\t}\n\tpublic void setCommon(boolean common) {\n\t\tthis.common = common;\n\t}\n\n}", "public class Role extends BaseEntity{\n\t\n\tprivate static final long serialVersionUID = 596760102394542763L;\n\tprivate String roleName;\n\tprivate String roleValue;\n\tprivate String roleDesc;\n\tprivate Set<Right> rights = new HashSet<Right>();\n\t\n\tpublic String getRoleName() {\n\t\treturn roleName;\n\t}\n\tpublic void setRoleName(String roleName) {\n\t\tthis.roleName = roleName;\n\t}\n\tpublic String getRoleValue() {\n\t\treturn roleValue;\n\t}\n\tpublic void setRoleValue(String roleValue) {\n\t\tthis.roleValue = roleValue;\n\t}\n\tpublic String getRoleDesc() {\n\t\treturn roleDesc;\n\t}\n\tpublic void setRoleDesc(String roleDesc) {\n\t\tthis.roleDesc = roleDesc;\n\t}\n\tpublic Set<Right> getRights() {\n\t\treturn rights;\n\t}\n\tpublic void setRights(Set<Right> rights) {\n\t\tthis.rights = rights;\n\t}\n\t\n}", "public interface RightService extends BaseService<Right> {\n\n\tpublic void saveOrUpdateRight(Right model);\n\n\tpublic void appendRightByURL(String url);\n\n\tpublic void batchSaveRight(List<Right> allRights);\n\n\tpublic List<Right> findRightsInRange(Integer[] ownRightIds);\n\n\tpublic List<Right> findRightsNotInRange(Set<Right> rights);\n\n\tpublic int getMaxRightPos();\n\n\tpublic Page<Right> listAllRightPage(int i, int pageSize);\n\n}", "public interface RoleService extends BaseService<Role>{\n\n\tpublic void saveOrUpdateRole(Role model, Integer[] ownRightIds);\n\n\tpublic List<Role> findRolesNotInRange(Set<Role> set);\n\n\tpublic List<Role> findRolesInRange(Integer[] ownRoleIds);\n\n}", "public final class ValidateUtils {\n\t\n\tprivate ValidateUtils(){\n\t\t\n\t}\n\n\t/**\n\t * ÅжÏ×Ö·û´®µÄÓÐЧÐÔ\n\t */\n\tpublic static boolean isValid(String str) {\n\t\tif (str == null || \"\".equals(str.trim())) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * Åжϼ¯ºÏµÄÓÐЧÐÔ\n\t */\n\t@SuppressWarnings(\"rawtypes\")\n\tpublic static boolean isValid(Collection collection) {\n\t\tif (collection == null || collection.isEmpty()) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * ÅжÏÊý×éÊÇ·ñÓÐЧ\n\t */\n\tpublic static boolean isValid(Object[] arr) {\n\t\tif (arr == null || arr.length == 0) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t@SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n\tpublic static boolean hasRight(String nameSpace, String actionName,\n\t\t\tHttpServletRequest req, BaseAction baseAction) {\n\t\tif (!ValidateUtils.isValid(nameSpace) || \"/\".equals(nameSpace)) {\n\t\t\tnameSpace = \"\";\n\t\t}\n\t\t// ½«³¬Á´½ÓµÄ²ÎÊý²¿·ÖÂ˵ô ?xxxx\n\t\tif (actionName != null && actionName.contains(\"?\")) {\n\t\t\tactionName = actionName.substring(0, actionName.indexOf(\"?\"));\n\t\t}\n\t\tString url = nameSpace + \"/\" + actionName;\n\t\tHttpSession session = req.getSession();\n\n\t\tServletContext sc = session.getServletContext();\n\t\tMap<String, Right> map = (Map<String, Right>) sc\n\t\t\t\t.getAttribute(\"all_rights_map\");\n\t\tRight r = map.get(url);\n\t\t// ¹«¹²×ÊÔ´?\n\t\tif (r == null || r.isCommon()) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\tAdmin admin = (Admin) session.getAttribute(\"admin\");\n\t\t\t// µÇ½?\n\t\t\tif (admin == null) {\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\t// userAware´¦Àí\n\t\t\t\tif (baseAction != null && baseAction instanceof AdminAware) {\n\t\t\t\t\t((AdminAware) baseAction).setAdmin(admin);\n\t\t\t\t}\n\t\t\t\t// ÓÐȨÏÞ?\n\t\t\t\tif (admin.hasRight(r)) {\n\t\t\t\t\treturn true;\n\t\t\t\t} else {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}" ]
import java.util.HashSet; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cjlu.newspublish.daos.impl.RoleDaoImpl; import com.cjlu.newspublish.models.security.Right; import com.cjlu.newspublish.models.security.Role; import com.cjlu.newspublish.services.RightService; import com.cjlu.newspublish.services.RoleService; import com.cjlu.newspublish.utils.ValidateUtils;
package com.cjlu.newspublish.services.impl; @Service("roleService") public class RoleServiceImpl extends BaseServiceImpl<Role> implements RoleService { @Autowired private RightService rightService; @Autowired private RoleDaoImpl roleDao; /** * ±£´æ»ò¸üнÇÉ« */ @Override public void saveOrUpdateRole(Role model, Integer[] ownRightIds) {
if (!ValidateUtils.isValid(ownRightIds)) {
5
idega/com.idega.documentmanager
src/java/com/idega/documentmanager/component/impl/FormComponentButtonAreaImpl.java
[ "public interface Button extends Component {\n\n\tpublic abstract PropertiesButton getProperties();\n}", "public interface ButtonArea extends Container {\n\n\tpublic abstract Button getButton(ConstButtonType button_type);\n\t\n\tpublic abstract Button addButton(ConstButtonType button_type, String component_after_this_id) throws NullPointerException;\n}", "public enum ConstButtonType {\n\t\n\tPREVIOUS_PAGE_BUTTON {public String toString() { return \"fbc_button_previous\"; }},\n\tNEXT_PAGE_BUTTON {public String toString() { return \"fbc_button_next\"; }},\n\tSUBMIT_FORM_BUTTON {public String toString() { return \"fbc_button_submit\"; }},\n\tSAVE_FORM_BUTTON {public String toString() { return \"fbc_button_save\"; }},\n\tRESET_FORM_BUTTON {public String toString() { return \"fbc_button_reset\"; }};\n\t\n\tpublic static Set<String> getAllTypesInStrings() {\n\t\t\n\t\treturn getAllStringTypesEnumsMappings().keySet();\n\t}\n\t\n\tprivate static Map<String, ConstButtonType> allStringTypesEnumsMappings;\n\t\n\tprivate synchronized static Map<String, ConstButtonType> getAllStringTypesEnumsMappings() {\n\t\t\n\t\tif(allStringTypesEnumsMappings == null) {\n\t\t\t\n\t\t\tallStringTypesEnumsMappings = new HashMap<String, ConstButtonType>();\n\t\t\t\n\t\t\tfor (ConstButtonType type : values())\n\t\t\t\tallStringTypesEnumsMappings.put(type.toString(), type);\n\t\t}\n\t\t\n\t\treturn allStringTypesEnumsMappings;\n\t}\n\t\n\tpublic static ConstButtonType getByStringType(String type) {\n\t\t\n\t\treturn getAllStringTypesEnumsMappings().get(type);\n\t}\n\t\n\tpublic abstract String toString();\n}", "public interface FormComponentButton extends FormComponent {\n\n\tpublic abstract void setSiblingsAndParentPages(FormComponentPage previous, FormComponentPage next);\n\t\n\tpublic abstract void setLastPageId(String last_page_id);\n}", "public interface FormComponentButtonArea extends FormComponentContainer {\n\n\tpublic abstract void setButtonMapping(String button_type, String button_id);\n\t\n\tpublic abstract void setPageSiblings(FormComponentPage previous, FormComponentPage next);\n\t\n\tpublic abstract FormComponentPage getPreviousPage();\n\t\n\tpublic abstract FormComponentPage getNextPage();\n\t\n\tpublic abstract FormComponentPage getCurrentPage();\n\t\n\tpublic abstract void announceLastPage(String last_page_id);\n}", "public interface FormComponentPage extends FormComponentContainer {\n\n\tpublic abstract void setButtonAreaComponentId(String button_area_id);\n\t\n\tpublic abstract void setPageSiblings(FormComponentPage previous, FormComponentPage next);\n\t\n\tpublic abstract void pagesSiblingsChanged();\n\t\n\tpublic abstract FormComponentPage getPreviousPage();\n\t\n\tpublic abstract FormComponentPage getNextPage();\n\t\n\tpublic abstract void announceLastPage(String last_page_id);\n\t\n\tpublic abstract ButtonArea getButtonArea();\n}" ]
import java.util.HashMap; import java.util.Map; import com.idega.documentmanager.business.component.Button; import com.idega.documentmanager.business.component.ButtonArea; import com.idega.documentmanager.business.component.ConstButtonType; import com.idega.documentmanager.component.FormComponentButton; import com.idega.documentmanager.component.FormComponentButtonArea; import com.idega.documentmanager.component.FormComponentPage;
package com.idega.documentmanager.component.impl; /** * @author <a href="mailto:[email protected]">Vytautas Čivilis</a> * @version $Revision: 1.4 $ * * Last modified: $Date: 2008/10/26 16:47:10 $ by $Author: anton $ */ public class FormComponentButtonAreaImpl extends FormComponentContainerImpl implements ButtonArea, FormComponentButtonArea { protected Map<String, String> buttons_type_id_mapping; public Button getButton(ConstButtonType buttonType) { if(buttonType == null) throw new NullPointerException("Button type provided null"); return !getButtonsTypeIdMapping().containsKey(buttonType) ? null : (Button)getContainedComponent(getButtonsTypeIdMapping().get(buttonType)); } public Button addButton(ConstButtonType buttonType, String componentAfterThisId) throws NullPointerException { if(buttonType == null) throw new NullPointerException("Button type provided null"); if(getButtonsTypeIdMapping().containsKey(buttonType)) throw new IllegalArgumentException("Button by type provided: "+buttonType+" already exists in the button area, remove first"); return (Button)addComponent(buttonType.toString(), componentAfterThisId); } protected Map<String, String> getButtonsTypeIdMapping() { if(buttons_type_id_mapping == null) buttons_type_id_mapping = new HashMap<String, String>(); return buttons_type_id_mapping; } @Override public void render() { super.render(); ((FormComponentPage)parent).setButtonAreaComponentId(getId()); } @Override public void remove() { super.remove(); ((FormComponentPage)parent).setButtonAreaComponentId(null); } public void setButtonMapping(String button_type, String button_id) { getButtonsTypeIdMapping().put(button_type, button_id); } public void setPageSiblings(FormComponentPage previous, FormComponentPage next) {
FormComponentButton button = (FormComponentButton)getButton(ConstButtonType.PREVIOUS_PAGE_BUTTON);
3
Kuanghusing/Weather
app/src/main/java/com/kuahusg/weather/Presenter/AboutMePresenterImpl.java
[ "public abstract class BasePresenter implements IBasePresenter {\n\n private IBaseView mView;\n // private IDataSource dataSource;\n private WeakReference<IDataSource> dataSourceWeakReference;\n\n public BasePresenter(IBaseView view) {\n this.mView = view;\n }\n\n public IBaseView getView() {\n return mView;\n }\n\n public boolean hasView() {\n return mView != null;\n }\n\n\n protected abstract IDataSource setDataSource();\n\n public IDataSource getDataSource() {\n if (dataSourceWeakReference.get() == null) {\n getDatasource();\n }\n return dataSourceWeakReference.get();\n }\n\n @Override\n public void init() {\n dataSourceWeakReference = new WeakReference<>(setDataSource());\n }\n\n @Override\n public void onDestroy() {\n mView = null;\n if (dataSourceWeakReference != null) {\n dataSourceWeakReference.clear();\n dataSourceWeakReference = null;\n }\n }\n\n private void getDatasource() {\n this.dataSourceWeakReference = new WeakReference<IDataSource>(new WeatherDataSource(new RemoteForecastDataSource(), new LocalForecastDataSource()));\n }\n\n\n}", "public interface IAboutMePresenter extends IBasePresenter {\n @Override\n void init();\n\n @Override\n void start();\n\n @Override\n void onDestroy();\n\n void onClickFab(Activity activity);\n\n\n}", "public interface IBaseView {\n void init();\n\n void start();\n\n void error(String message);\n\n void finish();\n}", "public interface IAboutMeView extends IBaseView {\n @Override\n void init();\n\n @Override\n void start();\n\n @Override\n void finish();\n\n @Override\n void error(String message);\n\n\n}", "public interface IDataSource {\n void queryWeather(String woeid, RequestWeatherCallback callback);\n\n void queryWeather(RequestWeatherCallback callback);\n\n\n void saveWeather(List<Forecast> forecastList, ForecastInfo info);\n\n void loadAllCity(RequestCityCallback cityCallback);\n\n void saveAllCity(List<String> cityList);\n\n void queryCity(RequestCityResultCallback callback, String cityName);\n\n}" ]
import android.app.Activity; import android.content.Intent; import android.net.Uri; import com.kuahusg.weather.Presenter.base.BasePresenter; import com.kuahusg.weather.Presenter.interfaceOfPresenter.IAboutMePresenter; import com.kuahusg.weather.R; import com.kuahusg.weather.UI.base.IBaseView; import com.kuahusg.weather.UI.interfaceOfView.IAboutMeView; import com.kuahusg.weather.data.IDataSource;
package com.kuahusg.weather.Presenter; /** * Created by kuahusg on 16-9-27. */ public class AboutMePresenterImpl extends BasePresenter implements IAboutMePresenter { private IAboutMeView mView; public AboutMePresenterImpl(IBaseView view) { super(view); mView = (IAboutMeView) view; } @Override public void init() { super.init(); } @Override
protected IDataSource setDataSource() {
4
OlgaKuklina/GitJourney
app/src/main/java/com/oklab/gitjourney/activities/RepositoryActivity.java
[ "public class ReposDataEntry implements Parcelable {\n\n public static final Creator<ReposDataEntry> CREATOR = new Creator<ReposDataEntry>() {\n @Override\n public ReposDataEntry createFromParcel(Parcel in) {\n return new ReposDataEntry(in);\n }\n\n @Override\n public ReposDataEntry[] newArray(int size) {\n return new ReposDataEntry[size];\n }\n };\n private final String title;\n private final String owner;\n private final boolean privacy;\n private final String description;\n private final String language;\n private final int stars;\n private final int forks;\n\n public ReposDataEntry(String title, String ownerName, boolean privacy, String description, String language, int stars, int forks) {\n this.title = title;\n this.owner = ownerName;\n this.privacy = privacy;\n this.description = description;\n this.language = language;\n this.stars = stars;\n this.forks = forks;\n }\n\n protected ReposDataEntry(Parcel in) {\n title = in.readString();\n owner = in.readString();\n privacy = in.readByte() != 0;\n description = in.readString();\n language = in.readString();\n stars = in.readInt();\n forks = in.readInt();\n }\n\n public boolean isPrivate() {\n return privacy;\n }\n\n public String getTitle() {\n return title;\n }\n\n public String getOwner() {\n return owner;\n }\n\n public String getDescription() {\n return description;\n }\n\n public String getLanguage() {\n return language;\n }\n\n public int getStars() {\n return stars;\n }\n\n public int getForks() {\n return forks;\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel parcel, int flags) {\n parcel.writeString(title);\n parcel.writeString(owner);\n parcel.writeInt((byte) (privacy ? 1 : 0));\n parcel.writeString(description);\n parcel.writeString(language);\n parcel.writeInt(stars);\n parcel.writeInt(forks);\n }\n}", "public class UserSessionData {\n\n private final String id;\n private final String credentials;\n private final String token;\n private final String login;\n\n\n public UserSessionData(String id, String credentials, String token, String login) {\n this.id = id;\n this.credentials = credentials;\n this.token = token;\n this.login = login;\n }\n\n public static UserSessionData createUserSessionDataFromString(String data) {\n if (data == null || data.isEmpty()) {\n return null;\n }\n String[] array = data.split(\";\");\n return new UserSessionData(array[0], array[1], array[2], array[3]);\n }\n\n public String getLogin() {\n return login;\n }\n\n public String getId() {\n return id;\n }\n\n public String getCredentials() {\n return credentials;\n }\n\n public String getToken() {\n return token;\n }\n\n @Override\n public String toString() {\n return id + \";\" + credentials + \";\" + token + \";\" + login;\n }\n}", "public class CommitsFragment extends Fragment {\n // TODO: Rename parameter arguments, choose names that match\n // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER\n private static final String ARG_PARAM1 = \"param1\";\n private static final String ARG_PARAM2 = \"param2\";\n\n // TODO: Rename and change types of parameters\n private String mParam1;\n private String mParam2;\n\n private OnFragmentInteractionListener mListener;\n\n public CommitsFragment() {\n // Required empty public constructor\n }\n\n /**\n * Use this factory method to create a new instance of\n * this fragment using the provided parameters.\n *\n * @param param1 Parameter 1.\n * @param param2 Parameter 2.\n * @return A new instance of fragment CodeFragment.\n */\n // TODO: Rename and change types and number of parameters\n public static CommitsFragment newInstance(String param1, String param2) {\n CommitsFragment fragment = new CommitsFragment();\n Bundle args = new Bundle();\n args.putString(ARG_PARAM1, param1);\n args.putString(ARG_PARAM2, param2);\n fragment.setArguments(args);\n return fragment;\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n if (getArguments() != null) {\n mParam1 = getArguments().getString(ARG_PARAM1);\n mParam2 = getArguments().getString(ARG_PARAM2);\n }\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n // Inflate the layout for this fragment\n return inflater.inflate(R.layout.fragment_code, container, false);\n }\n\n // TODO: Rename method, update argument and hook method into UI event\n public void onButtonPressed(Uri uri) {\n if (mListener != null) {\n mListener.onFragmentInteraction(uri);\n }\n }\n\n @Override\n public void onAttach(Context context) {\n super.onAttach(context);\n if (context instanceof OnFragmentInteractionListener) {\n mListener = (OnFragmentInteractionListener) context;\n } else {\n throw new RuntimeException(context.toString()\n + \" must implement OnFragmentInteractionListener\");\n }\n }\n\n @Override\n public void onDetach() {\n super.onDetach();\n mListener = null;\n }\n\n /**\n * This interface must be implemented by activities that contain this\n * fragment to allow an interaction in this fragment to be communicated\n * to the activity and potentially other fragments contained in that\n * activity.\n * <p>\n * See the Android Training lesson <a href=\n * \"http://developer.android.com/training/basics/fragments/communicating.html\"\n * >Communicating with Other Fragments</a> for more information.\n */\n public interface OnFragmentInteractionListener {\n // TODO: Update argument type and name\n void onFragmentInteraction(Uri uri);\n }\n}", "public class ContributorsFragment extends Fragment {\n\n // TODO: Customize parameter argument names\n private static final String ARG_COLUMN_COUNT = \"column-count\";\n // TODO: Customize parameters\n private int mColumnCount = 1;\n private OnListFragmentInteractionListener mListener;\n\n /**\n * Mandatory empty constructor for the fragment manager to instantiate the\n * fragment (e.g. upon screen orientation changes).\n */\n public ContributorsFragment() {\n }\n\n // TODO: Customize parameter initialization\n @SuppressWarnings(\"unused\")\n public static ContributorsFragment newInstance(int columnCount) {\n ContributorsFragment fragment = new ContributorsFragment();\n Bundle args = new Bundle();\n args.putInt(ARG_COLUMN_COUNT, columnCount);\n fragment.setArguments(args);\n return fragment;\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n if (getArguments() != null) {\n mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);\n }\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n View view = inflater.inflate(R.layout.fragment_contributors_item_list, container, false);\n\n // Set the adapter\n if (view instanceof RecyclerView) {\n Context context = view.getContext();\n RecyclerView recyclerView = (RecyclerView) view;\n if (mColumnCount <= 1) {\n recyclerView.setLayoutManager(new LinearLayoutManager(context));\n } else {\n recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));\n }\n recyclerView.setAdapter(new ContributorsItemRecyclerViewAdapter(new ArrayList<String>(), mListener));\n }\n return view;\n }\n\n\n @Override\n public void onAttach(Context context) {\n super.onAttach(context);\n if (context instanceof OnListFragmentInteractionListener) {\n mListener = (OnListFragmentInteractionListener) context;\n } else {\n throw new RuntimeException(context.toString()\n + \" must implement OnListFragmentInteractionListener\");\n }\n }\n\n @Override\n public void onDetach() {\n super.onDetach();\n mListener = null;\n }\n\n /**\n * This interface must be implemented by activities that contain this\n * fragment to allow an interaction in this fragment to be communicated\n * to the activity and potentially other fragments contained in that\n * activity.\n * <p/>\n * See the Android Training lesson <a href=\n * \"http://developer.android.com/training/basics/fragments/communicating.html\"\n * >Communicating with Other Fragments</a> for more information.\n */\n public interface OnListFragmentInteractionListener {\n // TODO: Update argument type and name\n void onListFragmentInteraction(String item);\n }\n}", "public class EventsFragment extends Fragment {\n private static final String TAG = com.oklab.gitjourney.fragments.EventsFragment.class.getSimpleName();\n private static final String ARG_PARAM1 = \"param1\";\n private static final String ARG_PARAM2 = \"param2\";\n private WebView mv;\n // TODO: Rename and change types of parameters\n private String mParam1;\n private String mParam2;\n\n private com.oklab.gitjourney.fragments.CommitsFragment.OnFragmentInteractionListener mListener;\n\n public EventsFragment() {\n // Required empty public constructor\n }\n\n /**\n * Use this factory method to create a new instance of\n * this fragment using the provided parameters.\n *\n * @param param1 Parameter 1.\n * @param param2 Parameter 2.\n * @return A new instance of fragment CodeFragment.\n */\n // TODO: Rename and change types and number of parameters\n public static com.oklab.gitjourney.fragments.CommitsFragment newInstance(String param1, String param2) {\n com.oklab.gitjourney.fragments.CommitsFragment fragment = new com.oklab.gitjourney.fragments.CommitsFragment();\n Bundle args = new Bundle();\n args.putString(ARG_PARAM1, param1);\n args.putString(ARG_PARAM2, param2);\n fragment.setArguments(args);\n return fragment;\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n if (getArguments() != null) {\n mParam1 = getArguments().getString(ARG_PARAM1);\n mParam2 = getArguments().getString(ARG_PARAM2);\n }\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n // Inflate the layout for this fragment\n return inflater.inflate(R.layout.fragment_code, container, false);\n }\n\n // TODO: Rename method, update argument and hook method into UI event\n public void onButtonPressed(Uri uri) {\n if (mListener != null) {\n mListener.onFragmentInteraction(uri);\n }\n }\n\n @Override\n public void onAttach(Context context) {\n super.onAttach(context);\n if (context instanceof com.oklab.gitjourney.fragments.CommitsFragment.OnFragmentInteractionListener) {\n mListener = (com.oklab.gitjourney.fragments.CommitsFragment.OnFragmentInteractionListener) context;\n } else {\n throw new RuntimeException(context.toString()\n + \" must implement OnFragmentInteractionListener\");\n }\n }\n\n @Override\n public void onDetach() {\n super.onDetach();\n mListener = null;\n }\n\n /**\n * This interface must be implemented by activities that contain this\n * fragment to allow an interaction in this fragment to be communicated\n * to the activity and potentially other fragments contained in that\n * activity.\n * <p>\n * See the Android Training lesson <a href=\n * \"http://developer.android.com/training/basics/fragments/communicating.html\"\n * >Communicating with Other Fragments</a> for more information.\n */\n public interface OnFragmentInteractionListener {\n // TODO: Update argument type and name\n void onFragmentInteraction(Uri uri);\n }\n}", "public class TakeScreenshotService {\n\n private static final String TAG = TakeScreenshotService.class.getSimpleName();\n private final Activity activity;\n\n public TakeScreenshotService(Activity activity) {\n this.activity = activity;\n }\n\n public void takeScreenShot() {\n View v1 = activity.getWindow().getDecorView().getRootView();\n v1.setDrawingCacheEnabled(true);\n Bitmap myBitmap = v1.getDrawingCache();\n String filePath = saveBitmap(myBitmap);\n v1.setDrawingCacheEnabled(false);\n if (filePath != null) {\n sendMail(filePath);\n }\n }\n\n private String saveBitmap(Bitmap bitmap) {\n Utils.verifyStoragePermissions(activity);\n String filePath = Environment.getExternalStorageDirectory()\n + File.separator + activity.getString(R.string.local_path);\n File imagePath = new File(filePath);\n FileOutputStream stream;\n try {\n stream = new FileOutputStream(imagePath);\n bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);\n stream.flush();\n stream.close();\n return filePath;\n } catch (IOException e) {\n Log.e(TAG, \"\", e);\n return null;\n }\n }\n\n private void sendMail(String path) {\n Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);\n emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,\n activity.getString(R.string.screenshot_msg_title));\n emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,\n activity.getString(R.string.screenshot_msg_extra_text));\n emailIntent.setType(activity.getString(R.string.content_type));\n Uri myUri = Uri.parse(activity.getString(R.string.content_path) + path);\n emailIntent.putExtra(Intent.EXTRA_STREAM, myUri);\n activity.startActivity(Intent.createChooser(emailIntent, activity.getString(R.string.screenshot_msg_desc)));\n }\n}", "public class GithubLanguageColorsMatcher {\n private static final String TAG = GithubLanguageColorsMatcher.class.getSimpleName();\n private static final HashMap<Character, String> MAP = new HashMap<>();\n\n static {\n MAP.put(' ', \"\");\n MAP.put('\\'', \"Diez\");\n MAP.put('+', \"Plus\");\n MAP.put('-', \"\");\n MAP.put('_', \"\");\n }\n\n public static int findMatchedColor(Context context, String language) {\n int id = context.getResources().getIdentifier(language, \"color\", \"com.oklab.githubjourney\");\n if (id != 0) {\n return id;\n }\n StringBuilder builder = new StringBuilder();\n\n for (int i = 0; i < language.length(); i++) {\n char a = language.charAt(i);\n if (MAP.containsKey(a)) {\n builder.append(MAP.get(a));\n } else {\n builder.append(a);\n }\n }\n Log.v(TAG, \"language = \" + language);\n Log.v(TAG, \"builder = \" + builder.toString());\n\n id = context.getResources().getIdentifier(builder.toString(), \"color\", \"com.oklab.gitjourney\");\n Log.v(TAG, \"id = \" + id);\n return id;\n }\n}", "public final class Utils {\n public static final String SHARED_PREF_NAME = \"com.ok.lab.GitJourney\";\n public static final String DMY_DATE_FORMAT_PATTERN = \"dd-MM-yyyy\";\n private static final int REQUEST_EXTERNAL_STORAGE = 1;\n private static String[] PERMISSIONS_STORAGE = {\n Manifest.permission.READ_EXTERNAL_STORAGE,\n Manifest.permission.WRITE_EXTERNAL_STORAGE\n };\n\n private Utils() {\n\n }\n\n public static void verifyStoragePermissions(Activity activity) {\n // Check if we have write permission\n int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);\n Log.e(\"TAG\", \"verifyStoragePermissions\");\n if (permission != PackageManager.PERMISSION_GRANTED) {\n // We don't have permission so prompt the user\n ActivityCompat.requestPermissions(\n activity,\n PERMISSIONS_STORAGE,\n REQUEST_EXTERNAL_STORAGE\n );\n }\n }\n\n public static DateFormat createDateFormatterWithTimeZone(Context context, String pattern) {\n SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);\n boolean timeZone = sharedPref.getBoolean(\"timezone_switch\", true);\n SimpleDateFormat formatter = new SimpleDateFormat(pattern, Locale.getDefault());\n if (timeZone) {\n formatter.setTimeZone(TimeZone.getDefault());\n } else {\n String customTimeZone = sharedPref.getString(\"timezone_list\", TimeZone.getDefault().getID());\n formatter.setTimeZone(TimeZone.getTimeZone(customTimeZone));\n }\n return formatter;\n }\n\n public static String getStackTrace(Exception e) {\n StringWriter writer = new StringWriter();\n PrintWriter printer = new PrintWriter(writer);\n e.printStackTrace(printer);\n printer.close();\n return writer.toString();\n }\n}" ]
import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.webkit.WebViewClient; import com.oklab.gitjourney.R; import com.oklab.gitjourney.asynctasks.RepoReadmeDownloadAsyncTask; import com.oklab.gitjourney.data.ReposDataEntry; import com.oklab.gitjourney.data.UserSessionData; import com.oklab.gitjourney.fragments.CommitsFragment; import com.oklab.gitjourney.fragments.ContributorsFragment; import com.oklab.gitjourney.fragments.EventsFragment; import com.oklab.gitjourney.fragments.IssuesFragment; import com.oklab.gitjourney.fragments.ReadmeFragment; import com.oklab.gitjourney.fragments.RepositoryContentListFragment; import com.oklab.gitjourney.services.TakeScreenshotService; import com.oklab.gitjourney.utils.GithubLanguageColorsMatcher; import com.oklab.gitjourney.utils.Utils; import org.markdownj.MarkdownProcessor;
package com.oklab.gitjourney.activities; public class RepositoryActivity extends AppCompatActivity implements RepoReadmeDownloadAsyncTask.OnRepoReadmeContentLoadedListener , RepositoryContentListFragment.RepoContentFragmentInteractionListener , CommitsFragment.OnFragmentInteractionListener , ContributorsFragment.OnListFragmentInteractionListener { private static final String TAG = RepositoryActivity.class.getSimpleName(); private WebView mv; private String owner = ""; private String title = ""; private UserSessionData currentSessionData; private TakeScreenshotService takeScreenshotService; private RepositoryContentListFragment repoContentListFragment; private ViewPager mViewPager; private RepositoryActivity.SectionsPagerAdapter mSectionsPagerAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_repository); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); ReposDataEntry entry = getIntent().getParcelableExtra("repo"); title = entry.getTitle(); toolbar.setTitleMarginBottom(3); toolbar.setTitle(title); mSectionsPagerAdapter = new RepositoryActivity.SectionsPagerAdapter(getSupportFragmentManager()); mViewPager = (ViewPager) findViewById(R.id.repo_view_pager); mViewPager.setAdapter(mSectionsPagerAdapter); mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { Log.v(TAG, "onPageSelected, position = " + position); } @Override public void onPageScrollStateChanged(int state) { } }); mViewPager.setOffscreenPageLimit(4); TabLayout tabLayout = (TabLayout) findViewById(R.id.repo_tabs); tabLayout.setupWithViewPager(mViewPager); if (entry.getLanguage() != null && !entry.getLanguage().isEmpty() && !entry.getLanguage().equals("null")) { Log.v(TAG, " data.getLanguage() = " + entry.getLanguage()); int colorId = GithubLanguageColorsMatcher.findMatchedColor(this, entry.getLanguage()); Log.v(TAG, " colorId = " + colorId); if (colorId != 0) { toolbar.setBackgroundColor(this.getResources().getColor(colorId)); } } setSupportActionBar(toolbar); if (entry.getOwner() == null || entry.getOwner().isEmpty()) {
SharedPreferences prefs = this.getSharedPreferences(Utils.SHARED_PREF_NAME, 0);
7
Wisebite/wisebite_android
app/src/main/java/dev/wisebite/wisebite/adapter/OrderItemMenuAdapter.java
[ "@Getter\n@Setter\n@AllArgsConstructor(suppressConstructorProperties = true)\n@NoArgsConstructor\n@ToString\n@Builder\npublic class Dish implements Entity {\n\n private String id;\n private String name;\n private Double price;\n private String description;\n\n private Map<String, Object> reviews = new LinkedHashMap<>();\n\n\n @Override\n public String getId() {\n return id;\n }\n\n @Override\n public void setId(String id) {\n this.id = id;\n }\n\n}", "@Getter\n@Setter\n@AllArgsConstructor(suppressConstructorProperties = true)\n@NoArgsConstructor\n@ToString\n@Builder\npublic class Menu implements Entity {\n\n private String id;\n private String name;\n private Double price;\n private String description;\n\n private Map<String, Object> mainDishes = new LinkedHashMap<>();\n private Map<String, Object> secondaryDishes = new LinkedHashMap<>();\n private Map<String, Object> otherDishes = new LinkedHashMap<>();\n private Map<String, Object> reviews = new LinkedHashMap<>();\n\n @Override\n public String getId() {\n return id;\n }\n\n @Override\n public void setId(String id) {\n this.id = id;\n }\n\n}", "public class DishService extends Service<Dish> {\n\n public DishService(Repository<Dish> repository) {\n super(repository);\n }\n\n public ArrayList<Dish> parseDishMapToDishModel(Map<String, Object> dishesMap) {\n ArrayList<Dish> dishes = new ArrayList<>();\n if (dishesMap != null) {\n for (String dishKey : dishesMap.keySet()) {\n dishes.add(repository.get(dishKey));\n }\n }\n return dishes;\n }\n\n public String getName(OrderItem orderItem) {\n return repository.get(orderItem.getDishId()).getName();\n }\n\n}", "public final class ServiceFactory {\n\n private static DishService dishService;\n private static ImageService imageService;\n private static MenuService menuService;\n private static OpenTimeService openTimeService;\n private static OrderItemService orderItemService;\n private static OrderService orderService;\n private static RestaurantService restaurantService;\n private static ReviewService reviewService;\n private static UserService userService;\n\n public static DishService getDishService(Context context){\n if (dishService == null)\n dishService = new DishService(\n new DishRepository(context));\n return dishService;\n }\n\n public static ImageService getImageService(Context context){\n if (imageService == null)\n imageService = new ImageService(\n new ImageRepository(context));\n return imageService;\n }\n\n public static MenuService getMenuService(Context context){\n if (menuService == null)\n menuService = new MenuService(\n new MenuRepository(context),\n new DishRepository(context));\n return menuService;\n }\n\n public static OpenTimeService getOpenTimeService(Context context){\n if (openTimeService == null)\n openTimeService = new OpenTimeService(\n new OpenTimeRepository(context));\n return openTimeService;\n }\n\n public static OrderItemService getOrderItemService(Context context){\n if (orderItemService == null)\n orderItemService = new OrderItemService(\n new OrderItemRepository(context),\n new DishRepository(context),\n new MenuRepository(context));\n return orderItemService;\n }\n\n public static OrderService getOrderService(Context context){\n if (orderService == null)\n orderService = new OrderService(\n new OrderRepository(context),\n new OrderItemRepository(context),\n new DishRepository(context),\n new MenuRepository(context),\n new RestaurantRepository(context),\n new UserRepository(context));\n return orderService;\n }\n\n public static RestaurantService getRestaurantService(Context context){\n if (restaurantService == null)\n restaurantService = new RestaurantService(\n new RestaurantRepository(context),\n new MenuRepository(context),\n new DishRepository(context),\n new ImageRepository(context),\n new OpenTimeRepository(context),\n new OrderRepository(context),\n new OrderItemRepository(context),\n new UserRepository(context),\n new ReviewRepository(context));\n return restaurantService;\n }\n\n public static ReviewService getReviewService(Context context) {\n if (reviewService == null) {\n reviewService = new ReviewService(\n new ReviewRepository(context),\n new RestaurantRepository(context),\n new DishRepository(context),\n new MenuRepository(context),\n new UserRepository(context));\n }\n return reviewService;\n }\n\n public static UserService getUserService(Context context){\n if (userService == null)\n userService = new UserService(\n new UserRepository(context),\n new ImageRepository(context),\n new RestaurantRepository(context),\n new OrderRepository(context),\n new OrderItemRepository(context));\n return userService;\n }\n\n public static Integer getServiceCount() {\n return 9;\n }\n}", "public class Utils {\n\n private static Menu tempMenu;\n private static Date tempDate;\n private static Integer loaded = 0;\n\n @SuppressWarnings(\"deprecation\")\n public static String parseStartEndDate(TimePicker firstTimePicker, TimePicker secondTimePicker) {\n int firstHour, firstMinute, secondHour, secondMinute;\n\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n firstHour = firstTimePicker.getHour();\n firstMinute = firstTimePicker.getMinute();\n secondHour = secondTimePicker.getHour();\n secondMinute = secondTimePicker.getMinute();\n } else {\n firstHour = firstTimePicker.getCurrentHour();\n firstMinute = firstTimePicker.getCurrentMinute();\n secondHour = secondTimePicker.getCurrentHour();\n secondMinute = secondTimePicker.getCurrentMinute();\n }\n\n return datesToString(firstHour, firstMinute, secondHour, secondMinute);\n }\n\n public static String parseStartEndDate(Date startDate, Date endDate) {\n int firstHour, firstMinute, secondHour, secondMinute;\n\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(startDate);\n firstHour = calendar.get(Calendar.HOUR_OF_DAY);\n firstMinute = calendar.get(Calendar.MINUTE);\n\n calendar.setTime(endDate);\n secondHour = calendar.get(Calendar.HOUR_OF_DAY);\n secondMinute = calendar.get(Calendar.MINUTE);\n\n return datesToString(firstHour, firstMinute, secondHour, secondMinute);\n }\n\n @SuppressWarnings(\"deprecation\")\n public static OpenTime createOpenTimeByTimePicker(TimePicker firstTimePicker, TimePicker secondTimePicker, Integer viewId) {\n int dayOfTheWeek = parseViewIdToDayOfWeek(viewId);\n\n Calendar startCalendar = Calendar.getInstance();\n startCalendar.setTimeInMillis(0);\n startCalendar.set(Calendar.DAY_OF_WEEK, dayOfTheWeek);\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n startCalendar.set(Calendar.HOUR_OF_DAY, firstTimePicker.getHour());\n startCalendar.set(Calendar.MINUTE, firstTimePicker.getMinute());\n } else {\n startCalendar.set(Calendar.HOUR_OF_DAY, firstTimePicker.getCurrentHour());\n startCalendar.set(Calendar.MINUTE, firstTimePicker.getCurrentMinute());\n }\n\n\n Calendar endCalendar = Calendar.getInstance();\n endCalendar.setTimeInMillis(0);\n endCalendar.set(Calendar.DAY_OF_WEEK, dayOfTheWeek);\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n endCalendar.set(Calendar.HOUR_OF_DAY, secondTimePicker.getHour());\n endCalendar.set(Calendar.MINUTE, secondTimePicker.getMinute());\n } else {\n endCalendar.set(Calendar.HOUR_OF_DAY, secondTimePicker.getCurrentHour());\n endCalendar.set(Calendar.MINUTE, secondTimePicker.getCurrentMinute());\n }\n\n return OpenTime.builder()\n .startDate(startCalendar.getTime())\n .endDate(endCalendar.getTime())\n .build();\n }\n\n public static void setTempMenu(Menu menu) {\n tempMenu = menu;\n }\n\n public static Menu getTempMenu() {\n return tempMenu;\n }\n\n public static Integer getLoaded() { return loaded; }\n\n public static void increaseLoaded() { ++loaded; }\n\n public static String toStringWithTwoDecimals(double d) {\n d = Math.round(d * 100);\n d = d/100;\n return String.valueOf(d);\n }\n\n public static String getHour(Date date) {\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(date);\n\n int hour = calendar.get(Calendar.HOUR_OF_DAY);\n int minute = calendar.get(Calendar.MINUTE);\n\n String result = \"\";\n if (hour < 10) result += '0';\n result += String.valueOf(hour) + ':';\n if (minute < 10) result += '0';\n result += String.valueOf(minute);\n\n return result;\n }\n\n private static String datesToString(int firstHour, int firstMinute, int secondHour, int secondMinute) {\n String parsed = \"\";\n if (firstHour < 10) parsed += '0';\n parsed += String.valueOf(firstHour) + ':';\n if (firstMinute < 10) parsed += '0';\n parsed += String.valueOf(firstMinute);\n\n parsed += \" - \";\n\n if (secondHour < 10) parsed += '0';\n parsed += String.valueOf(secondHour) + ':';\n if (secondMinute < 10) parsed += '0';\n parsed += String.valueOf(secondMinute);\n return parsed;\n }\n\n public static int parseViewIdToDayOfWeek(Integer viewId) {\n switch (viewId) {\n case R.id.monday_date_picker:\n return Calendar.MONDAY;\n case R.id.tuesday_date_picker:\n return Calendar.TUESDAY;\n case R.id.wednesday_date_picker:\n return Calendar.WEDNESDAY;\n case R.id.thursday_date_picker:\n return Calendar.THURSDAY;\n case R.id.friday_date_picker:\n return Calendar.FRIDAY;\n case R.id.saturday_date_picker:\n return Calendar.SATURDAY;\n case R.id.sunday_date_picker:\n return Calendar.SUNDAY;\n default:\n return 0;\n }\n }\n\n public static String skipAts(String email) {\n return email.replaceAll(\"\\\\.\", \"@\");\n }\n\n public static boolean isEmpty(String str) {\n return str == null || str.trim().isEmpty();\n }\n\n public static void setAnalyticsDate(Date date) {\n tempDate = date;\n }\n\n public static Date getAnalyticsDate() {\n return tempDate;\n }\n}" ]
import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.support.design.widget.Snackbar; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Map; import dev.wisebite.wisebite.R; import dev.wisebite.wisebite.domain.Dish; import dev.wisebite.wisebite.domain.Menu; import dev.wisebite.wisebite.service.DishService; import dev.wisebite.wisebite.service.ServiceFactory; import dev.wisebite.wisebite.utils.Utils;
package dev.wisebite.wisebite.adapter; /** * Created by albert on 20/03/17. * @author albert */ public class OrderItemMenuAdapter extends RecyclerView.Adapter<OrderItemMenuAdapter.OrderItemMenuHolder> { private ArrayList<Menu> menus; private ArrayList<Menu> selectedMenus; private TextView totalPriceView; private Context context; private ArrayList<Dish> mainDishSelected, secondaryDishSelected, otherDishSelected; private LayoutInflater inflater; private DishService dishService; public OrderItemMenuAdapter(ArrayList<Menu> menus, TextView totalPriceView, ArrayList<Menu> selectedMenus, Context context) { this.menus = menus; this.totalPriceView = totalPriceView; this.selectedMenus = selectedMenus; this.context = context; this.inflater = LayoutInflater.from(context);
this.dishService = ServiceFactory.getDishService(context);
3
Nilhcem/droidcontn-2016
app/src/main/java/com/nilhcem/droidcontn/data/app/AppMapper.java
[ "public class Schedule extends ArrayList<ScheduleDay> implements Parcelable {\n\n public static final Parcelable.Creator<Schedule> CREATOR = new Parcelable.Creator<Schedule>() {\n public Schedule createFromParcel(Parcel source) {\n return new Schedule(source);\n }\n\n public Schedule[] newArray(int size) {\n return new Schedule[size];\n }\n };\n\n public Schedule() {\n }\n\n protected Schedule(Parcel in) {\n addAll(in.createTypedArrayList(ScheduleDay.CREATOR));\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeTypedList(this);\n }\n}", "@Value\npublic class ScheduleDay implements Parcelable {\n\n public static final Parcelable.Creator<ScheduleDay> CREATOR = new Parcelable.Creator<ScheduleDay>() {\n public ScheduleDay createFromParcel(Parcel source) {\n return new ScheduleDay(source);\n }\n\n public ScheduleDay[] newArray(int size) {\n return new ScheduleDay[size];\n }\n };\n\n LocalDate day;\n List<ScheduleSlot> slots;\n\n public ScheduleDay(LocalDate day, List<ScheduleSlot> slots) {\n this.day = day;\n this.slots = slots;\n }\n\n protected ScheduleDay(Parcel in) {\n day = (LocalDate) in.readSerializable();\n slots = in.createTypedArrayList(ScheduleSlot.CREATOR);\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeSerializable(day);\n dest.writeTypedList(slots);\n }\n}", "@Value\npublic class ScheduleSlot implements Parcelable {\n\n public static final Parcelable.Creator<ScheduleSlot> CREATOR = new Parcelable.Creator<ScheduleSlot>() {\n public ScheduleSlot createFromParcel(Parcel source) {\n return new ScheduleSlot(source);\n }\n\n public ScheduleSlot[] newArray(int size) {\n return new ScheduleSlot[size];\n }\n };\n\n LocalDateTime time;\n List<Session> sessions;\n\n public ScheduleSlot(LocalDateTime time, List<Session> sessions) {\n this.time = time;\n this.sessions = sessions;\n }\n\n protected ScheduleSlot(Parcel in) {\n time = (LocalDateTime) in.readSerializable();\n sessions = in.createTypedArrayList(Session.CREATOR);\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeSerializable(time);\n dest.writeTypedList(sessions);\n }\n}", "@Value\npublic class Session implements Parcelable {\n\n public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() {\n public Session createFromParcel(Parcel source) {\n return new Session(source);\n }\n\n public Session[] newArray(int size) {\n return new Session[size];\n }\n };\n\n int id;\n String room;\n List<Speaker> speakers;\n String title;\n String description;\n LocalDateTime fromTime;\n LocalDateTime toTime;\n\n public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) {\n this.id = id;\n this.room = room;\n this.speakers = speakers;\n this.title = title;\n this.description = description;\n this.fromTime = fromTime;\n this.toTime = toTime;\n }\n\n protected Session(Parcel in) {\n id = in.readInt();\n room = in.readString();\n speakers = in.createTypedArrayList(Speaker.CREATOR);\n title = in.readString();\n description = in.readString();\n fromTime = (LocalDateTime) in.readSerializable();\n toTime = (LocalDateTime) in.readSerializable();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeInt(id);\n dest.writeString(room);\n dest.writeTypedList(speakers);\n dest.writeString(title);\n dest.writeString(description);\n dest.writeSerializable(fromTime);\n dest.writeSerializable(toTime);\n }\n}", "@Value\npublic class Speaker implements Parcelable {\n\n public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() {\n public Speaker createFromParcel(Parcel source) {\n return new Speaker(source);\n }\n\n public Speaker[] newArray(int size) {\n return new Speaker[size];\n }\n };\n\n int id;\n String name;\n String title;\n String bio;\n String website;\n String twitter;\n String github;\n String photo;\n\n public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) {\n this.id = id;\n this.name = name;\n this.title = title;\n this.bio = bio;\n this.website = website;\n this.twitter = twitter;\n this.github = github;\n this.photo = photo;\n }\n\n protected Speaker(Parcel in) {\n id = in.readInt();\n name = in.readString();\n title = in.readString();\n bio = in.readString();\n website = in.readString();\n twitter = in.readString();\n github = in.readString();\n photo = in.readString();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeInt(id);\n dest.writeString(name);\n dest.writeString(title);\n dest.writeString(bio);\n dest.writeString(website);\n dest.writeString(twitter);\n dest.writeString(github);\n dest.writeString(photo);\n }\n}" ]
import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.nilhcem.droidcontn.data.app.model.Schedule; import com.nilhcem.droidcontn.data.app.model.ScheduleDay; import com.nilhcem.droidcontn.data.app.model.ScheduleSlot; import com.nilhcem.droidcontn.data.app.model.Session; import com.nilhcem.droidcontn.data.app.model.Speaker; import org.threeten.bp.LocalDate; import org.threeten.bp.LocalDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import javax.inject.Inject; import java8.util.stream.Collectors; import static java8.util.stream.StreamSupport.stream;
package com.nilhcem.droidcontn.data.app; public class AppMapper { @Inject public AppMapper() { } public Map<Integer, Speaker> speakersToMap(@NonNull List<Speaker> from) { return stream(from).collect(Collectors.toMap(Speaker::getId, speaker -> speaker)); } public List<Speaker> toSpeakersList(@Nullable List<Integer> speakerIds, @NonNull Map<Integer, Speaker> speakersMap) { if (speakerIds == null) { return null; } return stream(speakerIds).map(speakersMap::get).collect(Collectors.toList()); } public List<Integer> toSpeakersIds(@Nullable List<Speaker> speakers) { if (speakers == null) { return null; } return stream(speakers).map(Speaker::getId).collect(Collectors.toList()); }
public Schedule toSchedule(@NonNull List<Session> sessions) {
3
underhilllabs/dccsched
src/com/underhilllabs/dccsched/ui/BlocksActivity.java
[ "public static class Blocks implements BlocksColumns, BaseColumns {\n public static final Uri CONTENT_URI =\n BASE_CONTENT_URI.buildUpon().appendPath(PATH_BLOCKS).build();\n\n public static final String CONTENT_TYPE =\n \"vnd.android.cursor.dir/vnd.dccsched.block\";\n public static final String CONTENT_ITEM_TYPE =\n \"vnd.android.cursor.item/vnd.dccsched.block\";\n\n /** Count of {@link Sessions} inside given block. */\n public static final String SESSIONS_COUNT = \"sessions_count\";\n\n /**\n * Flag indicating that at least one {@link Sessions#SESSION_ID} inside\n * this block has {@link Sessions#STARRED} set.\n */\n public static final String CONTAINS_STARRED = \"contains_starred\";\n\n /** Default \"ORDER BY\" clause. */\n public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + \" ASC, \"\n + BlocksColumns.BLOCK_END + \" ASC\";\n\n /** Build {@link Uri} for requested {@link #BLOCK_ID}. */\n public static Uri buildBlockUri(String blockId) {\n return CONTENT_URI.buildUpon().appendPath(blockId).build();\n }\n\n /**\n * Build {@link Uri} that references any {@link Sessions} associated\n * with the requested {@link #BLOCK_ID}.\n */\n public static Uri buildSessionsUri(String blockId) {\n return CONTENT_URI.buildUpon().appendPath(blockId).appendPath(PATH_SESSIONS).build();\n }\n\n /**\n * Build {@link Uri} that references any {@link Blocks} that occur\n * between the requested time boundaries.\n */\n public static Uri buildBlocksBetweenDirUri(long startTime, long endTime) {\n return CONTENT_URI.buildUpon().appendPath(PATH_BETWEEN).appendPath(\n String.valueOf(startTime)).appendPath(String.valueOf(endTime)).build();\n }\n\n /** Read {@link #BLOCK_ID} from {@link Blocks} {@link Uri}. */\n public static String getBlockId(Uri uri) {\n return uri.getPathSegments().get(1);\n }\n\n /**\n * Generate a {@link #BLOCK_ID} that will always match the requested\n * {@link Blocks} details.\n */\n public static String generateBlockId(long startTime, long endTime) {\n startTime /= DateUtils.SECOND_IN_MILLIS;\n endTime /= DateUtils.SECOND_IN_MILLIS;\n return ParserUtils.sanitizeId(startTime + \"-\" + endTime);\n }\n}", "public class BlockView extends Button {\n private final String mBlockId;\n private final String mTitle;\n private final long mStartTime;\n private final long mEndTime;\n private final boolean mContainsStarred;\n private final int mColumn;\n\n public BlockView(Context context, String blockId, String title, long startTime,\n long endTime, boolean containsStarred, int column) {\n super(context);\n\n mBlockId = blockId;\n mTitle = title;\n mStartTime = startTime;\n mEndTime = endTime;\n mContainsStarred = containsStarred;\n mColumn = column;\n\n setText(mTitle);\n\n // TODO: turn into color state list with layers?\n int textColor = -1;\n int accentColor = -1;\n switch (mColumn) {\n case 0:\n // blue\n textColor = Color.WHITE;\n accentColor = Color.parseColor(\"#18b6e6\");\n break;\n case 1:\n // red\n textColor = Color.WHITE;\n accentColor = Color.parseColor(\"#df1831\");\n break;\n case 2:\n // green\n textColor = Color.WHITE;\n accentColor = Color.parseColor(\"#00a549\");\n break;\n }\n\n LayerDrawable buttonDrawable = (LayerDrawable)\n context.getResources().getDrawable(R.drawable.btn_block);\n buttonDrawable.getDrawable(0).setColorFilter(accentColor, PorterDuff.Mode.SRC_ATOP);\n buttonDrawable.getDrawable(1).setAlpha(mContainsStarred ? 255 : 0);\n\n setTextColor(textColor);\n setBackgroundDrawable(buttonDrawable);\n }\n\n public String getBlockId() {\n return mBlockId;\n }\n\n public long getStartTime() {\n return mStartTime;\n }\n\n public long getEndTime() {\n return mEndTime;\n }\n\n public int getColumn() {\n return mColumn;\n }\n}", "public class BlocksLayout extends ViewGroup {\n private int mColumns = 3;\n\n private TimeRulerView mRulerView;\n private View mNowView;\n\n public BlocksLayout(Context context) {\n this(context, null);\n }\n\n public BlocksLayout(Context context, AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public BlocksLayout(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n\n final TypedArray a = context.obtainStyledAttributes(attrs,\n R.styleable.BlocksLayout, defStyle, 0);\n\n mColumns = a.getInt(R.styleable.TimeRulerView_headerWidth, mColumns);\n\n a.recycle();\n }\n\n private void ensureChildren() {\n mRulerView = (TimeRulerView) findViewById(R.id.blocks_ruler);\n mRulerView.setDrawingCacheEnabled(true);\n if (mRulerView == null) {\n throw new IllegalStateException(\"Must include a R.id.blocks_ruler view.\");\n }\n\n mNowView = findViewById(R.id.blocks_now);\n mNowView.setDrawingCacheEnabled(true);\n if (mNowView == null) {\n throw new IllegalStateException(\"Must include a R.id.blocks_now view.\");\n }\n }\n\n /**\n * Remove any {@link BlockView} instances, leaving only\n * {@link TimeRulerView} remaining.\n */\n public void removeAllBlocks() {\n ensureChildren();\n removeAllViews();\n addView(mRulerView);\n addView(mNowView);\n }\n\n public void addBlock(BlockView blockView) {\n blockView.setDrawingCacheEnabled(true);\n addView(blockView, 1);\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n ensureChildren();\n\n mRulerView.measure(widthMeasureSpec, heightMeasureSpec);\n mNowView.measure(widthMeasureSpec, heightMeasureSpec);\n\n final int width = mRulerView.getMeasuredWidth();\n final int height = mRulerView.getMeasuredHeight();\n\n setMeasuredDimension(resolveSize(width, widthMeasureSpec),\n resolveSize(height, heightMeasureSpec));\n }\n\n @Override\n protected void onLayout(boolean changed, int l, int t, int r, int b) {\n ensureChildren();\n\n final TimeRulerView rulerView = mRulerView;\n final int headerWidth = rulerView.getHeaderWidth();\n final int columnWidth = (getWidth() - headerWidth) / mColumns;\n\n rulerView.layout(0, 0, getWidth(), getHeight());\n\n final int count = getChildCount();\n for (int i = 0; i < count; i++) {\n final View child = getChildAt(i);\n if (child.getVisibility() == GONE) continue;\n\n if (child instanceof BlockView) {\n final BlockView blockView = (BlockView) child;\n final int top = rulerView.getTimeVerticalOffset(blockView.getStartTime());\n final int bottom = rulerView.getTimeVerticalOffset(blockView.getEndTime());\n final int left = headerWidth + (blockView.getColumn() * columnWidth);\n final int right = left + columnWidth;\n child.layout(left, top, right, bottom);\n }\n }\n\n // Align now view to match current time\n final View nowView = mNowView;\n final long now = System.currentTimeMillis();\n\n final int top = rulerView.getTimeVerticalOffset(now);\n final int bottom = top + nowView.getMeasuredHeight();\n final int left = 0;\n final int right = getWidth();\n\n nowView.layout(left, top, right, bottom);\n }\n}", "public class Maps {\n /**\n * Creates a {@code HashMap} instance.\n *\n * @return a newly-created, initially-empty {@code HashMap}\n */\n public static <K, V> HashMap<K, V> newHashMap() {\n return new HashMap<K, V>();\n }\n\n /**\n * Creates a {@code LinkedHashMap} instance.\n *\n * @return a newly-created, initially-empty {@code HashMap}\n */\n public static <K, V> LinkedHashMap<K, V> newLinkedHashMap() {\n return new LinkedHashMap<K, V>();\n }\n}", "public class NotifyingAsyncQueryHandler extends AsyncQueryHandler {\n private WeakReference<AsyncQueryListener> mListener;\n\n /**\n * Interface to listen for completed query operations.\n */\n public interface AsyncQueryListener {\n void onQueryComplete(int token, Object cookie, Cursor cursor);\n }\n\n public NotifyingAsyncQueryHandler(ContentResolver resolver, AsyncQueryListener listener) {\n super(resolver);\n setQueryListener(listener);\n }\n\n /**\n * Assign the given {@link AsyncQueryListener} to receive query events from\n * asynchronous calls. Will replace any existing listener.\n */\n public void setQueryListener(AsyncQueryListener listener) {\n mListener = new WeakReference<AsyncQueryListener>(listener);\n }\n\n /**\n * Clear any {@link AsyncQueryListener} set through\n * {@link #setQueryListener(AsyncQueryListener)}\n */\n public void clearQueryListener() {\n mListener = null;\n }\n\n /**\n * Begin an asynchronous query with the given arguments. When finished,\n * {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} is\n * called if a valid {@link AsyncQueryListener} is present.\n */\n public void startQuery(Uri uri, String[] projection) {\n startQuery(-1, null, uri, projection, null, null, null);\n }\n\n /**\n * Begin an asynchronous query with the given arguments. When finished,\n * {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} is called\n * if a valid {@link AsyncQueryListener} is present.\n *\n * @param token Unique identifier passed through to\n * {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)}\n */\n public void startQuery(int token, Uri uri, String[] projection) {\n startQuery(token, null, uri, projection, null, null, null);\n }\n\n /**\n * Begin an asynchronous query with the given arguments. When finished,\n * {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} is called\n * if a valid {@link AsyncQueryListener} is present.\n */\n public void startQuery(Uri uri, String[] projection, String sortOrder) {\n startQuery(-1, null, uri, projection, null, null, sortOrder);\n }\n\n /**\n * Begin an asynchronous query with the given arguments. When finished,\n * {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} is called\n * if a valid {@link AsyncQueryListener} is present.\n */\n public void startQuery(Uri uri, String[] projection, String selection,\n String[] selectionArgs, String orderBy) {\n startQuery(-1, null, uri, projection, selection, selectionArgs, orderBy);\n }\n\n /**\n * Begin an asynchronous update with the given arguments.\n */\n public void startUpdate(Uri uri, ContentValues values) {\n startUpdate(-1, null, uri, values, null, null);\n }\n\n public void startInsert(Uri uri, ContentValues values) {\n startInsert(-1, null, uri, values);\n }\n\n public void startDelete(Uri uri) {\n startDelete(-1, null, uri, null, null);\n }\n\n /** {@inheritDoc} */\n @Override\n protected void onQueryComplete(int token, Object cookie, Cursor cursor) {\n final AsyncQueryListener listener = mListener == null ? null : mListener.get();\n if (listener != null) {\n listener.onQueryComplete(token, cookie, cursor);\n } else if (cursor != null) {\n cursor.close();\n }\n }\n}", "public class ParserUtils {\n // TODO: consider refactor to HandlerUtils?\n\n // TODO: localize this string at some point\n public static final String BLOCK_TITLE_BREAKOUT_SESSIONS = \"Breakout sessions\";\n\n public static final String BLOCK_TYPE_FOOD = \"food\";\n public static final String BLOCK_TYPE_SESSION = \"session\";\n public static final String BLOCK_TYPE_OFFICE_HOURS = \"officehours\";\n\n public static final Set<String> LOCAL_TRACK_IDS = Sets.newHashSet(\n\t \"platinum\",\"gold\",\"silver\",\"bronze\", \"business\", \"development\", \"design\", \"community\");\n\n /** Used to sanitize a string to be {@link Uri} safe. */\n private static final Pattern sSanitizePattern = Pattern.compile(\"[^a-z0-9-_]\");\n private static final Pattern sParenPattern = Pattern.compile(\"\\\\(.*?\\\\)\");\n\n /** Used to split a comma-separated string. */\n private static final Pattern sCommaPattern = Pattern.compile(\"\\\\s*,\\\\s*\");\n\n private static Time sTime = new Time();\n private static XmlPullParserFactory sFactory;\n\n /**\n * Sanitize the given string to be {@link Uri} safe for building\n * {@link ContentProvider} paths.\n */\n public static String sanitizeId(String input) {\n return sanitizeId(input, false);\n }\n\n /**\n * Sanitize the given string to be {@link Uri} safe for building\n * {@link ContentProvider} paths.\n */\n public static String sanitizeId(String input, boolean stripParen) {\n if (input == null) return null;\n if (stripParen) {\n // Strip out all parenthetical statements when requested.\n input = sParenPattern.matcher(input).replaceAll(\"\");\n }\n return sSanitizePattern.matcher(input.toLowerCase()).replaceAll(\"\");\n }\n\n /**\n * Split the given comma-separated string, returning all values.\n */\n public static String[] splitComma(CharSequence input) {\n if (input == null) return new String[0];\n return sCommaPattern.split(input);\n }\n\n /**\n * Build and return a new {@link XmlPullParser} with the given\n * {@link InputStream} assigned to it.\n */\n public static XmlPullParser newPullParser(InputStream input) throws XmlPullParserException {\n if (sFactory == null) {\n sFactory = XmlPullParserFactory.newInstance();\n }\n final XmlPullParser parser = sFactory.newPullParser();\n parser.setInput(input, null);\n return parser;\n }\n\n /**\n * Parse the given string as a RFC 3339 timestamp, returning the value as\n * milliseconds since the epoch.\n */\n public static long parseTime(String time) {\n sTime.parse3339(time);\n return sTime.toMillis(false);\n }\n\n /**\n * Return a {@link Blocks#BLOCK_ID} matching the requested arguments.\n */\n public static String findBlock(String title, long startTime, long endTime) {\n // TODO: in future we might check provider if block exists\n return Blocks.generateBlockId(startTime, endTime);\n }\n\n /**\n * Return a {@link Blocks#BLOCK_ID} matching the requested arguments,\n * inserting a new {@link Blocks} entry as a\n * {@link ContentProviderOperation} when none already exists.\n */\n public static String findOrCreateBlock(String title, String type, long startTime, long endTime,\n ArrayList<ContentProviderOperation> batch, ContentResolver resolver) {\n // TODO: check for existence instead of always blindly creating. it's\n // okay for now since the database replaces on conflict.\n final ContentProviderOperation.Builder builder = ContentProviderOperation\n .newInsert(Blocks.CONTENT_URI);\n final String blockId = Blocks.generateBlockId(startTime, endTime);\n builder.withValue(Blocks.BLOCK_ID, blockId);\n builder.withValue(Blocks.BLOCK_TITLE, title);\n builder.withValue(Blocks.BLOCK_START, startTime);\n builder.withValue(Blocks.BLOCK_END, endTime);\n builder.withValue(Blocks.BLOCK_TYPE, type);\n batch.add(builder.build());\n return blockId;\n }\n\n /**\n * Query and return the {@link SyncColumns#UPDATED} time for the requested\n * {@link Uri}. Expects the {@link Uri} to reference a single item.\n */\n public static long queryItemUpdated(Uri uri, ContentResolver resolver) {\n final String[] projection = { SyncColumns.UPDATED };\n final Cursor cursor = resolver.query(uri, projection, null, null, null);\n try {\n if (cursor.moveToFirst()) {\n return cursor.getLong(0);\n } else {\n return ScheduleContract.UPDATED_NEVER;\n }\n } finally {\n cursor.close();\n }\n }\n\n /**\n * Query and return the newest {@link SyncColumns#UPDATED} time for all\n * entries under the requested {@link Uri}. Expects the {@link Uri} to\n * reference a directory of several items.\n */\n public static long queryDirUpdated(Uri uri, ContentResolver resolver) {\n final String[] projection = { \"MAX(\" + SyncColumns.UPDATED + \")\" };\n final Cursor cursor = resolver.query(uri, projection, null, null, null);\n try {\n cursor.moveToFirst();\n return cursor.getLong(0);\n } finally {\n cursor.close();\n }\n }\n\n /**\n * Translate an incoming {@link Tracks#TRACK_ID}, usually passing directly\n * through, but returning a different value when a local alias is defined.\n */\n public static String translateTrackIdAlias(String trackId) {\n if (\"gwt\".equals(trackId)) {\n return \"googlewebtoolkit\";\n } else {\n return trackId;\n }\n }\n\n /**\n * Translate a possibly locally aliased {@link Tracks#TRACK_ID} to its real value;\n * this usually is a pass-through.\n */\n public static String translateTrackIdAliasInverse(String trackId) {\n if (\"googlewebtoolkit\".equals(trackId)) {\n return \"gwt\";\n } else {\n return trackId;\n }\n }\n\n /** XML tag constants used by the Atom standard. */\n public interface AtomTags {\n String ENTRY = \"entry\";\n String UPDATED = \"updated\";\n String TITLE = \"title\";\n String LINK = \"link\";\n String CONTENT = \"content\";\n\n String REL = \"rel\";\n String HREF = \"href\";\n }\n}", "public class UIUtils {\n\n /**\n * Time zone to use when formatting all session times. To always use the\n * phone local time, use {@link TimeZone#getDefault()}.\n */\n public static TimeZone CONFERENCE_TIME_ZONE = TimeZone.getTimeZone(\"America/Denver\");\n\n public static final long CONFERENCE_START_MILLIS = ParserUtils.parseTime(\n \"2010-06-26T09:00:00.000-06:00\");\n public static final long CONFERENCE_END_MILLIS = ParserUtils.parseTime(\n \"2010-06-27T18:30:00.000-06:00\");\n\n public static final Uri CONFERENCE_URL = Uri.parse(\"http://drupalcampcolorado.org\");\n\n /** Flags used with {@link DateUtils#formatDateRange}. */\n private static final int TIME_FLAGS = DateUtils.FORMAT_SHOW_TIME\n | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_WEEKDAY;\n\n private static final int BRIGHTNESS_THRESHOLD = 150;\n\n /** {@link StringBuilder} used for formatting time block. */\n private static StringBuilder sBuilder = new StringBuilder(50);\n /** {@link Formatter} used for formatting time block. */\n private static Formatter sFormatter = new Formatter(sBuilder, Locale.getDefault());\n\n private static StyleSpan sBoldSpan = new StyleSpan(Typeface.BOLD);\n\n public static void setTitleBarColor(View titleBarView, int color) {\n final ViewGroup titleBar = (ViewGroup) titleBarView;\n titleBar.setBackgroundColor(color);\n\n /*\n * Calculate the brightness of the titlebar color, based on the commonly known\n * brightness formula:\n *\n * http://en.wikipedia.org/wiki/HSV_color_space%23Lightness\n */\n int brColor = (30 * Color.red(color) +\n 59 * Color.green(color) +\n 11 * Color.blue(color)) / 100;\n if (brColor > BRIGHTNESS_THRESHOLD) {\n ((TextView) titleBar.findViewById(R.id.title_text)).setTextColor(\n titleBar.getContext().getResources().getColor(R.color.title_text_alt));\n\n // Iterate through all children of the titlebar and if they're a LevelListDrawable,\n // set their level to 1 (alternate).\n // TODO: find a less hacky way of doing this.\n titleBar.post(new Runnable() {\n public void run() {\n final int childCount = titleBar.getChildCount();\n for (int i = 0; i < childCount; i++) {\n final View child = titleBar.getChildAt(i);\n if (child instanceof ImageButton) {\n final ImageButton childButton = (ImageButton) child;\n if (childButton.getDrawable() != null &&\n childButton.getDrawable() instanceof LevelListDrawable) {\n ((LevelListDrawable) childButton.getDrawable()).setLevel(1);\n }\n }\n }\n }\n });\n }\n }\n\n /**\n * Invoke \"home\" action, returning to {@link HomeActivity}.\n */\n public static void goHome(Context context) {\n final Intent intent = new Intent(context, HomeActivity.class);\n intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);\n context.startActivity(intent);\n }\n\n /**\n * Invoke \"search\" action, triggering a default search.\n */\n public static void goSearch(Activity activity) {\n activity.startSearch(null, false, Bundle.EMPTY, false);\n }\n\n /**\n * Format and return the given {@link Blocks} and {@link Rooms} values using\n * {@link #CONFERENCE_TIME_ZONE}.\n */\n public static String formatSessionSubtitle(long blockStart, long blockEnd,\n String roomName, Context context) {\n TimeZone.setDefault(CONFERENCE_TIME_ZONE);\n\n // NOTE: There is an efficient version of formatDateRange in Eclair and\n // beyond that allows you to recycle a StringBuilder.\n final CharSequence timeString = DateUtils.formatDateRange(context,\n blockStart, blockEnd, TIME_FLAGS);\n\n return context.getString(R.string.session_subtitle, timeString, roomName);\n }\n\n /**\n * Populate the given {@link TextView} with the requested text, formatting\n * through {@link Html#fromHtml(String)} when applicable. Also sets\n * {@link TextView#setMovementMethod} so inline links are handled.\n */\n public static void setTextMaybeHtml(TextView view, String text) {\n if (text.contains(\"<\") && text.contains(\">\")) {\n view.setText(Html.fromHtml(text));\n view.setMovementMethod(LinkMovementMethod.getInstance());\n } else {\n view.setText(text);\n }\n }\n\n public static void setSessionTitleColor(long blockStart, long blockEnd, TextView title,\n TextView subtitle) {\n long currentTimeMillis = System.currentTimeMillis();\n int colorId = android.R.color.primary_text_light;\n int subColorId = android.R.color.secondary_text_light;\n\n if (currentTimeMillis > blockEnd &&\n currentTimeMillis < CONFERENCE_END_MILLIS) {\n colorId = subColorId = R.color.session_foreground_past;\n }\n\n final Resources res = title.getResources();\n title.setTextColor(res.getColor(colorId));\n subtitle.setTextColor(res.getColor(subColorId));\n }\n\n /**\n * Given a snippet string with matching segments surrounded by curly\n * braces, turn those areas into bold spans, removing the curly braces.\n */\n public static Spannable buildStyledSnippet(String snippet) {\n final SpannableStringBuilder builder = new SpannableStringBuilder(snippet);\n\n // Walk through string, inserting bold snippet spans\n int startIndex = -1, endIndex = -1, delta = 0;\n while ((startIndex = snippet.indexOf('{', endIndex)) != -1) {\n endIndex = snippet.indexOf('}', startIndex);\n\n // Remove braces from both sides\n builder.delete(startIndex - delta, startIndex - delta + 1);\n builder.delete(endIndex - delta - 1, endIndex - delta);\n\n // Insert bold style\n builder.setSpan(sBoldSpan, startIndex - delta, endIndex - delta - 1,\n Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);\n\n delta += 2;\n }\n\n return builder;\n }\n}", "public interface AsyncQueryListener {\n void onQueryComplete(int token, Object cookie, Cursor cursor);\n}" ]
import com.underhilllabs.dccsched.R; import com.underhilllabs.dccsched.provider.ScheduleContract.Blocks; import com.underhilllabs.dccsched.ui.widget.BlockView; import com.underhilllabs.dccsched.ui.widget.BlocksLayout; import com.underhilllabs.dccsched.util.Maps; import com.underhilllabs.dccsched.util.NotifyingAsyncQueryHandler; import com.underhilllabs.dccsched.util.ParserUtils; import com.underhilllabs.dccsched.util.UIUtils; import com.underhilllabs.dccsched.util.NotifyingAsyncQueryHandler.AsyncQueryListener; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.graphics.Rect; import android.graphics.drawable.LayerDrawable; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.provider.BaseColumns; import android.util.Log; import android.view.View; import android.widget.ScrollView; import java.util.HashMap;
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.underhilllabs.dccsched.ui; /** * {@link Activity} that displays a high-level view of a single day of * {@link Blocks} across the conference. Shows them lined up against a vertical * ruler of times across the day. */ public class BlocksActivity extends Activity implements AsyncQueryListener, View.OnClickListener { private static final String TAG = "BlocksActivity"; // TODO: these layouts and views are structured pretty weird, ask someone to // review them and come up with better organization. // TODO: show blocks that don't fall into columns at the bottom public static final String EXTRA_TIME_START = "com.google.android.dccsched.extra.TIME_START"; public static final String EXTRA_TIME_END = "com.google.android.dccsched.extra.TIME_END"; private ScrollView mScrollView;
private BlocksLayout mBlocks;
2
lucmoreau/OpenProvenanceModel
tupelo/src/test/java/org/openprovenance/rdf/Example5Test.java
[ "public interface Edge extends Annotable, HasAccounts {\n Ref getCause();\n Ref getEffect();\n} ", "public class OPMFactory implements CommonURIs {\n\n public static String roleIdPrefix=\"r_\";\n public static String usedIdPrefix=\"u_\";\n public static String wasGenerateByIdPrefix=\"g_\";\n public static String wasDerivedFromIdPrefix=\"d_\";\n public static String wasTriggeredByIdPrefix=\"t_\";\n public static String wasControlledByIdPrefix=\"c_\";\n public static String opmGraphIdPrefix=\"gr_\";\n\n public static final String packageList=\n \"org.openprovenance.model\";\n\n public String getPackageList() {\n return packageList;\n }\n\n private final static OPMFactory oFactory=new OPMFactory();\n\n public static OPMFactory getFactory() {\n return oFactory;\n }\n\n protected ObjectFactory of;\n\n protected DatatypeFactory dataFactory;\n\n void init() {\n try {\n dataFactory= DatatypeFactory.newInstance ();\n } catch (DatatypeConfigurationException ex) {\n throw new RuntimeException (ex);\n }\n }\n\n\n\n public OPMFactory() {\n of=new ObjectFactory();\n init();\n }\n\n public OPMFactory(ObjectFactory of) {\n this.of=of;\n init();\n }\n\n public ObjectFactory getObjectFactory() {\n return of;\n }\n\n public ProcessRef newProcessRef(Process p) {\n ProcessRef res=of.createProcessRef();\n res.setRef(p);\n return res;\n }\n\n public RoleRef newRoleRef(Role p) {\n RoleRef res=of.createRoleRef();\n res.setRef(p);\n return res;\n }\n\n public AnnotationRef newAnnotationRef(Annotation a) {\n AnnotationRef res=of.createAnnotationRef();\n res.setRef(a);\n return res;\n }\n\n public ArtifactRef newArtifactRef(Artifact a) {\n ArtifactRef res=of.createArtifactRef();\n res.setRef(a);\n return res;\n }\n public AgentRef newAgentRef(Agent a) {\n AgentRef res=of.createAgentRef();\n res.setRef(a);\n return res;\n }\n\n public AccountRef newAccountRef(Account acc) {\n AccountRef res=of.createAccountRef();\n res.setRef(acc);\n return res;\n }\n\n\n\n\n\n public DependencyRef newDependencyRef(WasGeneratedBy edge) {\n DependencyRef res=of.createDependencyRef();\n res.setRef(edge);\n return res;\n }\n\n public DependencyRef newDependencyRef(Used edge) {\n DependencyRef res=of.createDependencyRef();\n res.setRef(edge);\n return res;\n }\n public DependencyRef newDependencyRef(WasDerivedFrom edge) {\n DependencyRef res=of.createDependencyRef();\n res.setRef(edge);\n return res;\n }\n\n public DependencyRef newDependencyRef(WasControlledBy edge) {\n DependencyRef res=of.createDependencyRef();\n res.setRef(edge);\n return res;\n }\n public DependencyRef newDependencyRef(WasTriggeredBy edge) {\n DependencyRef res=of.createDependencyRef();\n res.setRef(edge);\n return res;\n }\n\n\n\n public Process newProcess(String pr,\n Collection<Account> accounts) {\n return newProcess(pr,accounts,null);\n }\n\n public Process newProcess(String pr,\n Collection<Account> accounts,\n String label) {\n Process res=of.createProcess();\n res.setId(pr);\n addAccounts(res,accounts,null);\n if (label!=null) addAnnotation(res,newLabel(label));\n return res;\n }\n\n public Agent newAgent(String ag,\n Collection<Account> accounts) {\n return newAgent(ag,accounts,null);\n }\n\n public Agent newAgent(String ag,\n Collection<Account> accounts,\n String label) {\n Agent res=of.createAgent();\n res.setId(ag);\n addAccounts(res,accounts,null);\n if (label!=null) addAnnotation(res,newLabel(label));\n return res;\n }\n\n public Account newAccount(String id) {\n Account res=of.createAccount();\n res.setId(id);\n return res;\n }\n public Account newAccount(String id, String label) {\n Account res=of.createAccount();\n res.setId(id);\n res.getAnnotation().add(of.createLabel(newLabel(label)));\n return res;\n }\n\n public Label newLabel(String label) {\n Label res=of.createLabel();\n res.setValue(label);\n return res;\n }\n\n public Value newValue(Object value, String encoding) {\n Value res=of.createValue();\n res.setContent(value);\n res.setEncoding(encoding);\n return res;\n }\n\n\n public Profile newProfile(String profile) {\n Profile res=of.createProfile();\n res.setValue(profile);\n return res;\n }\n\n\n public PName newPName(String profile) {\n PName res=of.createPName();\n res.setValue(profile);\n return res;\n }\n\n\n public Role getRole(Edge e) {\n if (e instanceof Used) {\n return ((Used) e).getRole();\n } \n if (e instanceof WasGeneratedBy) {\n return ((WasGeneratedBy) e).getRole();\n } \n if (e instanceof WasControlledBy) {\n return ((WasControlledBy) e).getRole();\n }\n return null;\n }\n \n public String getLabel(EmbeddedAnnotation annotation) {\n if (annotation instanceof Label) {\n Label label=(Label) annotation;\n return label.getValue();\n } else {\n for (Property prop: annotation.getProperty()) {\n if (prop.getKey().equals(LABEL_PROPERTY)) {\n return (String) prop.getValue();\n }\n }\n return null;\n }\n }\n\n\n public String getType(EmbeddedAnnotation annotation) {\n if (annotation instanceof Type) {\n Type type=(Type) annotation;\n return type.getValue();\n } else {\n for (Property prop: annotation.getProperty()) {\n if (prop.getKey().equals(TYPE_PROPERTY)) {\n return (String) prop.getValue();\n }\n }\n return null;\n }\n }\n\n public Object getValue(EmbeddedAnnotation annotation) {\n if (annotation instanceof Value) {\n Value value=(Value) annotation;\n return value.getContent();\n } else {\n for (Property prop: annotation.getProperty()) {\n if (prop.getKey().equals(VALUE_PROPERTY)) {\n return prop.getValue();\n }\n }\n return null;\n }\n }\n\n public String getEncoding(EmbeddedAnnotation annotation) {\n if (annotation instanceof Value) {\n Value value=(Value) annotation;\n return value.getEncoding();\n } else {\n for (Property prop: annotation.getProperty()) {\n if (prop.getKey().equals(ENCODING_PROPERTY)) {\n return (String) prop.getValue();\n }\n }\n return null;\n }\n }\n\n public String getProfile(EmbeddedAnnotation annotation) {\n if (annotation instanceof Profile) {\n Profile profile=(Profile) annotation;\n return profile.getValue();\n } else {\n for (Property prop: annotation.getProperty()) {\n if (prop.getKey().equals(PROFILE_PROPERTY)) {\n return (String) prop.getValue();\n }\n }\n return null;\n }\n }\n\n public String getPname(EmbeddedAnnotation annotation) {\n if (annotation instanceof PName) {\n PName pname=(PName) annotation;\n return pname.getValue();\n } else {\n for (Property prop: annotation.getProperty()) {\n if (prop.getKey().equals(PNAME_PROPERTY)) {\n return (String) prop.getValue();\n }\n }\n return null;\n }\n }\n\n\n\n /** Return the value of the value property in the first annotation. */\n\n public Object getValue(List<JAXBElement<? extends EmbeddedAnnotation>> annotations) {\n for (JAXBElement<? extends EmbeddedAnnotation> jann: annotations) {\n EmbeddedAnnotation ann=jann.getValue();\n Object value=getValue(ann);\n if (value!=null) return value;\n }\n return null;\n }\n\n\n\n /** Return the value of the label property in the first annotation. */\n public String getLabel(List<JAXBElement<? extends EmbeddedAnnotation>> annotations) {\n for (JAXBElement<? extends EmbeddedAnnotation> jann: annotations) {\n EmbeddedAnnotation ann=jann.getValue();\n String label=getLabel(ann);\n if (label!=null) return label;\n }\n return null;\n }\n\n\n /** Return the value of the type property in the first annotation. */\n\n public String getType(List<JAXBElement<? extends EmbeddedAnnotation>> annotations) {\n for (JAXBElement<? extends EmbeddedAnnotation> jann: annotations) {\n EmbeddedAnnotation ann=jann.getValue();\n String type=getType(ann);\n if (type!=null) return type;\n }\n return null;\n }\n\n\n /** Return the value of the profile property in the first annotation. */\n public String getProfile(List<JAXBElement<? extends EmbeddedAnnotation>> annotations) {\n for (JAXBElement<? extends EmbeddedAnnotation> jann: annotations) {\n EmbeddedAnnotation ann=jann.getValue();\n String profile=getProfile(ann);\n if (profile!=null) return profile;\n }\n return null;\n }\n\n /** Return the value of the pname property in the first annotation. */\n public String getPname(List<JAXBElement<? extends EmbeddedAnnotation>> annotations) {\n for (JAXBElement<? extends EmbeddedAnnotation> jann: annotations) {\n EmbeddedAnnotation ann=jann.getValue();\n String pname=getPname(ann);\n if (pname!=null) return pname;\n }\n return null;\n }\n\n\n /** Return the value of the value property. */\n\n public List<Object> getValues(List<JAXBElement<? extends EmbeddedAnnotation>> annotations) {\n List<Object> res=new LinkedList();\n for (JAXBElement<? extends EmbeddedAnnotation> jann: annotations) {\n EmbeddedAnnotation ann=jann.getValue();\n Object value=getValue(ann);\n if (value!=null) res.add(value);\n }\n return res;\n }\n\n\n\n /** Return the value of the label property. */\n public List<String> getLabels(List<JAXBElement<? extends EmbeddedAnnotation>> annotations) {\n List<String> res=new LinkedList();\n for (JAXBElement<? extends EmbeddedAnnotation> jann: annotations) {\n EmbeddedAnnotation ann=jann.getValue();\n String label=getLabel(ann);\n if (label!=null) res.add(label);\n }\n return res;\n }\n\n\n /** Return the value of the type property. */\n\n public List<String> getTypes(List<JAXBElement<? extends EmbeddedAnnotation>> annotations) {\n List<String> res=new LinkedList();\n for (JAXBElement<? extends EmbeddedAnnotation> jann: annotations) {\n EmbeddedAnnotation ann=jann.getValue();\n String type=getType(ann);\n if (type!=null) res.add(type);\n }\n return res;\n }\n\n\n /** Return the value of the profile property. */\n public List<String> getProfiles(List<JAXBElement<? extends EmbeddedAnnotation>> annotations) {\n List<String> res=new LinkedList();\n for (JAXBElement<? extends EmbeddedAnnotation> jann: annotations) {\n EmbeddedAnnotation ann=jann.getValue();\n String profile=getProfile(ann);\n if (profile!=null) res.add(profile);\n }\n return res;\n }\n\n /** Return the value of the pname property. */\n public List<String> getPnames(List<JAXBElement<? extends EmbeddedAnnotation>> annotations) {\n List<String> res=new LinkedList();\n for (JAXBElement<? extends EmbeddedAnnotation> jann: annotations) {\n EmbeddedAnnotation ann=jann.getValue();\n String pname=getPname(ann);\n if (pname!=null) res.add(pname);\n }\n return res;\n }\n\n /** Generic accessor for annotable entities. */\n public String getLabel(Annotable annotable) {\n return getLabel(annotable.getAnnotation());\n }\n\n /** Generic accessor for annotable entities. */\n public String getType(Annotable annotable) {\n return getType(annotable.getAnnotation());\n }\n\n /** Generic accessor for annotable entities. */\n public String getProfile(Annotable annotable) {\n return getProfile(annotable.getAnnotation());\n }\n\n /** Generic accessor for annotable entities. */\n public String getPname(Annotable annotable) {\n return getPname(annotable.getAnnotation());\n }\n\n\n public Type newType(String type) {\n Type res=of.createType();\n res.setValue(type);\n return res;\n }\n\n public void addValue(Artifact annotable, Object value, String encoding) {\n addAnnotation(annotable,newValue(value,encoding));\n }\n\n public void addAnnotation(Annotable annotable, Label ann) {\n if (ann!=null) {\n annotable.getAnnotation().add(of.createLabel(ann));\n }\n }\n\n public void addAnnotation(Annotable annotable, Value ann) {\n annotable.getAnnotation().add(of.createValue(ann));\n }\n\n public void addAnnotation(Annotable annotable, Profile ann) {\n annotable.getAnnotation().add(of.createProfile(ann));\n }\n\n public void addAnnotation(Annotable annotable, PName ann) {\n annotable.getAnnotation().add(of.createPname(ann));\n }\n\n public void addAnnotation(Annotable annotable, EmbeddedAnnotation ann) {\n annotable.getAnnotation().add(of.createAnnotation(ann));\n }\n\n public void addAnnotation(Annotable annotable, JAXBElement<? extends EmbeddedAnnotation> ann) {\n annotable.getAnnotation().add(ann);\n }\n public void addAnnotations(Annotable annotable, List<JAXBElement<? extends EmbeddedAnnotation>> anns) {\n annotable.getAnnotation().addAll(anns);\n }\n\n public void expandAnnotation(EmbeddedAnnotation ann) {\n if (ann instanceof Label) {\n Label label=(Label) ann;\n String labelValue=label.getValue();\n ann.getProperty().add(newProperty(LABEL_PROPERTY,labelValue));\n }\n if (ann instanceof Type) {\n Type type=(Type) ann;\n String typeValue=type.getValue();\n ann.getProperty().add(newProperty(TYPE_PROPERTY,typeValue));\n }\n if (ann instanceof Value) {\n Value val=(Value) ann;\n Object valValue=val.getContent();\n ann.getProperty().add(newProperty(VALUE_PROPERTY,valValue));\n }\n if (ann instanceof PName) {\n PName pname=(PName) ann;\n String pnameValue=pname.getValue();\n ann.getProperty().add(newProperty(PNAME_PROPERTY,pnameValue));\n }\n\n }\n\n\n public JAXBElement<? extends EmbeddedAnnotation> compactAnnotation(EmbeddedAnnotation ann) {\n if (ann instanceof Label) {\n Label label=(Label) ann;\n return of.createLabel(label);\n }\n if (ann instanceof Type) {\n Type type=(Type) ann;\n return of.createType(type);\n }\n if (ann instanceof Profile) {\n Profile profile=(Profile) ann;\n return of.createProfile(profile);\n }\n if (ann instanceof Value) {\n Value value=(Value) ann;\n return of.createValue(value);\n }\n if (ann instanceof PName) {\n PName pname=(PName) ann;\n return of.createPname(pname);\n }\n List<Property> properties=ann.getProperty();\n if (properties.size()==1) {\n Property prop=properties.get(0);\n if (prop.getKey().equals(LABEL_PROPERTY)) {\n Label label=newLabel((String)prop.getValue());\n setIdForCompactAnnotation(label,ann.getId());\n return of.createLabel(label);\n }\n if (prop.getKey().equals(TYPE_PROPERTY)) {\n Type type=newType((String)prop.getValue());\n setIdForCompactAnnotation(type,ann.getId());\n return of.createType(type);\n }\n if (prop.getKey().equals(PROFILE_PROPERTY)) {\n Profile profile=newProfile((String)prop.getValue());\n setIdForCompactAnnotation(profile,ann.getId());\n return of.createProfile(profile);\n }\n if (prop.getKey().equals(PNAME_PROPERTY)) {\n PName pname=newPName((String)prop.getValue());\n setIdForCompactAnnotation(pname,ann.getId());\n return of.createPname(pname);\n }\n }\n else if (properties.size()==2) {\n if ((properties.get(0).getKey().equals(VALUE_PROPERTY))\n &&\n (properties.get(1).getKey().equals(ENCODING_PROPERTY))) {\n Value value=newValue(properties.get(0).getValue(),\n (String)properties.get(1).getValue());\n setIdForCompactAnnotation(value,ann.getId());\n return of.createValue(value);\n } else if ((properties.get(1).getKey().equals(VALUE_PROPERTY))\n &&\n (properties.get(0).getKey().equals(ENCODING_PROPERTY))) {\n Value value=newValue(properties.get(1).getValue(),\n (String)properties.get(0).getValue());\n setIdForCompactAnnotation(value,ann.getId());\n return of.createValue(value);\n }\n }\n\n return of.createAnnotation(ann);\n }\n\n public XMLGregorianCalendar\n newXMLGregorianCalendar(GregorianCalendar gc) {\n return dataFactory.newXMLGregorianCalendar(gc);\n }\n\n\n\tpublic OTime newOTime (OTime time) {\n return newOTime(time.getNoEarlierThan(),\n time.getNoLaterThan(),\n time.getExactlyAt());\n }\n\n\n\tpublic OTime newOTime (XMLGregorianCalendar point1,\n XMLGregorianCalendar point2,\n XMLGregorianCalendar point3) {\n OTime time = of.createOTime();\n time.setNoEarlierThan (point1);\n time.setNoLaterThan (point2);\n time.setExactlyAt (point3);\n return time;\n }\n\n\tpublic OTime newOTime (XMLGregorianCalendar point1,\n XMLGregorianCalendar point2) {\n OTime time = of.createOTime();\n time.setNoEarlierThan (point1);\n time.setNoLaterThan (point2);\n return time;\n }\n\n\tpublic OTime newOTime (XMLGregorianCalendar point) {\n OTime time = of.createOTime();\n time.setExactlyAt (point);\n return time;\n }\n\n\tpublic OTime newOTime (String value1, String value2) {\n XMLGregorianCalendar point1 = dataFactory.newXMLGregorianCalendar (value1);\n XMLGregorianCalendar point2 = dataFactory.newXMLGregorianCalendar (value2);\n return newOTime(point1,point2);\n }\n\n\tpublic OTime newOTime (Date date1,\n Date date2) {\n GregorianCalendar gc1=new GregorianCalendar();\n gc1.setTime(date1);\n GregorianCalendar gc2=new GregorianCalendar();\n gc2.setTime(date2);\n return newOTime(newXMLGregorianCalendar(gc1),\n newXMLGregorianCalendar(gc2));\n }\n\n\tpublic OTime newOTime (Date date) {\n GregorianCalendar gc=new GregorianCalendar();\n gc.setTime(date);\n return newOTime(newXMLGregorianCalendar(gc));\n }\n\n\tpublic OTime newInstantaneousTime (XMLGregorianCalendar point) {\n return newOTime(point);\n }\n\n\tpublic OTime newInstantaneousTime (String value) {\n XMLGregorianCalendar point = dataFactory.newXMLGregorianCalendar (value);\n return newOTime(point);\n }\n\n\n\tpublic OTime newInstantaneousTime (Date date) {\n GregorianCalendar gc=new GregorianCalendar();\n gc.setTime(date);\n XMLGregorianCalendar xgc=newXMLGregorianCalendar(gc);\n return newOTime(xgc);\n }\n\n\tpublic OTime newInstantaneousTimeNow () {\n return newInstantaneousTime(new Date());\n }\n\n\n public boolean compactId=false;\n \n public void setIdForCompactAnnotation(EmbeddedAnnotation ann, String id) {\n if (compactId) ann.setId(id);\n }\n\n\n public void addAnnotation(Annotable annotable, List<EmbeddedAnnotation> anns) {\n List<JAXBElement<? extends EmbeddedAnnotation>> annotations=annotable.getAnnotation();\n for (EmbeddedAnnotation ann: anns) { \n annotations.add(of.createAnnotation(ann));\n }\n }\n\n\n\n public void addCompactAnnotation(Annotable annotable, List<EmbeddedAnnotation> anns) {\n List<JAXBElement<? extends EmbeddedAnnotation>> annotations=annotable.getAnnotation();\n for (EmbeddedAnnotation ann: anns) { \n annotations.add(compactAnnotation(ann));\n }\n }\n\n\n\n public Overlaps newOverlaps(Collection<Account> accounts) {\n Overlaps res=of.createOverlaps();\n LinkedList ll=new LinkedList();\n int i=0;\n for (Account acc: accounts) {\n if (i==2) break;\n ll.add(newAccountRef(acc));\n i++;\n }\n res.getAccount().addAll(ll);\n return res;\n }\n \n public Overlaps newOverlaps(AccountRef aid1,AccountRef aid2) {\n Overlaps res=of.createOverlaps();\n res.getAccount().add(aid1);\n res.getAccount().add(aid2);\n return res;\n }\n\n /** By default, no auto generation of Id. Override this behaviour if required. */\n public String autoGenerateId(String prefix) {\n return null;\n }\n\n /** Conditional autogeneration of Id. By default, no auto\n * generation of Id. Override this behaviour if required. */\n public String autoGenerateId(String prefix, String id) {\n return id;\n }\n\n public Role newRole(String value) {\n return newRole(autoGenerateId(roleIdPrefix),value);\n }\n\n public Role newRole(Role role) {\n return newRole(autoGenerateId(roleIdPrefix,role.getId()),role.getValue());\n }\n\n public Role newRole(String id, String value) {\n Role res=of.createRole();\n res.setId(id);\n res.setValue(value);\n return res;\n }\n\n public Artifact newArtifact(Artifact a) {\n LinkedList<Account> ll=new LinkedList();\n for (AccountRef acc: a.getAccount()) {\n ll.add(newAccount((Account)acc.getRef()));\n }\n Artifact res=newArtifact(a.getId(),ll);\n addNewAnnotations(res,a.getAnnotation());\n return res;\n }\n public Process newProcess(Process a) {\n LinkedList<Account> ll=new LinkedList();\n for (AccountRef acc: a.getAccount()) {\n ll.add(newAccount((Account)acc.getRef()));\n }\n Process res=newProcess(a.getId(),ll);\n addNewAnnotations(res,a.getAnnotation());\n return res;\n }\n public Agent newAgent(Agent a) {\n LinkedList<Account> ll=new LinkedList();\n for (AccountRef acc: a.getAccount()) {\n ll.add(newAccount((Account)acc.getRef()));\n }\n Agent res=newAgent(a.getId(),ll);\n addNewAnnotations(res,a.getAnnotation());\n return res;\n }\n\n public Account newAccount(Account acc) {\n Account res=newAccount(acc.getId());\n addNewAnnotations(res,acc.getAnnotation());\n return res;\n }\n\n public void addNewAnnotations(Annotable res,\n List<JAXBElement<? extends org.openprovenance.model.EmbeddedAnnotation>> anns) {\n for (JAXBElement<? extends org.openprovenance.model.EmbeddedAnnotation> ann: anns) {\n EmbeddedAnnotation ea=ann.getValue();\n if (ea.getId()!=null) \n addAnnotation(res,newEmbeddedAnnotation(ea.getId(),\n ea.getProperty(),\n ea.getAccount(),\n null));\n }\n }\n\n\n\n\n public Artifact newArtifact(String id,\n Collection<Account> accounts) {\n return newArtifact(id,accounts,null);\n }\n\n public Artifact newArtifact(String id,\n Collection<Account> accounts,\n String label) {\n Artifact res=of.createArtifact();\n res.setId(id);\n addAccounts(res,accounts,null);\n if (label!=null) addAnnotation(res,newLabel(label));\n return res;\n }\n\n public void addAccounts(HasAccounts element, Collection<Account> accounts, Object ignoreForErasure) {\n if ((accounts !=null) && (accounts.size()!=0)) {\n LinkedList ll=new LinkedList();\n for (Account acc: accounts) {\n ll.add(newAccountRef(acc));\n }\n addAccounts(element,ll);\n }\n }\n public void addAccounts(HasAccounts element, Collection<AccountRef> accounts) {\n if ((accounts !=null) && (accounts.size()!=0)) {\n element.getAccount().addAll(accounts);\n }\n }\n\n\n public Used newUsed(String id,\n ProcessRef pid,\n Role role,\n ArtifactRef aid,\n Collection<AccountRef> accounts) {\n Used res=of.createUsed();\n res.setId(autoGenerateId(usedIdPrefix,id));\n res.setEffect(pid);\n res.setRole(role);\n res.setCause(aid);\n addAccounts(res,accounts);\n return res;\n }\n\n\n\n public UsedStar newUsedStar(ProcessRef pid,\n ArtifactRef aid,\n Collection<AccountRef> accounts) {\n UsedStar res=of.createUsedStar();\n res.setEffect(pid);\n res.setCause(aid);\n addAccounts(res,accounts);\n return res;\n }\n\n public Used newUsed(Process p,\n Role role,\n Artifact a,\n Collection<Account> accounts) {\n Used res=newUsed(null,p,role,a,accounts);\n return res;\n }\n\n public Used newUsed(String id,\n Process p,\n Role role,\n Artifact a,\n Collection<Account> accounts) {\n ProcessRef pid=newProcessRef(p);\n ArtifactRef aid=newArtifactRef(a);\n LinkedList ll=new LinkedList();\n if (accounts!=null) {\n for (Account acc: accounts) {\n ll.add(newAccountRef(acc));\n }\n }\n return newUsed(id,pid,role,aid,ll);\n }\n public UsedStar newUsedStar(Process p,\n Artifact a,\n Collection<Account> accounts) {\n ProcessRef pid=newProcessRef(p);\n ArtifactRef aid=newArtifactRef(a);\n LinkedList ll=new LinkedList();\n if (accounts!=null) {\n for (Account acc: accounts) {\n ll.add(newAccountRef(acc));\n }\n }\n return newUsedStar(pid,aid,ll);\n }\n\n\n public Used newUsed(String id,\n Process p,\n Role role,\n Artifact a,\n String type,\n Collection<Account> accounts) {\n Used res=newUsed(id,p,role,a,accounts);\n addAnnotation(res,of.createType(newType(type)));\n return res;\n }\n\n public Used newUsed(Used u) {\n Used u1=newUsed(u.getId(),\n u.getEffect(),\n u.getRole(),\n u.getCause(),\n u.getAccount());\n u1.getAnnotation().addAll(u.getAnnotation());\n return u1;\n }\n\n public WasControlledBy newWasControlledBy(WasControlledBy c) {\n WasControlledBy wcb=newWasControlledBy(c.getEffect(),\n c.getRole(),\n c.getCause(),\n c.getAccount());\n wcb.setId(c.getId());\n wcb.getAnnotation().addAll(c.getAnnotation());\n return wcb;\n }\n\n public WasGeneratedBy newWasGeneratedBy(WasGeneratedBy g) {\n WasGeneratedBy wgb=newWasGeneratedBy(g.getId(),\n g.getEffect(),\n g.getRole(),\n g.getCause(),\n g.getAccount());\n wgb.setId(g.getId());\n wgb.getAnnotation().addAll(g.getAnnotation());\n return wgb;\n }\n\n public WasDerivedFrom newWasDerivedFrom(WasDerivedFrom d) {\n WasDerivedFrom wdf=newWasDerivedFrom(d.getId(),\n d.getEffect(),\n d.getCause(),\n d.getAccount());\n wdf.getAnnotation().addAll(d.getAnnotation());\n return wdf;\n }\n\n public WasTriggeredBy newWasTriggeredBy(WasTriggeredBy d) {\n WasTriggeredBy wtb=newWasTriggeredBy(d.getId(),\n d.getEffect(),\n d.getCause(),\n d.getAccount());\n wtb.setId(d.getId());\n wtb.getAnnotation().addAll(d.getAnnotation());\n return wtb;\n }\n\n\n\n public WasGeneratedBy newWasGeneratedBy(String id,\n ArtifactRef aid,\n Role role,\n ProcessRef pid,\n Collection<AccountRef> accounts) {\n WasGeneratedBy res=of.createWasGeneratedBy();\n res.setId(autoGenerateId(wasGenerateByIdPrefix,id));\n res.setCause(pid);\n res.setRole(role);\n res.setEffect(aid);\n addAccounts(res,accounts);\n return res;\n }\n\n public WasGeneratedByStar newWasGeneratedByStar(ArtifactRef aid,\n ProcessRef pid,\n Collection<AccountRef> accounts) {\n WasGeneratedByStar res=of.createWasGeneratedByStar();\n res.setCause(pid);\n res.setEffect(aid);\n addAccounts(res,accounts);\n return res;\n }\n public WasGeneratedBy newWasGeneratedBy(Artifact a,\n Role role,\n Process p,\n Collection<Account> accounts) {\n return newWasGeneratedBy(null,a,role,p,accounts);\n }\n\n public WasGeneratedBy newWasGeneratedBy(String id,\n Artifact a,\n Role role,\n Process p,\n Collection<Account> accounts) {\n ArtifactRef aid=newArtifactRef(a);\n ProcessRef pid=newProcessRef(p);\n LinkedList ll=new LinkedList();\n for (Account acc: accounts) {\n ll.add(newAccountRef(acc));\n }\n return newWasGeneratedBy(id,aid,role,pid,ll);\n }\n\n\n public WasGeneratedByStar newWasGeneratedByStar(Artifact a,\n Process p,\n Collection<Account> accounts) {\n ArtifactRef aid=newArtifactRef(a);\n ProcessRef pid=newProcessRef(p);\n LinkedList ll=new LinkedList();\n for (Account acc: accounts) {\n ll.add(newAccountRef(acc));\n }\n return newWasGeneratedByStar(aid,pid,ll);\n }\n\n\n\n public WasGeneratedBy newWasGeneratedBy(String id,\n Artifact a,\n Role role,\n Process p,\n String type,\n Collection<Account> accounts) {\n WasGeneratedBy wgb=newWasGeneratedBy(id,a,role,p,accounts);\n addAnnotation(wgb,of.createType(newType(type)));\n return wgb;\n }\n\n public WasControlledBy newWasControlledBy(ProcessRef pid,\n Role role,\n AgentRef agid,\n Collection<AccountRef> accounts) {\n return newWasControlledBy(null,pid,role,agid,accounts);\n }\n \n public WasControlledBy newWasControlledBy(String id,\n ProcessRef pid,\n Role role,\n AgentRef agid,\n Collection<AccountRef> accounts) {\n WasControlledBy res=of.createWasControlledBy();\n res.setId(autoGenerateId(wasControlledByIdPrefix,id));\n res.setEffect(pid);\n res.setRole(role);\n res.setCause(agid);\n addAccounts(res,accounts);\n return res;\n }\n\n\n public WasControlledBy newWasControlledBy(Process p,\n Role role,\n Agent ag,\n Collection<Account> accounts) {\n return newWasControlledBy(null,p,role,ag,accounts);\n }\n\n public WasControlledBy newWasControlledBy(String id,\n Process p,\n Role role,\n Agent ag,\n Collection<Account> accounts) {\n AgentRef agid=newAgentRef(ag);\n ProcessRef pid=newProcessRef(p);\n LinkedList ll=new LinkedList();\n for (Account acc: accounts) {\n ll.add(newAccountRef(acc));\n }\n return newWasControlledBy(id,pid,role,agid,ll);\n }\n\n public WasControlledBy newWasControlledBy(String id,\n Process p,\n Role role,\n Agent ag,\n String type,\n Collection<Account> accounts) {\n WasControlledBy wcb=newWasControlledBy(id,p,role,ag,accounts);\n addAnnotation(wcb,of.createType(newType(type)));\n return wcb;\n }\n\n\n public WasDerivedFrom newWasDerivedFrom(String id,\n ArtifactRef aid1,\n ArtifactRef aid2,\n Collection<AccountRef> accounts) {\n WasDerivedFrom res=of.createWasDerivedFrom();\n res.setId(autoGenerateId(wasDerivedFromIdPrefix,id));\n res.setCause(aid2);\n res.setEffect(aid1);\n addAccounts(res,accounts);\n return res;\n }\n\n public WasDerivedFromStar newWasDerivedFromStar(ArtifactRef aid1,\n ArtifactRef aid2,\n Collection<AccountRef> accounts) {\n WasDerivedFromStar res=of.createWasDerivedFromStar();\n res.setCause(aid2);\n res.setEffect(aid1);\n addAccounts(res,accounts);\n return res;\n }\n\n public WasDerivedFrom newWasDerivedFrom(Artifact a1,\n Artifact a2,\n Collection<Account> accounts) {\n return newWasDerivedFrom(null,a1,a2,accounts);\n }\n\n public WasDerivedFrom newWasDerivedFrom(String id,\n Artifact a1,\n Artifact a2,\n Collection<Account> accounts) {\n ArtifactRef aid1=newArtifactRef(a1);\n ArtifactRef aid2=newArtifactRef(a2);\n LinkedList ll=new LinkedList();\n for (Account acc: accounts) {\n ll.add(newAccountRef(acc));\n }\n return newWasDerivedFrom(id,aid1,aid2,ll);\n }\n\n public WasDerivedFromStar newWasDerivedFromStar(Artifact a1,\n Artifact a2,\n Collection<Account> accounts) {\n ArtifactRef aid1=newArtifactRef(a1);\n ArtifactRef aid2=newArtifactRef(a2);\n LinkedList ll=new LinkedList();\n for (Account acc: accounts) {\n ll.add(newAccountRef(acc));\n }\n return newWasDerivedFromStar(aid1,aid2,ll);\n }\n\n\n public WasDerivedFrom newWasDerivedFrom(String id,\n Artifact a1,\n Artifact a2,\n String type,\n Collection<Account> accounts) {\n WasDerivedFrom wdf=newWasDerivedFrom(id,a1,a2,accounts);\n addAnnotation(wdf,of.createType(newType(type)));\n return wdf;\n }\n\n\n\n public WasTriggeredBy newWasTriggeredBy(String id,\n ProcessRef pid1,\n ProcessRef pid2,\n Collection<AccountRef> accounts) {\n WasTriggeredBy res=of.createWasTriggeredBy();\n res.setId(autoGenerateId(wasTriggeredByIdPrefix,id));\n res.setEffect(pid1);\n res.setCause(pid2);\n addAccounts(res,accounts);\n return res;\n }\n\n public WasTriggeredByStar newWasTriggeredByStar(ProcessRef pid1,\n ProcessRef pid2,\n Collection<AccountRef> accounts) {\n WasTriggeredByStar res=of.createWasTriggeredByStar();\n res.setEffect(pid1);\n res.setCause(pid2);\n addAccounts(res,accounts);\n return res;\n }\n\n public WasTriggeredBy newWasTriggeredBy(Process p1,\n Process p2,\n Collection<Account> accounts) {\n return newWasTriggeredBy(null,p1,p2,accounts);\n }\n\n public WasTriggeredBy newWasTriggeredBy(String id,\n Process p1,\n Process p2,\n Collection<Account> accounts) {\n ProcessRef pid1=newProcessRef(p1);\n ProcessRef pid2=newProcessRef(p2);\n LinkedList<AccountRef> ll=new LinkedList();\n for (Account acc: accounts) {\n ll.add(newAccountRef(acc));\n }\n return newWasTriggeredBy(id,pid1,pid2,ll);\n }\n\n public WasTriggeredByStar newWasTriggeredByStar(Process p1,\n Process p2,\n Collection<Account> accounts) {\n ProcessRef pid1=newProcessRef(p1);\n ProcessRef pid2=newProcessRef(p2);\n LinkedList<AccountRef> ll=new LinkedList();\n for (Account acc: accounts) {\n ll.add(newAccountRef(acc));\n }\n return newWasTriggeredByStar(pid1,pid2,ll);\n }\n\n public WasTriggeredBy newWasTriggeredBy(String id,\n Process p1,\n Process p2,\n String type,\n Collection<Account> accounts) {\n WasTriggeredBy wtb=newWasTriggeredBy(p1,p2,accounts);\n wtb.setId(id);\n addAnnotation(wtb,of.createType(newType(type)));\n return wtb;\n }\n\n\n public EmbeddedAnnotation newEmbeddedAnnotation(String id,\n String property,\n Object value,\n Collection<Account> accs) {\n LinkedList<AccountRef> ll=new LinkedList();\n if (accs!=null) {\n for (Account acc: accs) {\n ll.add(newAccountRef(acc));\n }\n }\n return newEmbeddedAnnotation(id,property,value,ll,null);\n }\n\n public Annotation newAnnotation(String id,\n Artifact a,\n String property,\n Object value,\n Collection<Account> accs) {\n ArtifactRef aid=newArtifactRef(a);\n LinkedList<AccountRef> ll=new LinkedList();\n if (accs!=null) {\n for (Account acc: accs) {\n ll.add(newAccountRef(acc));\n }\n }\n return newAnnotation(id,aid,property,value,ll);\n }\n public Annotation newAnnotation(String id,\n Process p,\n String property,\n Object value,\n Collection<Account> accs) {\n ProcessRef pid=newProcessRef(p);\n LinkedList<AccountRef> ll=new LinkedList();\n if (accs!=null) {\n for (Account acc: accs) {\n ll.add(newAccountRef(acc));\n }\n }\n return newAnnotation(id,pid,property,value,ll);\n }\n\n public Annotation newAnnotation(String id,\n Annotation a,\n String property,\n Object value,\n Collection<Account> accs) {\n AnnotationRef aid=newAnnotationRef(a);\n LinkedList<AccountRef> ll=new LinkedList();\n if (accs!=null) {\n for (Account acc: accs) {\n ll.add(newAccountRef(acc));\n }\n }\n return newAnnotation(id,aid,property,value,ll);\n }\n\n public Annotation newAnnotation(String id,\n WasDerivedFrom edge,\n String property,\n Object value,\n Collection<Account> accs) {\n DependencyRef cid=newDependencyRef(edge);\n LinkedList<AccountRef> ll=new LinkedList();\n if (accs!=null) {\n for (Account acc: accs) {\n ll.add(newAccountRef(acc));\n }\n }\n return newAnnotation(id,cid,property,value,ll);\n }\n public Annotation newAnnotation(String id,\n Used edge,\n String property,\n Object value,\n Collection<Account> accs) {\n DependencyRef cid=newDependencyRef(edge);\n LinkedList<AccountRef> ll=new LinkedList();\n if (accs!=null) {\n for (Account acc: accs) {\n ll.add(newAccountRef(acc));\n }\n }\n return newAnnotation(id,cid,property,value,ll);\n }\n public Annotation newAnnotation(String id,\n WasGeneratedBy edge,\n String property,\n Object value,\n Collection<Account> accs) {\n DependencyRef cid=newDependencyRef(edge);\n LinkedList<AccountRef> ll=new LinkedList();\n if (accs!=null) {\n for (Account acc: accs) {\n ll.add(newAccountRef(acc));\n }\n }\n return newAnnotation(id,cid,property,value,ll);\n }\n public Annotation newAnnotation(String id,\n WasControlledBy edge,\n String property,\n Object value,\n Collection<Account> accs) {\n DependencyRef cid=newDependencyRef(edge);\n LinkedList<AccountRef> ll=new LinkedList();\n if (accs!=null) {\n for (Account acc: accs) {\n ll.add(newAccountRef(acc));\n }\n }\n return newAnnotation(id,cid,property,value,ll);\n }\n public Annotation newAnnotation(String id,\n WasTriggeredBy edge,\n String property,\n Object value,\n Collection<Account> accs) {\n DependencyRef cid=newDependencyRef(edge);\n LinkedList<AccountRef> ll=new LinkedList();\n if (accs!=null) {\n for (Account acc: accs) {\n ll.add(newAccountRef(acc));\n }\n }\n return newAnnotation(id,cid,property,value,ll);\n }\n\n public Annotation newAnnotation(String id,\n Role role,\n String property,\n Object value,\n Collection<Account> accs) {\n RoleRef rid=newRoleRef(role);\n LinkedList<AccountRef> ll=new LinkedList();\n if (accs!=null) {\n for (Account acc: accs) {\n ll.add(newAccountRef(acc));\n }\n }\n return newAnnotation(id,rid,property,value,ll);\n }\n\n public Property newProperty(String property,\n Object value) {\n Property res=of.createProperty();\n res.setKey(property);\n res.setValue(value);\n return res;\n }\n\n public Property newProperty(Property property) {\n return newProperty(property.getKey(),property.getValue());\n }\n\n\n public void addProperty(Annotation ann, Property p) {\n ann.getProperty().add(p);\n }\n\n public void addProperty(Annotation ann, List<Property> p) {\n ann.getProperty().addAll(p);\n }\n\n public void addProperty(EmbeddedAnnotation ann, Property p) {\n ann.getProperty().add(p);\n }\n\n public void addProperty(EmbeddedAnnotation ann, List<Property> p) {\n ann.getProperty().addAll(p);\n }\n\n public Annotation newAnnotation(String id,\n Ref ref,\n String property,\n Object value,\n Collection<AccountRef> accs) {\n Annotation res=of.createAnnotation();\n res.setId(id);\n res.setLocalSubject(ref.getRef());\n addProperty(res,newProperty(property,value));\n addAccounts(res,accs);\n return res;\n }\n\n public Annotation newAnnotation(String id,\n Object o,\n List<Property> properties,\n Collection<AccountRef> accs) {\n Annotation res=of.createAnnotation();\n res.setId(id);\n res.setLocalSubject(o);\n for (Property property: properties) {\n addProperty(res,property);\n }\n addAccounts(res,accs);\n return res;\n }\n\n public Annotation newAnnotation(Annotation ann) {\n Annotation res=newAnnotation(ann.getId(),\n ann.getLocalSubject(),\n ann.getProperty(),\n ann.getAccount());\n return res;\n }\n\n public EmbeddedAnnotation newEmbeddedAnnotation(String id,\n String property,\n Object value,\n Collection<AccountRef> accs,\n Object dummyParameterForAvoidingSameErasure) {\n EmbeddedAnnotation res=of.createEmbeddedAnnotation();\n res.setId(id);\n addProperty(res,newProperty(property,value));\n addAccounts(res,accs);\n return res;\n }\n public EmbeddedAnnotation newEmbeddedAnnotation(String id,\n List<Property> properties,\n Collection<AccountRef> accs,\n Object dummyParameterForAvoidingSameErasure) {\n EmbeddedAnnotation res=of.createEmbeddedAnnotation();\n res.setId(id);\n if (properties!=null) {\n addProperty(res,properties);\n }\n addAccounts(res,accs);\n return res;\n }\n\n\n public OPMGraph newOPMGraph(Collection<Account> accs,\n Collection<Overlaps> ops,\n Collection<Process> ps,\n Collection<Artifact> as,\n Collection<Agent> ags,\n Collection<Object> lks) {\n return newOPMGraph(null,accs,ops,ps,as,ags,lks,null);\n }\n\n public OPMGraph newOPMGraph(Collection<Account> accs,\n Collection<Overlaps> ops,\n Collection<Process> ps,\n Collection<Artifact> as,\n Collection<Agent> ags,\n Collection<Object> lks,\n Collection<Annotation> anns) {\n return newOPMGraph(null,accs,ops,ps,as,ags,lks,anns);\n }\n\n public OPMGraph newOPMGraph(String id,\n Collection<Account> accs,\n Collection<Overlaps> ops,\n Collection<Process> ps,\n Collection<Artifact> as,\n Collection<Agent> ags,\n Collection<Object> lks,\n Collection<Annotation> anns)\n {\n OPMGraph res=of.createOPMGraph();\n res.setId(autoGenerateId(opmGraphIdPrefix,id));\n if (accs!=null) {\n Accounts aaccs=of.createAccounts();\n aaccs.getAccount().addAll(accs);\n if (ops!=null) \n aaccs.getOverlaps().addAll(ops);\n res.setAccounts(aaccs);\n \n }\n if (ps!=null) {\n Processes pps=of.createProcesses();\n pps.getProcess().addAll(ps);\n res.setProcesses(pps);\n }\n if (as!=null) {\n Artifacts aas=of.createArtifacts();\n aas.getArtifact().addAll(as);\n res.setArtifacts(aas);\n }\n if (ags!=null) {\n Agents aags=of.createAgents();\n aags.getAgent().addAll(ags);\n res.setAgents(aags);\n }\n if (lks!=null) {\n Dependencies ccls=of.createDependencies();\n ccls.getUsedOrWasGeneratedByOrWasTriggeredBy().addAll(lks);\n res.setDependencies(ccls);\n }\n\n if (anns!=null) {\n Annotations l=of.createAnnotations();\n l.getAnnotation().addAll(anns);\n res.setAnnotations(l);\n }\n return res;\n }\n\n public OPMGraph newOPMGraph(Collection<Account> accs,\n Overlaps [] ovs,\n Process [] ps,\n Artifact [] as,\n Agent [] ags,\n Object [] lks) \n {\n\n return newOPMGraph(accs,\n ((ovs==null) ? null : Arrays.asList(ovs)),\n ((ps==null) ? null : Arrays.asList(ps)),\n ((as==null) ? null : Arrays.asList(as)),\n ((ags==null) ? null : Arrays.asList(ags)),\n ((lks==null) ? null : Arrays.asList(lks)));\n }\n public OPMGraph newOPMGraph(Collection<Account> accs,\n Overlaps [] ovs,\n Process [] ps,\n Artifact [] as,\n Agent [] ags,\n Object [] lks,\n Annotation [] anns) {\n return newOPMGraph(null,accs,ovs,ps,as,ags,lks,anns);\n }\n\n public OPMGraph newOPMGraph(String id,\n Collection<Account> accs,\n Overlaps [] ovs,\n Process [] ps,\n Artifact [] as,\n Agent [] ags,\n Object [] lks,\n Annotation [] anns) \n {\n\n return newOPMGraph(id,\n accs,\n ((ovs==null) ? null : Arrays.asList(ovs)),\n ((ps==null) ? null : Arrays.asList(ps)),\n ((as==null) ? null : Arrays.asList(as)),\n ((ags==null) ? null : Arrays.asList(ags)),\n ((lks==null) ? null : Arrays.asList(lks)),\n ((anns==null) ? null : Arrays.asList(anns)));\n }\n\n public OPMGraph newOPMGraph(Accounts accs,\n Processes ps,\n Artifacts as,\n Agents ags,\n Dependencies lks)\n {\n OPMGraph res=of.createOPMGraph();\n //res.setId(autoGenerateId(opmGraphIdPrefix));\n res.setAccounts(accs);\n res.setProcesses(ps);\n res.setArtifacts(as);\n res.setAgents(ags);\n res.setDependencies(lks);\n return res;\n }\n\n public OPMGraph newOPMGraph(Accounts accs,\n Processes ps,\n Artifacts as,\n Agents ags,\n Dependencies lks,\n Annotations anns)\n {\n OPMGraph res=of.createOPMGraph();\n //res.setId(autoGenerateId(opmGraphIdPrefix));\n res.setAccounts(accs);\n res.setProcesses(ps);\n res.setArtifacts(as);\n res.setAgents(ags);\n res.setDependencies(lks);\n res.setAnnotations(anns);\n return res;\n }\n\n public OPMGraph newOPMGraph(OPMGraph graph) {\n return newOPMGraph(graph.getAccounts(),\n graph.getProcesses(),\n graph.getArtifacts(),\n graph.getAgents(),\n graph.getDependencies(),\n graph.getAnnotations());\n }\n\n\n public Accounts newAccounts(Collection<Account> accs,\n Collection<Overlaps> ovlps) {\n Accounts res=of.createAccounts();\n if (accs!=null) {\n res.getAccount().addAll(accs);\n }\n if (ovlps!=null) {\n res.getOverlaps().addAll(ovlps);\n }\n return res;\n }\n\n// public Encoding newEncoding(String encoding) {\n// Encoding res=of.createEncoding();\n// res.setValue(encoding);\n// return res;\n// }\n// public String getEncoding(EmbeddedAnnotation annotation) {\n// if (annotation instanceof Encoding) {\n// Encoding encoding=(Encoding) annotation;\n// return encoding.getValue();\n// } else {\n// for (Property prop: annotation.getProperty()) {\n// if (prop.equals(ENCODING_PROPERTY)) {\n// return (String) prop.getValue();\n// }\n// }\n// return null;\n// }\n// }\n\n static {\n initBuilder();\n }\n static public DocumentBuilder builder;\n\n\tstatic void initBuilder() {\n\t\ttry {\n\t\t\tDocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();\n\t\t\tdocBuilderFactory.setNamespaceAware(true);\n\t\t\tbuilder = docBuilderFactory.newDocumentBuilder();\n\t\t} catch (ParserConfigurationException ex) {\n\t\t\tthrow new RuntimeException(ex);\n\t\t}\n\t}\n \n}", "public class OPMDeserialiser {\r\n\r\n\r\n\r\n // it is recommended by the Jaxb documentation that one JAXB\r\n // context is created for one application. This object is thread\r\n // safe (in the sun impelmenation, but not\r\n // marshallers/unmarshallers.\r\n\r\n static protected JAXBContext jc;\r\n\r\n public OPMDeserialiser () throws JAXBException {\r\n if (jc==null) \r\n jc = JAXBContext.newInstance( OPMFactory.packageList );\r\n // note, it is sometimes recommended to pass the current classloader\r\n \r\n }\r\n\r\n public OPMDeserialiser (String packageList) throws JAXBException {\r\n if (jc==null) \r\n jc = JAXBContext.newInstance(packageList);\r\n }\r\n\r\n\r\n private static ThreadLocal<OPMDeserialiser> threadDeserialiser=\r\n new ThreadLocal<OPMDeserialiser> () {\r\n protected synchronized OPMDeserialiser initialValue () {\r\n try {\r\n return new OPMDeserialiser();\r\n } catch (JAXBException jxb) {\r\n throw new RuntimeException(\"OPMDeserialiser: deserialiser init failure()\");\r\n }\r\n }\r\n };\r\n\r\n public static OPMDeserialiser getThreadOPMDeserialiser() {\r\n return threadDeserialiser.get();\r\n }\r\n\r\n public OPMGraph deserialiseOPMGraph (Element serialised)\r\n throws JAXBException {\r\n Unmarshaller u=jc.createUnmarshaller();\r\n JAXBElement<OPMGraph> root= u.unmarshal(serialised,OPMGraph.class);\r\n OPMGraph res=root.getValue();\r\n return res;\r\n }\r\n\r\n public OPMGraph deserialiseOPMGraph (File serialised)\r\n throws JAXBException {\r\n Unmarshaller u=jc.createUnmarshaller();\r\n Object root= u.unmarshal(serialised);\r\n OPMGraph res=(OPMGraph)((JAXBElement<OPMGraph>) root).getValue();\r\n return res;\r\n }\r\n\r\n\r\n public OPMGraph validateOPMGraph (String[] schemaFiles, File serialised)\r\n throws JAXBException,SAXException, IOException {\r\n SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);\r\n Source [] sources=new Source[2+schemaFiles.length];\r\n sources[0]=new StreamSource(this.getClass().getResourceAsStream(\"/\"+\"opm.1_1.xsd\"));\r\n int i=0;\r\n for (String schemaFile: schemaFiles) {\r\n sources[2+i]=new StreamSource(new File(schemaFile));\r\n i++;\r\n }\r\n Schema schema = sf.newSchema(sources); \r\n Unmarshaller u=jc.createUnmarshaller();\r\n //u.setValidating(true); was jaxb1.0\r\n u.setSchema(schema);\r\n Object root= u.unmarshal(serialised);\r\n OPMGraph res=(OPMGraph)((JAXBElement<OPMGraph>) root).getValue();\r\n return res;\r\n }\r\n\r\n public static void main(String [] args) {\r\n OPMDeserialiser deserial=OPMDeserialiser.getThreadOPMDeserialiser();\r\n if ((args==null) || (args.length==0)) {\r\n System.out.println(\"Usage: opmxml-validate <filename> {schemaFiles}*\");\r\n return;\r\n }\r\n File f=new File(args[0]);\r\n String [] schemas=new String[args.length-1];\r\n for (int i=1; i< args.length; i++) {\r\n schemas[i-1]=args[i];\r\n }\r\n try {\r\n deserial.validateOPMGraph(schemas,f);\r\n System.out.println(args[0] + \" IS a valid OPM graph\");\r\n return ;\r\n } catch (JAXBException je) {\r\n je.printStackTrace();\r\n System.out.println(args[0] + \" IS NOT a valid OPM graph\");\r\n } catch (SAXException je) {\r\n je.printStackTrace();\r\n System.out.println(args[0] + \" IS NOT a valid OPM graph\");\r\n } catch (IOException io) {\r\n io.printStackTrace();\r\n System.out.println(args[0] + \" IS NOT a valid OPM graph\");\r\n }\r\n }\r\n}\r", "public class OPMSerialiser {\r\n private ObjectFactory of=new ObjectFactory();\r\n\tstatic DocumentBuilder docBuilder;\r\n\r\n\r\n /** Note DocumentBuilderFactory is documented to be non thread safe. \r\n TODO: code analysis, of potential concurrency issues. */\r\n\tstatic void initBuilder() {\r\n\t\ttry {\r\n\t\t\tDocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();\r\n\t\t\tdocBuilderFactory.setNamespaceAware(true);\r\n\t\t\tdocBuilder = docBuilderFactory.newDocumentBuilder();\r\n\t\t} catch (ParserConfigurationException ex) {\r\n\t\t\tthrow new RuntimeException(ex);\r\n\t\t}\r\n\t}\r\n\r\n private static ThreadLocal<OPMSerialiser> threadSerialiser =\r\n new ThreadLocal<OPMSerialiser> () {\r\n protected synchronized OPMSerialiser initialValue () {\r\n try {\r\n return new OPMSerialiser();\r\n } catch (JAXBException jxb) {\r\n throw new RuntimeException(\"OPMSerialiser: serialiser init failure()\");\r\n }\r\n }\r\n };\r\n\r\n public static OPMSerialiser getThreadOPMSerialiser() {\r\n return threadSerialiser.get();\r\n }\r\n\r\n\r\n \r\n static {\r\n initBuilder();\r\n }\r\n protected JAXBContext jc;\r\n\r\n public static String defaultNamespace=\"http://example.com/\";\r\n\r\n protected final boolean usePrefixMapper;\r\n public OPMSerialiser () throws JAXBException {\r\n jc = JAXBContext.newInstance( OPMFactory.packageList );\r\n usePrefixMapper=true;\r\n }\r\n public OPMSerialiser (boolean usePrefixMapper) throws JAXBException {\r\n jc = JAXBContext.newInstance( OPMFactory.packageList );\r\n this.usePrefixMapper=usePrefixMapper;\r\n }\r\n\r\n public OPMSerialiser (String packageList) throws JAXBException {\r\n jc = JAXBContext.newInstance( packageList );\r\n usePrefixMapper=true;\r\n }\r\n public OPMSerialiser (boolean usePrefixMapper, String packageList) throws JAXBException {\r\n jc = JAXBContext.newInstance( packageList );\r\n this.usePrefixMapper=usePrefixMapper;\r\n }\r\n\r\n public void configurePrefixes(Marshaller m) throws PropertyException {\r\n if (usePrefixMapper) {\r\n m.setProperty(\"com.sun.xml.bind.namespacePrefixMapper\",\r\n new NamespacePrefixMapper(defaultNamespace));\r\n }\r\n }\r\n\r\n public Document serialiseOPMGraph (OPMGraph request) throws JAXBException {\r\n return (Document) serialiseOPMGraph (defaultEmptyDocument(), request);\r\n }\r\n \r\n public Node serialiseOPMGraph (Node addTo, OPMGraph graph)\r\n throws JAXBException {\r\n Marshaller m=jc.createMarshaller();\r\n m.marshal(of.createOpmGraph(graph),addTo);\r\n return addTo;\r\n }\r\n public String serialiseOPMGraph (StringWriter sw, OPMGraph graph)\r\n throws JAXBException {\r\n Marshaller m=jc.createMarshaller();\r\n m.marshal(of.createOpmGraph(graph),sw);\r\n return sw.toString();\r\n }\r\n\r\n public String serialiseOPMGraph (StringWriter sw, OPMGraph graph, boolean format)\r\n throws JAXBException {\r\n Marshaller m=jc.createMarshaller();\r\n m.setProperty(\"jaxb.formatted.output\",format);\r\n configurePrefixes(m);\r\n m.marshal(of.createOpmGraph(graph),sw);\r\n return sw.toString();\r\n }\r\n\r\n public void serialiseOPMGraph (File file, OPMGraph graph, boolean format)\r\n throws JAXBException {\r\n Marshaller m=jc.createMarshaller();\r\n m.setProperty(\"jaxb.formatted.output\",format);\r\n configurePrefixes(m);\r\n m.marshal(of.createOpmGraph(graph),file);\r\n }\r\n\r\n /** By default we use a document provided by the DocumentBuilder\r\n factory. If this functionality is required,\r\n PStructureSerialiser needs to be subclassed and the\r\n defaultEmptyDocument method overriden. */\r\n\r\n public Document defaultEmptyDocument () {\r\n return docBuilder.newDocument();\r\n }\r\n\r\n\r\n \r\n\r\n}\r", "public class OPMUtilities {\r\n\r\n private OPMFactory of=new OPMFactory();\r\n\r\n public List<Node> getNodes(OPMGraph g) {\r\n List<Node> res=new LinkedList();\r\n res.addAll(g.getArtifacts().getArtifact());\r\n res.addAll(g.getProcesses().getProcess());\r\n res.addAll(g.getAgents().getAgent());\r\n return res;\r\n }\r\n\r\n public List<Edge> getEdges(OPMGraph g) {\r\n List<Edge> res=new LinkedList();\r\n Dependencies dep=g.getDependencies();\r\n for (Object o:dep.getUsedOrWasGeneratedByOrWasTriggeredBy()) {\r\n res.add((Edge)o);\r\n }\r\n return res;\r\n }\r\n\r\n \r\n \r\n\r\n public OPMGraph union (OPMGraph g1, OPMGraph g2) {\r\n\r\n Accounts accs=union(g1.getAccounts(),g2.getAccounts());\r\n\r\n Processes ps=union(g1.getProcesses(),g2.getProcesses());\r\n\r\n Artifacts as=union(g1.getArtifacts(),g2.getArtifacts());\r\n\r\n Agents ags=union(g1.getAgents(),g2.getAgents());\r\n\r\n Dependencies lks=union(g1.getDependencies(),\r\n g2.getDependencies());\r\n\r\n OPMGraph g=of.newOPMGraph(accs,\r\n ps,\r\n as,\r\n ags,\r\n lks);\r\n return g;\r\n }\r\n\r\n public Accounts union (Accounts g1, Accounts g2) {\r\n Accounts res=of.newAccounts(null,null);\r\n if (g1.getAccount()!=null) {\r\n res.getAccount().addAll(g1.getAccount());\r\n }\r\n if (g2.getAccount()!=null) {\r\n res.getAccount().addAll(g2.getAccount());\r\n }\r\n if (g1.getOverlaps()!=null) {\r\n res.getOverlaps().addAll(g1.getOverlaps());\r\n }\r\n if (g2.getOverlaps()!=null) {\r\n res.getOverlaps().addAll(g2.getOverlaps());\r\n }\r\n return res;\r\n }\r\n\r\n public Agents union (Agents g1, Agents g2) {\r\n return null;\r\n }\r\n\r\n public Processes union (Processes g1, Processes g2) {\r\n return null;\r\n }\r\n\r\n public Artifacts union (Artifacts g1, Artifacts g2) {\r\n return null;\r\n }\r\n\r\n public Dependencies union (Dependencies g1, Dependencies g2) {\r\n return null;\r\n }\r\n\r\n /** Returns a graph with the same structure, in which the *\r\n effective membership of all nodes has been computed. The\r\n function returns an entirely new graph, without modifying the\r\n original. */\r\n \r\n public OPMGraph effectiveMembership (OPMGraph g) {\r\n Accounts accs=g.getAccounts();\r\n\r\n Processes ps=g.getProcesses();\r\n\r\n Artifacts as=g.getArtifacts();\r\n\r\n Agents ags=g.getAgents();\r\n\r\n Dependencies lks=g.getDependencies();\r\n\r\n OPMGraph g2=of.newOPMGraph(accs,\r\n ps,\r\n as,\r\n ags,\r\n lks);\r\n return g2;\r\n }\r\n\r\n public Accounts accountMembership (ArtifactRef aid, OPMGraph g) {\r\n return null;\r\n }\r\n\r\n public OPMGraph view (OPMGraph g, Accounts accs) {\r\n return g;\r\n }\r\n\r\n public boolean legalAccount (OPMGraph g) {\r\n return true;\r\n }\r\n\r\n public OPMGraph intersection (OPMGraph g1, OPMGraph g2) {\r\n return g1;\r\n }\r\n\r\n}\r", "public class CollectionFactory implements CollectionURIs {\n\n final private OPMFactory oFactory;\n\n public CollectionFactory(OPMFactory oFactory) {\n this.oFactory=oFactory;\n }\n \n\n// public WasDerivedFrom newContained(String id,\n// ArtifactRef aid1,\n// ArtifactRef aid2,\n// Collection<AccountRef> accounts) {\n// return oFactory.newWasDerivedFrom(id,aid1,aid2,CONTAINED,accounts);\n// }\n\n public WasDerivedFrom newContained(String id,\n Artifact a1,\n Artifact a2,\n Collection<Account> accounts) {\n return oFactory.newWasDerivedFrom(id,a1,a2,CONTAINED,accounts);\n }\n\n\n// public WasDerivedFrom newWasIdenticalTo(String id,\n// ArtifactRef aid1,\n// ArtifactRef aid2,\n// Collection<AccountRef> accounts) {\n// return oFactory.newWasDerivedFrom(id,aid1,aid2,WASIDENTICALTO,accounts);\n// }\n\n public WasDerivedFrom newWasIdenticalTo(String id,\n Artifact a1,\n Artifact a2,\n Collection<Account> accounts) {\n return oFactory.newWasDerivedFrom(id,a1,a2,WASIDENTICALTO,accounts);\n }\n\n\n\n\n\n}" ]
import java.io.File; import java.io.StringWriter; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; import javax.xml.bind.JAXBException; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.openprovenance.model.OPMGraph; import org.openprovenance.model.Edge; import org.openprovenance.model.Account; import org.openprovenance.model.Processes; import org.openprovenance.model.Artifact; import org.openprovenance.model.Agent; import org.openprovenance.model.Used; import org.openprovenance.model.OPMFactory; import org.openprovenance.model.WasGeneratedBy; import org.openprovenance.model.WasDerivedFrom; import org.openprovenance.model.WasTriggeredBy; import org.openprovenance.model.WasControlledBy; import org.openprovenance.model.OPMDeserialiser; import org.openprovenance.model.OPMSerialiser; import org.openprovenance.model.Overlaps; import org.openprovenance.model.Process; import org.openprovenance.model.OPMUtilities; import org.openprovenance.model.collections.CollectionFactory;
package org.openprovenance.rdf; /** * Unit test for simple App. */ public class Example5Test extends TestCase { /** * Create the test case * * @param testName name of the test case */ public Example5Test( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ static OPMGraph graph1; public void testCollectionProposal2() throws Exception { OPMFactory oFactory=new OPMFactory();
CollectionFactory cFactory=new CollectionFactory(oFactory);
5
OpsLabJPL/MarsImagesAndroid
MarsImages/Rajawali/src/main/java/rajawali/animation/mesh/AnimationSkeleton.java
[ "public class Camera extends ATransformable3D {\n\tprotected float[] mVMatrix = new float[16];\n\tprotected float[] mInvVMatrix = new float[16];\n\tprotected float[] mRotationMatrix = new float[16];\n\tprotected float[] mProjMatrix = new float[16];\n\tprotected float mNearPlane = 1.0f;\n\tprotected float mFarPlane = 120.0f;\n\tprotected float mFieldOfView = 45;\n\tprotected Number3D mUpAxis;\n\tprotected boolean mUseRotationMatrix = false;\n\tprotected float[] mRotateMatrixTmp = new float[16];\n\tprotected float[] mTmpMatrix = new float[16];\n\tprotected float[] mCombinedMatrix=new float[16];\n\tpublic Frustum mFrustum;\n\t\n\tprotected int mFogColor = 0xdddddd;\n\tprotected float mFogNear = 5;\n\tprotected float mFogFar = 25;\n\tprotected boolean mFogEnabled = false;\n\t\n\t// Camera's localized vectors\n\tprotected Number3D mRightVector;\n\tprotected Number3D mUpVector;\n\tprotected Number3D mLookVector;\n\t\n\tprotected Quaternion mLocalOrientation;\n\n\tpublic Camera() {\n\t\tsuper();\n\t\tmLocalOrientation = Quaternion.getIdentity();\n\t\tmUpAxis = new Number3D(0, 1, 0);\n\t\tmIsCamera = true;\n\t\tmFrustum = new Frustum();\n\t}\n\n\tpublic float[] getViewMatrix() {\n\t\tif (mLookAt != null) {\n\t\t\tMatrix.setLookAtM(mVMatrix, 0, mPosition.x, mPosition.y,\n\t\t\t\t\tmPosition.z, mLookAt.x, mLookAt.y, mLookAt.z, mUpAxis.x, mUpAxis.y,\n\t\t\t\t\tmUpAxis.z);\n\t\t\t\n\t\t\tmLocalOrientation.fromEuler(mRotation.y, mRotation.z, mRotation.x);\n\t\t\tmLocalOrientation.toRotationMatrix(mRotationMatrix);\n\t\t\tMatrix.multiplyMM(mVMatrix, 0, mRotationMatrix, 0, mVMatrix, 0);\n\t\t} else {\n\t\t\tif (mUseRotationMatrix == false && mRotationDirty) {\n\t\t\t\tsetOrientation();\n\t\t\t\tmOrientation.toRotationMatrix(mRotationMatrix);\n\t\t\t\tmRotationDirty = false;\n\t\t\t}\n\t\t\tMatrix.setIdentityM(mTmpMatrix, 0);\n\t\t\tMatrix.setIdentityM(mVMatrix, 0);\n\t\t\tMatrix.translateM(mTmpMatrix, 0, -mPosition.x, -mPosition.y, -mPosition.z);\n\t\t\tMatrix.multiplyMM(mVMatrix, 0, mRotationMatrix, 0, mTmpMatrix, 0);\n\t\t}\n\t\treturn mVMatrix;\n\t}\n\t\n\tpublic void updateFrustum(float[] pMatrix,float[] vMatrix) {\n\t\tMatrix.multiplyMM(mCombinedMatrix, 0, pMatrix, 0, vMatrix, 0);\n\t\tinvertM(mTmpMatrix, 0, mCombinedMatrix, 0);\n\t\tmFrustum.update(mCombinedMatrix);\n\t}\n\n\tprotected void rotateM(float[] m, int mOffset, float a, float x, float y,\n\t\t\tfloat z) {\n\t\tMatrix.setIdentityM(mRotateMatrixTmp, 0);\n\t\tMatrix.setRotateM(mRotateMatrixTmp, 0, a, x, y, z);\n\t\tSystem.arraycopy(m, 0, mTmpMatrix, 0, 16);\n\t\tMatrix.multiplyMM(m, mOffset, mTmpMatrix, mOffset, mRotateMatrixTmp, 0);\n\t}\n\n\tpublic void setRotationMatrix(float[] m) {\n\t\tmRotationMatrix = m;\n\t}\n\n\tpublic void setProjectionMatrix(int width, int height) {\n\t\tfloat ratio = (float) width / height;\n\t\tfloat frustumH = MathUtil.tan(getFieldOfView() / 360.0f * MathUtil.PI)\n\t\t\t\t* getNearPlane();\n\t\tfloat frustumW = frustumH * ratio;\n\n\t\tMatrix.frustumM(mProjMatrix, 0, -frustumW, frustumW, -frustumH,\n\t\t\t\tfrustumH, getNearPlane(), getFarPlane());\n\t}\n\t\n\t /**\n * Inverts a 4 x 4 matrix.\n *\n * @param mInv the array that holds the output inverted matrix\n * @param mInvOffset an offset into mInv where the inverted matrix is\n * stored.\n * @param m the input array\n * @param mOffset an offset into m where the matrix is stored.\n * @return true if the matrix could be inverted, false if it could not.\n */\n public static boolean invertM(float[] mInv, int mInvOffset, float[] m,\n int mOffset) {\n // Invert a 4 x 4 matrix using Cramer's Rule\n\n // transpose matrix\n final float src0 = m[mOffset + 0];\n final float src4 = m[mOffset + 1];\n final float src8 = m[mOffset + 2];\n final float src12 = m[mOffset + 3];\n\n final float src1 = m[mOffset + 4];\n final float src5 = m[mOffset + 5];\n final float src9 = m[mOffset + 6];\n final float src13 = m[mOffset + 7];\n\n final float src2 = m[mOffset + 8];\n final float src6 = m[mOffset + 9];\n final float src10 = m[mOffset + 10];\n final float src14 = m[mOffset + 11];\n\n final float src3 = m[mOffset + 12];\n final float src7 = m[mOffset + 13];\n final float src11 = m[mOffset + 14];\n final float src15 = m[mOffset + 15];\n\n // calculate pairs for first 8 elements (cofactors)\n final float atmp0 = src10 * src15;\n final float atmp1 = src11 * src14;\n final float atmp2 = src9 * src15;\n final float atmp3 = src11 * src13;\n final float atmp4 = src9 * src14;\n final float atmp5 = src10 * src13;\n final float atmp6 = src8 * src15;\n final float atmp7 = src11 * src12;\n final float atmp8 = src8 * src14;\n final float atmp9 = src10 * src12;\n final float atmp10 = src8 * src13;\n final float atmp11 = src9 * src12;\n\n // calculate first 8 elements (cofactors)\n final float dst0 = (atmp0 * src5 + atmp3 * src6 + atmp4 * src7)\n - (atmp1 * src5 + atmp2 * src6 + atmp5 * src7);\n final float dst1 = (atmp1 * src4 + atmp6 * src6 + atmp9 * src7)\n - (atmp0 * src4 + atmp7 * src6 + atmp8 * src7);\n final float dst2 = (atmp2 * src4 + atmp7 * src5 + atmp10 * src7)\n - (atmp3 * src4 + atmp6 * src5 + atmp11 * src7);\n final float dst3 = (atmp5 * src4 + atmp8 * src5 + atmp11 * src6)\n - (atmp4 * src4 + atmp9 * src5 + atmp10 * src6);\n final float dst4 = (atmp1 * src1 + atmp2 * src2 + atmp5 * src3)\n - (atmp0 * src1 + atmp3 * src2 + atmp4 * src3);\n final float dst5 = (atmp0 * src0 + atmp7 * src2 + atmp8 * src3)\n - (atmp1 * src0 + atmp6 * src2 + atmp9 * src3);\n final float dst6 = (atmp3 * src0 + atmp6 * src1 + atmp11 * src3)\n - (atmp2 * src0 + atmp7 * src1 + atmp10 * src3);\n final float dst7 = (atmp4 * src0 + atmp9 * src1 + atmp10 * src2)\n - (atmp5 * src0 + atmp8 * src1 + atmp11 * src2);\n\n // calculate pairs for second 8 elements (cofactors)\n final float btmp0 = src2 * src7;\n final float btmp1 = src3 * src6;\n final float btmp2 = src1 * src7;\n final float btmp3 = src3 * src5;\n final float btmp4 = src1 * src6;\n final float btmp5 = src2 * src5;\n final float btmp6 = src0 * src7;\n final float btmp7 = src3 * src4;\n final float btmp8 = src0 * src6;\n final float btmp9 = src2 * src4;\n final float btmp10 = src0 * src5;\n final float btmp11 = src1 * src4;\n\n // calculate second 8 elements (cofactors)\n final float dst8 = (btmp0 * src13 + btmp3 * src14 + btmp4 * src15)\n - (btmp1 * src13 + btmp2 * src14 + btmp5 * src15);\n final float dst9 = (btmp1 * src12 + btmp6 * src14 + btmp9 * src15)\n - (btmp0 * src12 + btmp7 * src14 + btmp8 * src15);\n final float dst10 = (btmp2 * src12 + btmp7 * src13 + btmp10 * src15)\n - (btmp3 * src12 + btmp6 * src13 + btmp11 * src15);\n final float dst11 = (btmp5 * src12 + btmp8 * src13 + btmp11 * src14)\n - (btmp4 * src12 + btmp9 * src13 + btmp10 * src14);\n final float dst12 = (btmp2 * src10 + btmp5 * src11 + btmp1 * src9 )\n - (btmp4 * src11 + btmp0 * src9 + btmp3 * src10);\n final float dst13 = (btmp8 * src11 + btmp0 * src8 + btmp7 * src10)\n - (btmp6 * src10 + btmp9 * src11 + btmp1 * src8 );\n final float dst14 = (btmp6 * src9 + btmp11 * src11 + btmp3 * src8 )\n - (btmp10 * src11 + btmp2 * src8 + btmp7 * src9 );\n final float dst15 = (btmp10 * src10 + btmp4 * src8 + btmp9 * src9 )\n - (btmp8 * src9 + btmp11 * src10 + btmp5 * src8 );\n\n // calculate determinant\n final float det =\n src0 * dst0 + src1 * dst1 + src2 * dst2 + src3 * dst3;\n\n if (det == 0.0f) {\n return false;\n }\n\n // calculate matrix inverse\n final float invdet = 1.0f / det;\n mInv[ mInvOffset] = dst0 * invdet;\n mInv[ 1 + mInvOffset] = dst1 * invdet;\n mInv[ 2 + mInvOffset] = dst2 * invdet;\n mInv[ 3 + mInvOffset] = dst3 * invdet;\n\n mInv[ 4 + mInvOffset] = dst4 * invdet;\n mInv[ 5 + mInvOffset] = dst5 * invdet;\n mInv[ 6 + mInvOffset] = dst6 * invdet;\n mInv[ 7 + mInvOffset] = dst7 * invdet;\n\n mInv[ 8 + mInvOffset] = dst8 * invdet;\n mInv[ 9 + mInvOffset] = dst9 * invdet;\n mInv[10 + mInvOffset] = dst10 * invdet;\n mInv[11 + mInvOffset] = dst11 * invdet;\n\n mInv[12 + mInvOffset] = dst12 * invdet;\n mInv[13 + mInvOffset] = dst13 * invdet;\n mInv[14 + mInvOffset] = dst14 * invdet;\n mInv[15 + mInvOffset] = dst15 * invdet;\n\n return true;\n }\n\n public void setUpAxis(float x, float y, float z) {\n \tmUpAxis.setAll(x, y, z);\n }\n \n public void setUpAxis(Number3D upAxis) {\n \tmUpAxis.setAllFrom(upAxis);\n }\n \n public void setUpAxis(Axis upAxis) {\n \tif(upAxis == Axis.X)\n \t\tmUpAxis.setAll(1, 0, 0);\n \telse if(upAxis == Axis.Y)\n \t\tmUpAxis.setAll(0, 1, 0);\n \telse\n \t\tmUpAxis.setAll(0, 0, 1);\n }\n \n\tpublic float[] getProjectionMatrix() {\n\t\treturn mProjMatrix;\n\t}\n\n\tpublic float getNearPlane() {\n\t\treturn mNearPlane;\n\t}\n\n\tpublic void setNearPlane(float nearPlane) {\n\t\tthis.mNearPlane = nearPlane;\n\t}\n\n\tpublic float getFarPlane() {\n\t\treturn mFarPlane;\n\t}\n\n\tpublic void setFarPlane(float farPlane) {\n\t\tthis.mFarPlane = farPlane;\n\t}\n\n\tpublic float getFieldOfView() {\n\t\treturn mFieldOfView;\n\t}\n\n\tpublic void setFieldOfView(float fieldOfView) {\n\t\tthis.mFieldOfView = fieldOfView;\n\t}\n\n\tpublic boolean getUseRotationMatrix() {\n\t\treturn mUseRotationMatrix;\n\t}\n\n\tpublic void setUseRotationMatrix(boolean useRotationMatrix) {\n\t\tthis.mUseRotationMatrix = useRotationMatrix;\n\t}\n\n\tpublic int getFogColor() {\n\t\treturn mFogColor;\n\t}\n\n\tpublic void setFogColor(int fogColor) {\n\t\tthis.mFogColor = fogColor;\n\t}\n\n\tpublic float getFogNear() {\n\t\treturn mFogNear;\n\t}\n\n\tpublic void setFogNear(float fogNear) {\n\t\tthis.mFogNear = fogNear;\n\t}\n\n\tpublic float getFogFar() {\n\t\treturn mFogFar;\n\t}\n\n\tpublic void setFogFar(float fogFar) {\n\t\tthis.mFogFar = fogFar;\n\t}\n\n\tpublic boolean isFogEnabled() {\n\t\treturn mFogEnabled;\n\t}\n\n\tpublic void setFogEnabled(boolean fogEnabled) {\n\t\tthis.mFogEnabled = fogEnabled;\n\t}\n}", "public enum BufferType {\n\tFLOAT_BUFFER,\n\tINT_BUFFER,\n\tSHORT_BUFFER\n}", "public class Number3D {\n\tpublic float x;\n\tpublic float y;\n\tpublic float z;\n\t\n\tpublic static final int M00 = 0;// 0;\n public static final int M01 = 4;// 1;\n public static final int M02 = 8;// 2;\n public static final int M03 = 12;// 3;\n public static final int M10 = 1;// 4;\n public static final int M11 = 5;// 5;\n public static final int M12 = 9;// 6;\n public static final int M13 = 13;// 7;\n public static final int M20 = 2;// 8;\n public static final int M21 = 6;// 9;\n public static final int M22 = 10;// 10;\n public static final int M23 = 14;// 11;\n public static final int M30 = 3;// 12;\n public static final int M31 = 7;// 13;\n public static final int M32 = 11;// 14;\n public static final int M33 = 15;// 15;\n\n\tprivate static Number3D _temp = new Number3D();\n\n\tpublic enum Axis {\n\t\tX, Y, Z\n\t}\n\n\tpublic Number3D() {\n\t\tthis.x = 0;\n\t\tthis.y = 0;\n\t\tthis.z = 0;\n\t}\n\n\tpublic Number3D(Number3D from) {\n\t\tthis.x = from.x;\n\t\tthis.y = from.y;\n\t\tthis.z = from.z;\n\t}\n\t\n\tpublic Number3D(String[] values) {\n\t\tif(values.length != 3) RajLog.e(\"Number3D should be initialized with 3 values\");\n\t\tthis.x = Float.parseFloat(values[0]);\n\t\tthis.y = Float.parseFloat(values[1]);\n\t\tthis.z = Float.parseFloat(values[2]);\n\t}\n\n\tpublic Number3D(float x, float y, float z) {\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t\tthis.z = z;\n\t}\n\n\tpublic Number3D(double x, double y, double z) {\n\t\tthis.x = (float) x;\n\t\tthis.y = (float) y;\n\t\tthis.z = (float) z;\n\t}\n\n\tpublic boolean equals(Number3D obj) {\n\t\treturn obj.x == this.x && obj.y == this.y && obj.z == this.z;\n\t}\n\n\tpublic void setAll(float x, float y, float z) {\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t\tthis.z = z;\n\t}\n\n\tpublic void setAll(double x, double y, double z) {\n\t\tthis.x = (float) x;\n\t\tthis.y = (float) y;\n\t\tthis.z = (float) z;\n\t}\n\t\n\tpublic void project(float[] mat){\n\t\t\t\n float l_w = x * mat[M30] + y * mat[M31] + z * mat[M32] + mat[M33];\n \n this.setAll(\n \t\t (x * mat[M00] + y * mat[M01] + z * mat[M02] + mat[M03]) / l_w, \n \t\t (x * mat[M10] + y * mat[M11] + z * mat[M12] + mat[M13]) / l_w, \n \t\t (x * mat[M20] + y * mat[M21] + z * mat[M22] + mat[M23]) / l_w);\n \n\t}\n\n\tpublic void setAllFrom(Number3D other) {\n\t\tthis.x = other.x;\n\t\tthis.y = other.y;\n\t\tthis.z = other.z;\n\t}\n\n\tpublic float normalize() {\n\t\tdouble mod = Math.sqrt(x * x + y * y + z * z);\n\n\t\tif (mod != 0 && mod != 1) {\n\t\t\tmod = 1 / mod;\n\t\t\tthis.x *= mod;\n\t\t\tthis.y *= mod;\n\t\t\tthis.z *= mod;\n\t\t}\n\t\t\n\t\treturn (float)mod;\n\t}\n\n\tpublic Number3D inverse() {\n\t\treturn new Number3D(-x, -y, -z);\n\t}\n\t\n\tpublic Number3D add(Number3D n) {\n\t\tthis.x += n.x;\n\t\tthis.y += n.y;\n\t\tthis.z += n.z;\n\t\treturn this;\n\t}\n\n\tpublic Number3D add(float x, float y, float z) {\n\t\tthis.x += x;\n\t\tthis.y += y;\n\t\tthis.z += z;\n\t\treturn this;\n\t}\n\n\tpublic Number3D subtract(Number3D n) {\n\t\tthis.x -= n.x;\n\t\tthis.y -= n.y;\n\t\tthis.z -= n.z;\n\t\treturn this;\n\t}\n\n\tpublic Number3D multiply(float f) {\n\t\tthis.x *= f;\n\t\tthis.y *= f;\n\t\tthis.z *= f;\n\t\treturn this;\n\t}\n\n\tpublic void multiply(Number3D n) {\n\t\tthis.x *= n.x;\n\t\tthis.y *= n.y;\n\t\tthis.z *= n.z;\n\t}\n\n\tpublic void multiply(final float[] matrix) {\n\t\tfloat vx = x, vy = y, vz = z;\n\t\tthis.x = vx * matrix[0] + vy * matrix[4] + vz * matrix[8] + matrix[12];\n\t\tthis.y = vx * matrix[1] + vy * matrix[5] + vz * matrix[9] + matrix[13];\n\t\tthis.z = vx * matrix[2] + vy * matrix[6] + vz * matrix[10] + matrix[14];\n\t}\n\n\tpublic float distanceTo(Number3D other) {\n\t\treturn (float)Math.sqrt((x - other.x) * (x - other.x) + (y - other.y) * (y - other.y) + (z - other.z) * (z - other.z));\n\t}\n\n\tpublic float length() {\n\t\treturn (float)Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);\n\t}\n\n\tpublic Number3D clone() {\n\t\treturn new Number3D(x, y, z);\n\t}\n\n\tpublic void rotateX(float angle) {\n\t\tdouble cosRY = Math.cos(angle);\n\t\tdouble sinRY = Math.sin(angle);\n\n\t\t_temp.setAll(this.x, this.y, this.z);\n\n\t\tthis.y = (float)((_temp.y * cosRY) - (_temp.z * sinRY));\n\t\tthis.z = (float)((_temp.y * sinRY) + (_temp.z * cosRY));\n\t}\n\n\tpublic void rotateY(float angle) {\n\t\tdouble cosRY = Math.cos(angle);\n\t\tdouble sinRY = Math.sin(angle);\n\n\t\t_temp.setAll(this.x, this.y, this.z);\n\n\t\tthis.x = (float)((_temp.x * cosRY) + (_temp.z * sinRY));\n\t\tthis.z = (float)((_temp.x * -sinRY) + (_temp.z * cosRY));\n\t}\n\n\tpublic void rotateZ(float angle) {\n\t\tdouble cosRY = Math.cos(angle);\n\t\tdouble sinRY = Math.sin(angle);\n\n\t\t_temp.setAll(this.x, this.y, this.z);\n\n\t\tthis.x = (float)((_temp.x * cosRY) - (_temp.y * sinRY));\n\t\tthis.y = (float)((_temp.x * sinRY) + (_temp.y * cosRY));\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tStringBuffer sb = new StringBuffer();\n\t\tsb.append(x);\n\t\tsb.append(\", \");\n\t\tsb.append(y);\n\t\tsb.append(\", \");\n\t\tsb.append(z);\n\t\treturn sb.toString();\n\t}\n\n\t//\n\n\tpublic static Number3D add(Number3D a, Number3D b) {\n\t\treturn new Number3D(a.x + b.x, a.y + b.y, a.z + b.z);\n\t}\n\n\tpublic static Number3D subtract(Number3D a, Number3D b) {\n\t\treturn new Number3D(a.x - b.x, a.y - b.y, a.z - b.z);\n\t}\n\n\tpublic static Number3D multiply(Number3D a, Number3D b) {\n\t\treturn new Number3D(a.x * b.x, a.y * b.y, a.z * b.z);\n\t}\n\n\tpublic static Number3D multiply(Number3D a, float b) {\n\t\treturn new Number3D(a.x * b, a.y * b, a.z * b);\n\t}\n\n\tpublic static Number3D cross(Number3D v, Number3D w) {\n\t\treturn new Number3D(w.y * v.z - w.z * v.y, w.z * v.x - w.x * v.z, w.x * v.y - w.y * v.x);\n\t}\n\t\n\tpublic Number3D cross(Number3D w) {\n\t\t_temp.setAllFrom(this);\n\t\tx = w.y * _temp.z - w.z * _temp.y;\n\t\ty = w.z * _temp.x - w.x * _temp.z;\n\t\tz = w.x * _temp.y - w.y * _temp.x;\n\t\treturn this;\n\t}\n\n\tpublic static float dot(Number3D v, Number3D w) {\n\t\treturn v.x * w.x + v.y * w.y + v.z * w.z;\n\t}\n\t\n\tpublic float dot(Number3D w) {\n\t\treturn x * w.x + y * w.y + z * w.z;\n\t}\n\n\tpublic static Number3D getAxisVector(Axis axis) {\n\t\tNumber3D axisVector = new Number3D();\n\n\t\tswitch (axis) {\n\t\tcase X:\n\t\t\taxisVector.setAll(1, 0, 0);\n\t\t\tbreak;\n\t\tcase Y:\n\t\t\taxisVector.setAll(0, 1, 0);\n\t\t\tbreak;\n\t\tcase Z:\n\t\t\taxisVector.setAll(0, 0, 1);\n\t\t\tbreak;\n\t\t}\n\n\t\treturn axisVector;\n\t}\n\n\t\n\t/**\n\t * http://ogre.sourcearchive.com/documentation/1.4.5/classOgre_1_1Vector3_eeef4472ad0c4d5f34a038a9f2faa819.html#eeef4472ad0c4d5f34a038a9f2faa819\n\t * \n\t * @param direction\n\t * @return\n\t */\n\tpublic Quaternion getRotationTo(Number3D direction) {\n\t\t// Based on Stan Melax's article in Game Programming Gems\n\t\tQuaternion q = new Quaternion();\n\t\t// Copy, since cannot modify local\n\t\tNumber3D v0 = this;\n\t\tNumber3D v1 = direction;\n\t\tv0.normalize();\n\t\tv1.normalize();\n\n\t\tfloat d = Number3D.dot(v0, v1);\n\t\t// If dot == 1, vectors are the same\n\t\tif (d >= 1.0f) {\n\t\t\tq.setIdentity();\n\t\t}\n\t\tif (d < 0.000001f - 1.0f) {\n\t\t\t// Generate an axis\n\t\t\tNumber3D axis = Number3D.cross(Number3D.getAxisVector(Axis.X), this);\n\t\t\tif (axis.length() == 0) // pick another if colinear\n\t\t\t\taxis = Number3D.cross(Number3D.getAxisVector(Axis.Y), this);\n\t\t\taxis.normalize();\n\t\t\tq.fromAngleAxis(MathUtil.radiansToDegrees(MathUtil.PI), axis);\n\t\t} else {\n\t\t\tdouble s = Math.sqrt((1 + d) * 2);\n\t\t\tdouble invs = 1f / s;\n\n\t\t\tNumber3D c = Number3D.cross(v0, v1);\n\n\t\t\tq.x = (float)(c.x * invs);\n\t\t\tq.y = (float)(c.y * invs);\n\t\t\tq.z = (float)(c.z * invs);\n\t\t\tq.w = (float)(s * 0.5);\n\t\t\tq.normalize();\n\t\t}\n\t\treturn q;\n\t}\n\t\n\tpublic static Number3D getUpVector() {\n\t\treturn new Number3D(0, 1, 0);\n\t}\n\t\n\tpublic static Number3D lerp(Number3D from, Number3D to, float amount)\n\t{\n\t\tNumber3D out = new Number3D();\n\t\tout.x = from.x + (to.x - from.x) * amount;\n\t\tout.y = from.y + (to.y - from.y) * amount;\n\t\tout.z = from.z + (to.z - from.z) * amount;\n\t\treturn out;\n\t}\n\t\n\t/**\n\t * Performs a linear interpolation between from and to by the specified amount.\n\t * The result will be stored in the current object which means that the current\n\t * x, y, z values will be overridden.\n\t * \n\t * @param from\n\t * @param to\n\t * @param amount\n\t */\n\tpublic void lerpSelf(Number3D from, Number3D to, float amount)\n\t{\n\t this.x = from.x + (to.x - from.x) * amount;\n\t this.y = from.y + (to.y - from.y) * amount;\n\t this.z = from.z + (to.z - from.z) * amount;\n\t}\n}", "public final class Quaternion {\n\tpublic final static float F_EPSILON = .001f;\n\tpublic float w, x, y, z;\n\tprivate Number3D mTmpVec1, mTmpVec2, mTmpVec3;\n\n\tpublic Quaternion() {\n\t\tsetIdentity();\n\t\tmTmpVec1 = new Number3D();\n\t\tmTmpVec2 = new Number3D();\n\t\tmTmpVec3 = new Number3D();\n\t}\n\n\tpublic Quaternion(float w, float x, float y, float z) {\n\t\tthis();\n\t\tthis.w = w;\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t\tthis.z = z;\n\t}\n\n\tpublic Quaternion(Quaternion other) {\n\t\tthis();\n\t\tthis.w = other.w;\n\t\tthis.x = other.x;\n\t\tthis.y = other.y;\n\t\tthis.z = other.z;\n\t}\n\t\n\tpublic void setAllFrom(Quaternion other) {\n\t\tthis.w = other.w;\n\t\tthis.x = other.x;\n\t\tthis.y = other.y;\n\t\tthis.z = other.z;\n\t}\n\t\n\tpublic Quaternion clone() {\n\t\treturn new Quaternion(w, x, y, z);\n\t}\n\t\n\tpublic void setAll(float w, float x, float y, float z) {\n\t\tthis.w = w;\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t\tthis.z = z;\n\t}\n\n\tpublic Quaternion fromAngleAxis(final float angle, final Axis axis) {\n\t\tfromAngleAxis(angle, Number3D.getAxisVector(axis));\n\t\treturn this;\n\t}\n\t\n\tpublic Quaternion fromAngleAxis(final float angle, final Number3D axisVector) {\n\t\taxisVector.normalize();\n\t\tfloat radian = MathUtil.degreesToRadians(angle);\n\t\tfloat halfAngle = radian * .5f;\n\t\tfloat halfAngleSin = (float)Math.sin(halfAngle);\n\t\tw = (float)Math.cos(halfAngle);\n\t\tx = halfAngleSin * axisVector.x;\n\t\ty = halfAngleSin * axisVector.y;\n\t\tz = halfAngleSin * axisVector.z;\n\t\t\n\t\treturn this;\n\t}\n\t\n\tpublic Quaternion fromEuler(final float heading, final float attitude, final float bank) {\n\t\tfloat x = MathUtil.degreesToRadians(heading);\n\t\tfloat y = MathUtil.degreesToRadians(attitude);\n\t\tfloat z = MathUtil.degreesToRadians(bank);\n\t\tfloat c1 = (float)Math.cos(x / 2);\n\t\tfloat s1 = (float)Math.sin(x / 2);\n\t\tfloat c2 = (float)Math.cos(y / 2);\n\t\tfloat s2 = (float)Math.sin(y / 2);\n\t\tfloat c3 = (float)Math.cos(z / 2);\n\t\tfloat s3 = (float)Math.sin(z / 2);\n\t\tfloat c1c2 = c1 * c2;\n\t\tfloat s1s2 = s1 * s2;\n\t\tthis.w = c1c2 * c3 - s1s2 * s3;\n\t\tthis.x = c1c2 * s3 + s1s2 * c3;\n\t\tthis.y = s1 * c2 * c3 + c1 * s2 * s3;\n\t\tthis.z = c1 * s2 * c3 - s1 * c2 * s3;\n\n\t\treturn this;\n\t}\n\t\n\tpublic void fromAxes(final Number3D xAxis, final Number3D yAxis, final Number3D zAxis)\n {\n float[] kRot = new float[16];\n\n kRot[0] = xAxis.x;\n kRot[4] = xAxis.y;\n kRot[8] = xAxis.z;\n\n kRot[1] = yAxis.x;\n kRot[5] = yAxis.y;\n kRot[9] = yAxis.z;\n\n kRot[2] = zAxis.x;\n kRot[6] = zAxis.y;\n kRot[10] = zAxis.z;\n\n fromRotationMatrix(kRot);\n }\n\n\tpublic AngleAxis toAngleAxis() {\n\t\treturn toAngleAxis(new AngleAxis());\n\t}\n\t\n\tpublic AngleAxis toAngleAxis(AngleAxis angleAxis) {\n\t\tfloat length = x * x + y * y + z * z;\n\t\tif (length > 0.0) {\n\t\t\tangleAxis.setAngle(MathUtil.radiansToDegrees(2.0f * (float) Math.acos(w)));\n\t\t\tfloat invLength = -(float)Math.sqrt(length);\n\t\t\tangleAxis.getAxis().x = x * invLength;\n\t\t\tangleAxis.getAxis().y = y * invLength;\n\t\t\tangleAxis.getAxis().z = z * invLength;\n\t\t} else {\n\t\t\tangleAxis.setAngle(0);\n\t\t\tangleAxis.getAxis().x = 1;\n\t\t\tangleAxis.getAxis().y = 0;\n\t\t\tangleAxis.getAxis().z = 0;\n\t\t}\n\t\t\n\t\treturn angleAxis;\n\t}\n\n\tpublic void fromRotationMatrix(final float[] rotMatrix) {\n\t\t// Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes\n\t\t// article \"Quaternion Calculus and Fast Animation\".\n\n\t\tfloat fTrace = rotMatrix[0] + rotMatrix[5] + rotMatrix[10];\n\t\tfloat fRoot;\n\n\t\tif (fTrace > 0.0) {\n\t\t\t// |w| > 1/2, may as well choose w > 1/2\n\t\t\tfRoot = (float)Math.sqrt(fTrace + 1.0f); // 2w\n\t\t\tw = 0.5f * fRoot;\n\t\t\tfRoot = 0.5f / fRoot; // 1/(4w)\n\t\t\tx = (rotMatrix[9] - rotMatrix[6]) * fRoot;\n\t\t\ty = (rotMatrix[2] - rotMatrix[8]) * fRoot;\n\t\t\tz = (rotMatrix[4] - rotMatrix[1]) * fRoot;\n\t\t} else {\n\t\t\t// |w| <= 1/2\n\t\t\tint[] s_iNext = new int[] { 1, 2, 0 };\n\t\t\tint i = 0;\n\t\t\tif (rotMatrix[5] > rotMatrix[0])\n\t\t\t\ti = 1;\n\t\t\tif (rotMatrix[10] > rotMatrix[(i * 4) + i])\n\t\t\t\ti = 2;\n\t\t\tint j = s_iNext[i];\n\t\t\tint k = s_iNext[j];\n\n\t\t\tfRoot = (float)Math.sqrt(rotMatrix[(i * 4) + i] - rotMatrix[(j * 4) + j] - rotMatrix[(k * 4) + k] + 1.0f);\n\t\t\tfloat apkQuat[] = new float[] { x, y, z };\n\t\t\tapkQuat[i] = 0.5f * fRoot;\n\t\t\tfRoot = 0.5f / fRoot;\n\t\t\tw = (rotMatrix[(k * 4) + j] - rotMatrix[(j * 4) + k]) * fRoot;\n\t\t\tapkQuat[j] = (rotMatrix[(j * 4) + i] + rotMatrix[(i * 4) + j]) * fRoot;\n\t\t\tapkQuat[k] = (rotMatrix[(k * 4) + i] + rotMatrix[(i * 4) + k]) * fRoot;\n\n\t\t\tx = apkQuat[0];\n\t\t\ty = apkQuat[1];\n\t\t\tz = apkQuat[2];\n\t\t}\n\t}\n\n\tpublic Number3D getXAxis() {\n\t\tfloat fTy = 2.0f * y;\n\t\tfloat fTz = 2.0f * z;\n\t\tfloat fTwy = fTy * w;\n\t\tfloat fTwz = fTz * w;\n\t\tfloat fTxy = fTy * x;\n\t\tfloat fTxz = fTz * x;\n\t\tfloat fTyy = fTy * y;\n\t\tfloat fTzz = fTz * z;\n\n\t\treturn new Number3D(1 - (fTyy + fTzz), fTxy + fTwz, fTxz - fTwy);\n\t}\n\n\tpublic Number3D getYAxis() {\n\t\tfloat fTx = 2.0f * x;\n\t\tfloat fTy = 2.0f * y;\n\t\tfloat fTz = 2.0f * z;\n\t\tfloat fTwx = fTx * w;\n\t\tfloat fTwz = fTz * w;\n\t\tfloat fTxx = fTx * x;\n\t\tfloat fTxy = fTy * x;\n\t\tfloat fTyz = fTz * y;\n\t\tfloat fTzz = fTz * z;\n\n\t\treturn new Number3D(fTxy - fTwz, 1 - (fTxx + fTzz), fTyz + fTwx);\n\t}\n\n\tpublic Number3D getZAxis() {\n\t\tfloat fTx = 2.0f * x;\n\t\tfloat fTy = 2.0f * y;\n\t\tfloat fTz = 2.0f * z;\n\t\tfloat fTwx = fTx * w;\n\t\tfloat fTwy = fTy * w;\n\t\tfloat fTxx = fTx * x;\n\t\tfloat fTxz = fTz * x;\n\t\tfloat fTyy = fTy * y;\n\t\tfloat fTyz = fTz * y;\n\n\t\treturn new Number3D(fTxz + fTwy, fTyz - fTwx, 1 - (fTxx + fTyy));\n\t}\n\n\tpublic void add(Quaternion other) {\n\t\tw += other.w;\n\t\tx += other.x;\n\t\ty += other.y;\n\t\tz += other.z;\n\t}\n\n\tpublic void subtract(Quaternion other) {\n\t\tw -= other.w;\n\t\tx -= other.x;\n\t\ty -= other.y;\n\t\tz -= other.z;\n\t}\n\n\tpublic void multiply(float scalar) {\n\t\tw *= scalar;\n\t\tx *= scalar;\n\t\ty *= scalar;\n\t\tz *= scalar;\n\t}\n\n\tpublic void multiply(Quaternion other) {\n\t\tfloat tW = w;\n\t\tfloat tX = x;\n\t\tfloat tY = y;\n\t\tfloat tZ = z;\n\n\t\tw = tW * other.w - tX * other.x - tY * other.y - tZ * other.z;\n\t\tx = tW * other.x + tX * other.w + tY * other.z - tZ * other.y;\n\t\ty = tW * other.y + tY * other.w + tZ * other.x - tX * other.z;\n\t\tz = tW * other.z + tZ * other.w + tX * other.y - tY * other.x;\n\t}\n\n\tpublic Number3D multiply(final Number3D vector) {\n\t\tmTmpVec3.setAll(x, y, z);\n\t\tmTmpVec1 = Number3D.cross(mTmpVec3, vector);\n\t\tmTmpVec2 = Number3D.cross(mTmpVec3, mTmpVec1);\n\t\tmTmpVec1.multiply(2.0f * w);\n\t\tmTmpVec2.multiply(2.0f);\n\n\t\tmTmpVec1.add(mTmpVec2);\n\t\tmTmpVec1.add(vector);\n\n\t\treturn mTmpVec1;\n\t}\n\n\tpublic float dot(Quaternion other) {\n\t\treturn w * other.w + x * other.x + y * other.y + z * other.z;\n\t}\n\n\tpublic float norm() {\n\t\treturn w * w + x * x + y * y + z * z;\n\t}\n\n\tpublic Quaternion inverse() {\n\t\tfloat norm = norm();\n\t\tif (norm > 0) {\n\t\t\tfloat invNorm = 1.0f / norm;\n\t\t\treturn new Quaternion(w * invNorm, -x * invNorm, -y * invNorm, -z * invNorm);\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\t\n\tpublic void inverseSelf() {\n\t\tfloat norm = norm();\n\t\tif (norm > 0) {\n\t\t\tfloat invNorm = 1.0f / norm;\n\t\t\tsetAll(w * invNorm, -x * invNorm, -y * invNorm, -z * invNorm);\n\t\t}\n\t}\n\n\tpublic Quaternion unitInverse() {\n\t\treturn new Quaternion(w, -x, -y, -z);\n\t}\n\n\tpublic Quaternion exp() {\n\t\tfloat angle = (float)Math.sqrt(x * x + y * y + z * z);\n\t\tfloat sin = (float)Math.sin(angle);\n\t\tQuaternion result = new Quaternion();\n\t\tresult.w = (float)Math.cos(angle);\n\n\t\tif (Math.abs(sin) >= F_EPSILON) {\n\t\t\tfloat coeff = sin / angle;\n\t\t\tresult.x = coeff * x;\n\t\t\tresult.y = coeff * y;\n\t\t\tresult.z = coeff * z;\n\t\t} else {\n\t\t\tresult.x = x;\n\t\t\tresult.y = y;\n\t\t\tresult.z = z;\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tpublic Quaternion log() {\n\t\tQuaternion result = new Quaternion();\n\t\tresult.w = 0;\n\n\t\tif (Math.abs(w) < 1.0) {\n\t\t\tfloat angle = (float) Math.acos(w);\n\t\t\tfloat sin = (float)Math.sin(angle);\n\t\t\tif (Math.abs(sin) >= F_EPSILON) {\n\t\t\t\tfloat fCoeff = angle / sin;\n\t\t\t\tresult.x = fCoeff * x;\n\t\t\t\tresult.y = fCoeff * y;\n\t\t\t\tresult.z = fCoeff * z;\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\n\t\tresult.x = x;\n\t\tresult.y = y;\n\t\tresult.z = z;\n\n\t\treturn result;\n\t}\n\n\tpublic boolean equals(final Quaternion rhs, final float tolerance) {\n\t\tfloat fCos = dot(rhs);\n\t\tfloat angle = (float) Math.acos(fCos);\n\n\t\treturn (Math.abs(angle) <= tolerance) || MathUtil.realEqual(angle, MathUtil.PI, tolerance);\n\t}\n\n\tpublic static Quaternion slerp(float fT, final Quaternion rkP, final Quaternion rkQ, boolean shortestPath) {\n\t\tfloat fCos = rkP.dot(rkQ);\n\t\tQuaternion rkT = new Quaternion();\n\n\t\tif (fCos < 0.0f && shortestPath) {\n\t\t\tfCos = -fCos;\n\t\t\trkT = rkQ.inverse();\n\t\t} else {\n\t\t\trkT = rkQ;\n\t\t}\n\n\t\tif (Math.abs(fCos) < 1 - F_EPSILON) {\n\t\t\t// Standard case (slerp)\n\t\t\tfloat fSin = (float)Math.sqrt(1 - fCos * fCos);\n\t\t\tfloat fAngle = (float) Math.atan2(fSin, fCos);\n\t\t\tfloat fInvSin = 1.0f / fSin;\n\t\t\tfloat fCoeff0 = (float)Math.sin((1.0f - fT) * fAngle) * fInvSin;\n\t\t\tfloat fCoeff1 = (float)Math.sin(fT * fAngle) * fInvSin;\n\t\t\tQuaternion result = new Quaternion(rkP);\n\t\t\tQuaternion tmp = new Quaternion(rkT);\n\t\t\tresult.multiply(fCoeff0);\n\t\t\ttmp.multiply(fCoeff1);\n\t\t\tresult.add(tmp);\n\t\t\treturn result;\n\t\t} else {\n\t\t\t// There are two situations:\n\t\t\t// 1. \"rkP\" and \"rkQ\" are very close (fCos ~= +1), so we can do a\n\t\t\t// linear\n\t\t\t// interpolation safely.\n\t\t\t// 2. \"rkP\" and \"rkQ\" are almost inverse of each other (fCos ~= -1),\n\t\t\t// there\n\t\t\t// are an infinite number of possibilities interpolation. but we\n\t\t\t// haven't\n\t\t\t// have method to fix this case, so just use linear interpolation\n\t\t\t// here.\n\t\t\tQuaternion result = new Quaternion(rkP);\n\t\t\tQuaternion tmp = new Quaternion(rkT);\n\t\t\tresult.multiply(1.0f - fT);\n\t\t\ttmp.multiply(fT);\n\t\t\tresult.add(tmp);\n\t\t\t// taking the complement requires renormalisation\n\t\t\tresult.normalize();\n\t\t\treturn result;\n\t\t}\n\t}\n\n\tpublic Quaternion slerpExtraSpins(float fT, final Quaternion rkP, final Quaternion rkQ, int iExtraSpins) {\n\t\tfloat fCos = rkP.dot(rkQ);\n\t\tfloat fAngle = (float) Math.acos(fCos);\n\n\t\tif (Math.abs(fAngle) < F_EPSILON)\n\t\t\treturn rkP;\n\n\t\tfloat fSin = (float)Math.sin(fAngle);\n\t\tfloat fPhase = MathUtil.PI * iExtraSpins * fT;\n\t\tfloat fInvSin = 1.0f / fSin;\n\t\tfloat fCoeff0 = (float)Math.sin((1.0f - fT) * fAngle - fPhase) * fInvSin;\n\t\tfloat fCoeff1 = (float)Math.sin(fT * fAngle + fPhase) * fInvSin;\n\t\tQuaternion result = new Quaternion(rkP);\n\t\tQuaternion tmp = new Quaternion(rkQ);\n\t\tresult.multiply(fCoeff0);\n\t\ttmp.multiply(fCoeff1);\n\t\tresult.add(tmp);\n\t\treturn result;\n\t}\n\n\tpublic float normalize() {\n\t\tfloat len = norm();\n\t\tfloat factor = 1.0f / (float)Math.sqrt(len);\n\t\tmultiply(factor);\n\t\treturn len;\n\t}\n\n\tpublic float getRoll(boolean reprojectAxis) {\n\t\tif (reprojectAxis) {\n\t\t\t// float fTx = 2.0f * x;\n\t\t\tfloat fTy = 2.0f * y;\n\t\t\tfloat fTz = 2.0f * z;\n\t\t\tfloat fTwz = fTz * w;\n\t\t\tfloat fTxy = fTy * x;\n\t\t\tfloat fTyy = fTy * y;\n\t\t\tfloat fTzz = fTz * z;\n\n\t\t\treturn (float) Math.atan2(fTxy + fTwz, 1.0 - (fTyy + fTzz));\n\t\t} else {\n\t\t\treturn (float) Math.atan2(2 * (x * y + w * z), w * w + x * x - y * y - z * z);\n\t\t}\n\t}\n\n\tpublic float getPitch(boolean reprojectAxis) {\n\t\tif (reprojectAxis) {\n\t\t\tfloat fTx = 2.0f * x;\n\t\t\t// float fTy = 2.0f * y;\n\t\t\tfloat fTz = 2.0f * z;\n\t\t\tfloat fTwx = fTx * w;\n\t\t\tfloat fTxx = fTx * x;\n\t\t\tfloat fTyz = fTz * y;\n\t\t\tfloat fTzz = fTz * z;\n\n\t\t\treturn (float) Math.atan2(fTyz + fTwx, 1.0 - (fTxx + fTzz));\n\t\t} else {\n\t\t\treturn (float) Math.atan2(2 * (y * z + w * x), w * w - x * x - y * y + z * z);\n\t\t}\n\t}\n\n\tpublic float getYaw(boolean reprojectAxis) {\n\t\tif (reprojectAxis) {\n\t\t\tfloat fTx = 2.0f * x;\n\t\t\tfloat fTy = 2.0f * y;\n\t\t\tfloat fTz = 2.0f * z;\n\t\t\tfloat fTwy = fTy * w;\n\t\t\tfloat fTxx = fTx * x;\n\t\t\tfloat fTxz = fTz * x;\n\t\t\tfloat fTyy = fTy * y;\n\n\t\t\treturn (float) Math.atan2(fTxz + fTwy, 1.0 - (fTxx + fTyy));\n\n\t\t} else {\n\t\t\treturn (float) Math.asin(-2 * (x * z - w * y));\n\t\t}\n\t}\n\t\n\tpublic Matrix4 toRotationMatrix() {\n\t\tMatrix4 matrix = new Matrix4();\n\t\ttoRotationMatrix(matrix);\n\t\treturn matrix;\n\t}\n\n\tpublic void toRotationMatrix(Matrix4 matrix) {\n\t\tfloat[] m = new float[16];\n\t\ttoRotationMatrix(m);\n\t\tmatrix.set(m);\n\t}\n\t\n\tpublic void toRotationMatrix(float[] matrix) {\n\t\tfloat x2 = x * x;\n\t\tfloat y2 = y * y;\n\t\tfloat z2 = z * z;\n\t\tfloat xy = x * y;\n\t\tfloat xz = x * z;\n\t\tfloat yz = y * z;\n\t\tfloat wx = w * x;\n\t\tfloat wy = w * y;\n\t\tfloat wz = w * z;\n\n\t\tmatrix[0] = 1.0f - 2.0f * (y2 + z2);\n\t\tmatrix[1] = 2.0f * (xy - wz);\n\t\tmatrix[2] = 2.0f * (xz + wy);\n\t\tmatrix[3] = 0;\n\n\t\tmatrix[4] = 2.0f * (xy + wz);\n\t\tmatrix[5] = 1.0f - 2.0f * (x2 + z2);\n\t\tmatrix[6] = 2.0f * (yz - wx);\n\t\tmatrix[7] = 0;\n\n\t\tmatrix[8] = 2.0f * (xz - wy);\n\t\tmatrix[9] = 2.0f * (yz + wx);\n\t\tmatrix[10] = 1.0f - 2.0f * (x2 + y2);\n\t\tmatrix[11] = 0;\n\n\t\tmatrix[12] = 0;\n\t\tmatrix[13] = 0;\n\t\tmatrix[14] = 0;\n\t\tmatrix[15] = 1;\n\t}\n\n\tpublic void computeW()\n\t{\n\t float t = 1.0f - ( x * x ) - ( y * y ) - ( z * z );\n\t if ( t < 0.0f )\n\t {\n\t w = 0.0f;\n\t }\n\t else\n\t {\n\t w = -(float)Math.sqrt(t);\n\t }\n\t}\n\t\n\tpublic Quaternion nlerp(float fT, final Quaternion rkP, final Quaternion rkQ, boolean shortestPath) {\n\t\tQuaternion result = new Quaternion(rkP);\n\t\tQuaternion tmp = new Quaternion(rkQ);\n\t\tfloat fCos = result.dot(tmp);\n\t\tif (fCos < 0.0f && shortestPath) {\n\t\t\ttmp = tmp.inverse();\n\t\t\ttmp.subtract(result);\n\t\t\ttmp.multiply(fT);\n\t\t\tresult.add(tmp);\n\t\t} else {\n\t\t\ttmp.subtract(result);\n\t\t\ttmp.multiply(fT);\n\t\t\tresult.add(tmp);\n\t\t}\n\t\tresult.normalize();\n\t\treturn result;\n\t}\n\n\tpublic Quaternion setIdentity() {\n\t\tw = 1;\n\t\tx = 0;\n\t\ty = 0;\n\t\tz = 0;\n\t\treturn this;\n\t}\n\n\tpublic static Quaternion getIdentity() {\n\t\treturn new Quaternion(1, 0, 0, 0);\n\t}\n\n\tpublic String toString() {\n\t\treturn \"Quaternion.w \" + w + \" .x: \" + x + \" .y: \" + y + \" .z: \" + z;\n\t}\n\t\n\tpublic static Quaternion getRotationTo(final Number3D src, final Number3D dest)\n {\n Quaternion q = new Quaternion();\n Number3D v1 = new Number3D(src);\n Number3D v2 = new Number3D(dest);\n v1.normalize();\n v2.normalize();\n\n float d = Number3D.dot(v1, v2);\n\n if (d >= 1.0f)\n {\n return new Quaternion().setIdentity();\n }\n\n if (d < (1e-6f - 1.0f))\n {\n // // Generate an axis\n // Number3D axis = Number3D::UNIT_X.crossProduct(*this);\n // if (axis.isZeroLength()) // pick another if colinear\n // axis = Number3D::UNIT_Y.crossProduct(*this);\n // axis.normalise();\n // q.FromAngleAxis(Radian(Math::PI), axis);\n\n // Generate an axis\n Number3D axis = Number3D.cross(Number3D.getAxisVector(Axis.X), v1);\n\n if (axis.length() == 0.0f)\n {\n axis = Number3D.cross(Number3D.getAxisVector(Axis.Y), v1);\n }\n\n axis.normalize();\n\n q.fromAngleAxis(180, axis);\n }\n else\n {\n // Real s = Math::Sqrt( (1+d)*2 );\n // Real invs = 1 / s;\n\n // Number3D c = v0.crossProduct(v1);\n\n // q.x = c.x * invs;\n // q.y = c.y * invs;\n // q.z = c.z * invs;\n // q.w = s * 0.5;\n // q.normalise();\n\n float s = (float)Math.sqrt((1f + d) * 2f);\n float invs = 1 / s;\n\n Number3D c = Number3D.cross(v1, v2);\n\n q.x = (float) (c.x * invs);\n q.y = (float) (c.y * invs);\n q.z = (float) (c.z * invs);\n q.w = (float) (s * 0.5f);\n q.normalize();\n } \n\n return q;\n }\n}", "public class BufferUtil {\n\tstatic\n\t{\n\t\tSystem.loadLibrary(\"bufferutil\");\n\t}\n\t\n\tnative public static void copyJni(float[] src, Buffer dst, int numFloats, int offset);\n\t\n\tpublic static void copy(float[] src, Buffer dst, int numFloats, int offset) {\n\t\tcopyJni(src, dst, numFloats, offset);\n\t\tdst.position(0);\n\t\t\n\t\tif(dst instanceof ByteBuffer)\n\t\t\tdst.limit(numFloats << 2);\n\t\telse if(dst instanceof FloatBuffer)\n\t\t\tdst.limit(numFloats);\n\n\t}\n}", "public class ColorPickerInfo {\n\n\tprivate float mX;\n\tprivate float mY;\n\tprivate ObjectColorPicker mPicker;\n\tprivate ByteBuffer mColorPickerBuffer;\n\n\tpublic ColorPickerInfo(float x, float y, ObjectColorPicker picker) {\n\t\tmX = x;\n\t\tmY = y;\n\t\tmPicker = picker;\n\t}\n\n\tpublic ObjectColorPicker getPicker() {\n\t\treturn mPicker;\n\t}\n\n\tpublic float getX() {\n\t\treturn mX;\n\t}\n\n\tpublic float getY() {\n\t\treturn mY;\n\t}\n\n\tpublic void setColorPickerBuffer(ByteBuffer buffer) {\n\t\tmColorPickerBuffer = buffer;\n\t}\n\n\tpublic ByteBuffer getColorPickerBuffer() {\n\t\treturn mColorPickerBuffer;\n\t}\n}" ]
import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import rajawali.BufferInfo; import rajawali.Camera; import rajawali.Geometry3D.BufferType; import rajawali.math.Number3D; import rajawali.math.Quaternion; import rajawali.util.BufferUtil; import rajawali.util.ObjectColorPicker.ColorPickerInfo; import rajawali.util.RajLog; import android.opengl.GLES20; import android.opengl.Matrix; import android.os.SystemClock;
package rajawali.animation.mesh; public class AnimationSkeleton extends AAnimationObject3D { public static final int FLOAT_SIZE_BYTES = 4; private SkeletonJoint[] mJoints; private BoneAnimationSequence mSequence; public float[][] mInverseBindPoseMatrix; public float[] uBoneMatrix; public BufferInfo mBoneMatricesBufferInfo = new BufferInfo(); /** * FloatBuffer containing joint transformation matrices */ protected FloatBuffer mBoneMatrices; public AnimationSkeleton() { } public void setJoints(SkeletonJoint[] joints) { mJoints = joints; if (mBoneMatrices == null) { if (mBoneMatrices != null) { mBoneMatrices.clear(); } mBoneMatrices = ByteBuffer .allocateDirect(joints.length * FLOAT_SIZE_BYTES * 16) .order(ByteOrder.nativeOrder()).asFloatBuffer(); BufferUtil.copy(uBoneMatrix, mBoneMatrices, uBoneMatrix.length, 0); mBoneMatrices.position(0); } else { BufferUtil.copy(uBoneMatrix, mBoneMatrices, uBoneMatrix.length, 0); }
mGeometry.createBuffer(mBoneMatricesBufferInfo, BufferType.FLOAT_BUFFER, mBoneMatrices, GLES20.GL_ARRAY_BUFFER);
1
Tyde/TuCanMobile
app/src/main/java/com/dalthed/tucan/acraload/LoadAcraResults.java
[ "public class AnswerObject {\n\tprivate String HTML_text;\n\tprivate String redirectURL;\n\tprivate String lastcalledURL;\n\tprivate CookieManager Cookies;\n\t/**\n\t * RückgabeObjekt der BrowseMethods\n\t * @param HTML HTML-Code\n\t * @param redirect Redirect-URL aus dem HTTP-Header\n\t * @param myCookies CookieManager mit relevanten Cookies\n\t * @param lastcalledURL Zuletzt aufgerufene URL\n\t */\n\tpublic AnswerObject(String HTML,String redirect,CookieManager myCookies,String lastcalledURL){\n\t\tthis.HTML_text=HTML;\n\t\tthis.redirectURL=redirect;\n\t\tthis.Cookies=myCookies;\n\t\tthis.lastcalledURL=lastcalledURL;\n\t}\n\tpublic String getHTML(){\n\t\treturn this.HTML_text;\n\t}\n\tpublic String getRedirectURLString() {\n\t\treturn this.redirectURL;\n\t}\n\tpublic String getLastCalledURL() {\n\t\treturn this.lastcalledURL;\n\t}\n\tpublic CookieManager getCookieManager() {\n\t\treturn this.Cookies;\n\t}\n\t\n}", "public class CookieManager {\n\n\tprivate Map<String, Map<String, String>> Cookies;\n\tprivate static final String LOG_TAG = \"TuCanMobile\";\n\n\t/**\n\t * Der CookieManager speichert empfangene Cookies ab und gibt sie auch\n\t * wieder aus <br>\n\t * <br>\n\t * Erzeugt einen leeren {@link CookieManager}\n\t */\n\tpublic CookieManager() {\n\t\tCookies = new HashMap<String, Map<String, String>>();\n\t}\n\n\t/**\n\t * fügt ein neues Cookie hinzu\n\t * \n\t * @param domain\n\t * Die Domain, auf welche der Cookie registriert werden soll\n\t * @param name\n\t * Cookie-Name\n\t * @param value\n\t * Cookie-Wert\n\t */\n\tpublic void inputCookie(String domain, String name, String value) {\n\t\tif (Cookies.get(domain) == null) {\n\t\t\tMap<String, String> DomainMap = new HashMap<String, String>();\n\t\t\tCookies.put(domain, DomainMap);\n\t\t\tLog.i(LOG_TAG, \"Domain in Storage registriert: \" + domain);\n\t\t}\n\t\tMap<String, String> DomainMap = Cookies.get(domain);\n\t\tDomainMap.put(name, value);\n\t\tLog.i(LOG_TAG, \"Cookie in Storage (\" + domain + \") aufgenommen: \" + name + \" = \" + value);\n\t}\n\n\t/**\n\t * Prüft ob die angegeben Domain schon Cookies gespeichert hat\n\t * \n\t * @param domain\n\t * die zu prüfende Domain\n\t * @return <code>true</code>, wenn schon ein Cookie unter dieser Domain\n\t * eingespeichert wurde, <code>false</code> anderenfalls\n\t */\n\tpublic boolean domain_exists(String domain) {\n\t\tif (Cookies.get(domain) == null)\n\t\t\treturn false;\n\t\telse\n\t\t\treturn true;\n\t}\n\n\t/**\n\t * Gibt die unter der angegebenen URL gespeicherten Cookies als zum Header passenden HTTP-String an.\n\t * @param domain Die Domain, von welcher die Cookies abgefragt werden sollen\n\t * @return HTTP-Header-Cookie-String\n\t */\n\tpublic String getCookieHTTPString(String domain) {\n\t\tif (!Cookies.containsKey(domain))\n\t\t\treturn null;\n\n\t\tString[] HTTPString = new String[Cookies.get(domain).size()];\n\t\tIterator<Entry<String,String>> it = Cookies.get(domain).entrySet().iterator();\n\t\tint i = 0;\n\t\twhile (it.hasNext()) {\n\t\t\tEntry<String,String> pairs = it.next();\n\t\t\tHTTPString[i] = pairs.getKey() + \"=\" + pairs.getValue();\n\t\t\ti++;\n\t\t}\n\t\tif (HTTPString.length == 0)\n\t\t\treturn \"\";\n\n\t\tString glue = \";\";\n\t\tStringBuilder sb = new StringBuilder();\n\t\tfor (String s : HTTPString) {\n\t\t\tsb.append(s).append(glue);\n\t\t}\n\t\treturn sb.substring(0, sb.length() - glue.length());\n\n\t}\n\t/**\n\t * Speichert die Cookies aus einem HTTP-HEADER-COOKIE String ab\n\t * @param host Domain auf welche die Cookies gespeichert werden sollen\n\t * @param HTTPString HTTP-Header-Cookie String\n\t */\n\tpublic void generateManagerfromHTTPString(String host, String HTTPString) {\n\t\tif (HTTPString != null) {\n\t\t\tString[] multipleCookies = HTTPString.split(\";\\\\s*\");\n\t\t\tfor (String ccy : multipleCookies) {\n\t\t\t\tString[] eachVal = ccy.split(\"=\");\n\t\t\t\tif (eachVal.length == 2)\n\t\t\t\t\tinputCookie(host, eachVal[0], eachVal[1]);\n\t\t\t\telse\n\t\t\t\t\tinputCookie(host, eachVal[0], null);\n\t\t\t}\n\t\t}\n\t}\n}", "public class RequestObject {\n\tprivate URL RequestURL;\n\tprivate CookieManager RequestCookies;\n\tprivate String RequestMethod;\n\tprivate String RequestpostData;\n\tprivate boolean redirectNecessary ;\n\t/**\n\t * HTTP-Methode GET\n\t */\n\tfinal public static String METHOD_GET = \"GET\";\n\t/**\n\t * HTTP-Methode POST\n\t */\n\tfinal public static String METHOD_POST = \"POST\";\n\n\tprivate static final String LOG_TAG = \"TuCanMobile\";\n\n\t/**\n\t * Objekt, welches alle notwendigen Informationen für einen\n\t * <code>HTTP</code>/<code>HTTPS</code>-Request enthält\n\t * \n\t * @param RequestString\n\t * URL(als String), welche aufgerufen werden soll\n\t * @param RequestCookiemanager\n\t * {@link CookieManager}, welcher die notwendigen Cookies\n\t * enthalten soll\n\t * @param method\n\t * Entweder {@link #METHOD_GET} oder {@link #METHOD_POST}\n\t * @param postdata\n\t * Daten, welche bei {@link #METHOD_POST} mitgesendert werden\n\t * können\n\t * @author Daniel Thiem\n\t */\n\tpublic RequestObject(String RequestString, CookieManager RequestCookiemanager, String method,\n\t\t\tString postdata, boolean redirectNecessary) {\n\t\ttry {\n\t\t\tthis.RequestURL = new URL(RequestString);\n\t\t\t// Log.i(LOG_TAG,\"Hier haste die URL:\"+RequestString);\n\t\t} catch (MalformedURLException e) {\n\n\t\t\tLog.e(LOG_TAG, \"Malfomed URL\");\n\t\t}\n\t\tthis.RequestCookies = RequestCookiemanager;\n\t\tif (method == METHOD_GET) {\n\t\t\tthis.RequestMethod = METHOD_GET;\n\t\t} else if (method == METHOD_POST) {\n\t\t\tthis.RequestMethod = METHOD_POST;\n\t\t} else {\n\t\t\tthis.RequestMethod = METHOD_GET;\n\t\t}\n\t\tthis.RequestpostData = postdata;\n\t\tthis.redirectNecessary = redirectNecessary;\n\t}\n\tpublic RequestObject(String RequestString, CookieManager RequestCookiemanager, String method,\n\t\t\t\t\t\t String postdata) {\n\t\tthis(RequestString, RequestCookiemanager, method, postdata,false);\n\t}\n\n\t/**\n\t * Objekt, welches alle notwendigen Informationen für einen\n\t * <code>HTTP</code>/<code>HTTPS</code>-Request enthält. <br>\n\t * <br>\n\t * Dieser Konstruktor sollte nur aufgerufen werden, falls noch keine Cookies\n\t * vorhanden sind.\n\t * \n\t * @param RequestString\n\t * URL(als String), welche aufgerufen werden soll\n\t * @param method\n\t * Entweder {@link #METHOD_GET} oder {@link #METHOD_POST}\n\t * @param postdata\n\t * Daten, welche bei {@link #METHOD_POST} mitgesendert werden\n\t * können\n\t * @author Daniel Thiem\n\t */\n\tpublic RequestObject(String RequestString, String method, String postdata) {\n\t\tthis(RequestString, new CookieManager(), method, postdata,false);\n\t}\n\n\tpublic boolean isRedirectNecessary() {\n\t\treturn redirectNecessary;\n\t}\n\n\n\t/**\n\t * \n\t * @return aufzurufende URL\n\t * @author Daniel Thiem\n\t */\n\tpublic URL getmyURL() {\n\t\treturn this.RequestURL;\n\t}\n\n\t/**\n\t * \n\t * @param newManager\n\t * neuer {@link CookieManager}\n\t * \n\t * @author Daniel Thiem\n\t */\n\tpublic void setCookieManager(CookieManager newManager) {\n\t\tthis.RequestCookies = newManager;\n\t}\n\n\t/**\n\t * \n\t * @return {@link CookieManager}\n\t * @author Daniel Thiem\n\t */\n\tpublic CookieManager getCookies() {\n\t\treturn this.RequestCookies;\n\t}\n\n\t/**\n\t * \n\t * @return post Data\n\t * @author Daniel Thiem\n\t */\n\tpublic String getPostData() {\n\t\treturn this.RequestpostData;\n\t}\n\n\t/**\n\t * \n\t * @return genutzte Methode\n\t * @author Daniel Thiem\n\t */\n\tpublic String getMethod() {\n\t\treturn this.RequestMethod;\n\t}\n\n}", "public class SimpleSecureBrowser extends AsyncTask<RequestObject, Integer, AnswerObject> {\n\n\t/**\n\t * Der {@link BrowserAnswerReciever}, welcher den\n\t * {@link SimpleSecureBrowser} aufgerufen hat. Meistens ist dies auch eine\n\t * {@link Activity}\n\t */\n\tpublic BrowserAnswerReciever outerCallingRecieverActivity;\n\t/**\n\t * Der lade-{@link Dialog}, welcher während des Ladevorgangs gezeigt wird,\n\t * jedoch bei manchen Events von aussen auch abgebrochen werden muss\n\t */\n\tpublic ProgressDialog dialog;\n\t/**\n\t * Bei <code>true</code> wird ein HTTPS request restartet, anderenfalls nur\n\t * HTTP\n\t */\n\tpublic boolean HTTPS = true;\n\t/**\n\t * <i>Depricated: </i> nutze stattdessen: {@link #getStatus()}\n\t */\n\t@Deprecated\n\tboolean finished = false;\n\t/**\n\t * List Adapter that has been set on the activity\n\t */\n\tpublic ConfigurationChangeStorage mConfigurationStorage;\n\n\t/**\n\t * SimpleSecureBrowser ist ein AsyncTask welcher die RequestObjects passend\n\t * abschickt und zurückgibt. Muss aus einer SimpleWebListActivity gestartet\n\t * werden. Nachdem die Daten angekommen sind, wird die onPostExecute der\n\t * aufrufenden SimpleWebListActivity aufgerufen.\n\t * \n\t * @param callingActivity\n\t * aufrufender {@link BrowserAnswerReciever}\n\t */\n\tpublic SimpleSecureBrowser(BrowserAnswerReciever callingActivity) {\n\t\touterCallingRecieverActivity = callingActivity;\n\n\t}\n\n\t@Override\n\tprotected AnswerObject doInBackground(RequestObject... requestInfo) {\n\t\tAnswerObject answer = new AnswerObject(\"\", \"\", null, null);\n\t\tRequestObject significantRequest = requestInfo[0];\n\t\tBrowseMethods Browser = new BrowseMethods();\n\t\tBrowser.HTTPS = this.HTTPS;\n\t\ttry {\n\t\t\tanswer = Browser.browse(significantRequest);\n\t\t} catch (Exception e) {\n if(e instanceof ConnectException || e instanceof UnknownHostException) {\n final Activity context = getparentActivityHandler();\n Runnable runnable = new Runnable() {\n @Override\n public void run() {\n\n Toast toast = Toast.makeText(context, \"Keine Internetverbindung\",\n Toast.LENGTH_LONG);\n toast.show();\n\n }\n };\n getparentActivityHandler().runOnUiThread(runnable);\n\n\n }\n\n\n\t\t}\n\t\treturn answer;\n\t}\n\n\t/**\n\t * Zeige Dialog\n\t */\n\tpublic void showDialog() {\n\t\tonPreExecute();\n\t}\n\n\t@Override\n\tprotected void onPreExecute() {\n\n\t\tActivity parentActivityHandler = getparentActivityHandler();\n\n\t\t// parentActivityHandler.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);\n\t\tif (parentActivityHandler != null && !TucanMobile.TESTING) {\n\t\t\tString loading = getparentActivityHandler().getResources().getString(\n\t\t\t\t\tR.string.ui_load_data);\n\t\t\tdialog = ProgressDialog.show(parentActivityHandler, \"\",\n\t\t\t// parentActivityHandler.getResources().getString(R.string.ui_load_data),true);\n\t\t\t\t\tloading, true);\n\t\t\tdialog.setCancelable(true);\n\t\t\tdialog.setOnCancelListener(new DialogInterface.OnCancelListener() {\n\n\t\t\t\tpublic void onCancel(DialogInterface dialog) {\n\t\t\t\t\tcancel(true);\n\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t}\n\n\t/**\n\t * \n\t * @return {@link Activity} Object of {@link BrowserAnswerReciever}, if it\n\t * is an instance of that, otherwise <code>null</code>\n\t */\n\tprivate Activity getparentActivityHandler() {\n\t\tif (outerCallingRecieverActivity instanceof Activity) {\n\t\t\treturn (Activity) outerCallingRecieverActivity;\n\t\t}\n\t\treturn null;\n\n\t}\n\n\t@Override\n\tprotected void onPostExecute(AnswerObject result) {\n\n\t\tfinal Activity parentActivityHandler = getparentActivityHandler();\n\t\ttry {\n\t\t\tif (dialog != null) {\n\t\t\t\tdialog.setTitle(parentActivityHandler.getResources().getString(R.string.ui_calc));\n\t\t\t}\n\t\t\touterCallingRecieverActivity.onPostExecute(result);\n\t\t\t\n\t\t\tif (dialog != null && dialog.isShowing())\n\t\t\t\tdialog.dismiss();\n\t\t} catch (IllegalArgumentException e) {\n if(parentActivityHandler!=null) {\n getparentActivityHandler().runOnUiThread(new Runnable() {\n @Override\n public void run() {\n Toast.makeText(getparentActivityHandler(), \"Bei dem Drehen des Bildschirmes ist ein Fehler aufgetreten\", Toast.LENGTH_LONG).show();\n }\n });\n\n\n //ACRA.getErrorReporter().handleSilentException(e);\n parentActivityHandler.finish();\n }\n\t\t}\n\n\t}\n\n\t/**\n\t * Renews the given {@link Activity} {@link Context}, if a new App Instance\n\t * had to be created\n\t * \n\t * @param context\n\t * {@link BrowserAnswerReciever} object\n\t */\n\tpublic void renewContext(BrowserAnswerReciever context) {\n\t\touterCallingRecieverActivity = context;\n\t}\n\n}", "public class ConfigurationChangeStorage {\n\n\tprivate ArrayList<BasicScraper> scrapers;\n\tprivate ArrayList<SimpleSecureBrowser> browser;\n\tpublic ArrayList<ListAdapter> adapters;\n\n\tpublic int mode;\n\n\tpublic ConfigurationChangeStorage() {\n\t\tscrapers = new ArrayList<BasicScraper>();\n\t\tadapters = new ArrayList<ListAdapter>();\n\t\tbrowser = new ArrayList<SimpleSecureBrowser>();\n\t}\n\n\t/**\n\t * Gibt den Scraper mit angepassten Context zurück\n\t * \n\t * @param index\n\t * @param context\n\t * @return\n\t */\n\tpublic BasicScraper getScraper(int index, Context context) {\n\t\tif (scrapers.size() > index) {\n\t\t\tBasicScraper returnScraper = scrapers.get(index);\n\t\t\tif (returnScraper != null) {\n\n\t\t\t\treturnScraper.renewContext(context);\n\t\t\t\treturn returnScraper;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\n\t}\n\n\tpublic void addScraper(BasicScraper scrape) {\n\t\tscrapers.add(scrape);\n\t}\n\n\tpublic void addBrowser(List<SimpleSecureBrowser> browser) {\n\t\tif (browser != null) {\n\t\t\tthis.browser.addAll(browser);\n\t\t}\n\t}\n\n\tpublic void addBrowser(SimpleSecureBrowser browser) {\n\t\tif (browser != null) {\n\t\t\tthis.browser.add(browser);\n\t\t}\n\t}\n\n\tpublic void dismissDialogs() {\n\t\tif(browser!=null){\n\t\t\tfor(SimpleSecureBrowser singleBrowser: browser) {\n\t\t\t\tif(singleBrowser.dialog!=null) {\n\t\t\t\t\tsingleBrowser.dialog.dismiss();\n\t\t\t\t\tsingleBrowser.dialog = null;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void updateBrowser(BrowserAnswerReciever context) {\n\t\tfor (SimpleSecureBrowser singleBrowser : browser) {\n\t\t\tsingleBrowser.renewContext(context);\n\t\t\tsingleBrowser.dialog = null;\n\t\t\tif (!(singleBrowser.getStatus().equals(AsyncTask.Status.FINISHED))) {\n\t\t\t\tLog.i(TucanMobile.LOG_TAG,\n\t\t\t\t\t\t\"Configuration Change at unfinished Browser, show Dialog\");\n\n\t\t\t\tsingleBrowser.showDialog();\n\n\t\t\t}\n\t\t}\n\t}\n\n}" ]
import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import com.dalthed.tucan.R; import com.dalthed.tucan.Connection.AnswerObject; import com.dalthed.tucan.Connection.CookieManager; import com.dalthed.tucan.Connection.RequestObject; import com.dalthed.tucan.Connection.SimpleSecureBrowser; import com.dalthed.tucan.ui.SimpleWebListActivity; import com.dalthed.tucan.util.ConfigurationChangeStorage;
/** * This file is part of TuCan Mobile. * * TuCan Mobile 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. * * TuCan Mobile 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 TuCan Mobile. If not, see <http://www.gnu.org/licenses/>. */ package com.dalthed.tucan.acraload; public class LoadAcraResults extends SimpleWebListActivity { private CookieManager localCookieManager; private static final String LOG_TAG = "TuCanMobile"; private final String URLStringtoCall = "http://daniel-thiem.de/ACRA/export.php"; private ArrayList<String> classes,ids,urls; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.acra); URL URLtoCall; try { URLtoCall = new URL(URLStringtoCall); localCookieManager = new CookieManager(); localCookieManager.inputCookie("daniel-thiem.de", "canView", "16ede40c878aee38d0882b3a6b2642c0ae76dafb"); RequestObject thisRequest = new RequestObject(URLStringtoCall, localCookieManager, RequestObject.METHOD_GET, "",false); SimpleSecureBrowser callResultBrowser = new SimpleSecureBrowser( this); callResultBrowser.HTTPS=false; callResultBrowser.execute(thisRequest); } catch (MalformedURLException e) { Log.e(LOG_TAG, e.getMessage()); } } public void onPostExecute(AnswerObject result) { Document doc = Jsoup.parse(result.getHTML()); Iterator<Element> divs = doc.select("div").iterator(); classes= new ArrayList<String>(); ids = new ArrayList<String>(); urls = new ArrayList<String>(); ArrayList<String> text = new ArrayList<String>(); while(divs.hasNext()){ Element next = divs.next(); Log.i(LOG_TAG,next.attr("title")); classes.add(next.attr("title")); ids.add(next.id()); urls.add(next.text()); text.add("#"+next.id()+": "+next.attr("title")+":"+next.attr("line")); } ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,text); setListAdapter(mAdapter); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { Class target; try { target=Class.forName("com.dalthed.tucan."+classes.get(position)); } catch (ClassNotFoundException e) { target=null; Log.i(LOG_TAG,"com.dalthed.tucan."+classes.get(position) + " not found"); } if(target==null) try { target=Class.forName("com.dalthed.tucan.ui."+classes.get(position)); } catch (ClassNotFoundException e) { Log.i(LOG_TAG,"com.dalthed.tucan.ui."+classes.get(position) + " not found"); target=null; } if(target==null) try { target=Class.forName("com.dalthed.tucan.scraper."+classes.get(position)); } catch (ClassNotFoundException e) { Log.i(LOG_TAG,"com.dalthed.tucan.scraper."+classes.get(position) + " not found"); target=null; } if(target!=null){ Intent loadDefectClassIntent = new Intent(this,target); loadDefectClassIntent.putExtra("URL", urls.get(position)); loadDefectClassIntent.putExtra("Cookie", ""); loadDefectClassIntent.putExtra("HTTPS", false); loadDefectClassIntent.putExtra("PREPLink", false); startActivity(loadDefectClassIntent); } } @Override
public ConfigurationChangeStorage saveConfiguration() {
4
Raxa/RaxaMachineLearning
src/com/machine/learning/socket/UmlsSocket.java
[ "public interface PredictionResult {\n\tpublic double getConfidence();\n\tpublic Object getValue();\n}", "public class LearningModulesPool {\n\n\t// LinkedList of Learning Modules in this pool\n\tprivate static LinkedList<LearningModuleInterface> modules = new LinkedList<LearningModuleInterface>();\n\tprivate static Logger log = Logger.getLogger(LearningModulesPool.class);\n\n\t// method to add a learning module in this pool\n\tpublic static void addLearningModule(LearningModuleInterface module) {\n\t\tmodules.add(module);\n\t\tlog.debug(\"Module Added: \" + module.getClass());\n\t}\n\n\t/*\n\t * method to get the results for a query from all modules in the pool and\n\t * merge them to return all the results\n\t */\n\tpublic static LinkedList<PredictionResult> predict(String query, SearchAttribute[] features) {\n\n\t\tLinkedList<PredictionResult> results = new LinkedList<PredictionResult>();\n\n\t\t// get the sorted results from a module and merge them with all results.\n\t\tfor (int i = 0; i < modules.size(); i++) {\n\t\t\tresults = join(modules.get(i).predict(query, features), results);\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t// method to merge/join two list of sorted prediction results\n\tprivate static LinkedList<PredictionResult> join(List<PredictionResult> list1,\n\t\t\tList<PredictionResult> list2) {\n\t\t// iterator on list1\n\t\tIterator<PredictionResult> it1 = list1.iterator();\n\n\t\t// iteraton on list2\n\t\tIterator<PredictionResult> it2 = list2.iterator();\n\n\t\t// results after joining\n\t\tLinkedList<PredictionResult> results = new LinkedList<PredictionResult>();\n\t\tPredictionResult temp1, temp2;\n\t\tif (it1.hasNext() && it2.hasNext()) {\n\t\t\ttemp1 = it1.next();\n\t\t\ttemp2 = it2.next();\n\n\t\t\t// if item in list1 has more confidence add it to the results else\n\t\t\t// add item of list2\n\t\t\tif (temp1.getConfidence() > temp2.getConfidence()) {\n\t\t\t\tresults.add(temp1);\n\t\t\t\ttemp1 = it1.next();\n\t\t\t} else {\n\t\t\t\tresults.add(temp2);\n\t\t\t\ttemp2 = it2.next();\n\t\t\t}\n\n\t\t\t// while one of the iterator reach its end\n\t\t\twhile (it1.hasNext() && it2.hasNext()) {\n\t\t\t\tif (temp1.getConfidence() < temp2.getConfidence()) {\n\t\t\t\t\tresults.add(temp1);\n\t\t\t\t\ttemp1 = it1.next();\n\t\t\t\t} else {\n\t\t\t\t\tresults.add(temp2);\n\t\t\t\t\ttemp2 = it2.next();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// add items for list1 if any left\n\t\twhile (it1.hasNext()) {\n\t\t\tresults.add(it1.next());\n\t\t}\n\n\t\t// add items for list2 if any left\n\t\twhile (it2.hasNext()) {\n\t\t\tresults.add(it2.next());\n\t\t}\n\t\treturn results;\n\t}\n\n\t/*\n\t * method to call all the learning modules to initiate there learning\n\t * algorithm.\n\t */\n\tpublic static void learn() {\n\t\tThread[] threads = new Thread[modules.size()];\n\t\tfor (int i = 0; i < modules.size(); i++) {\n\t\t\tthreads[i] = runLearningThread(i);\n\t\t}\n\t\tfor (int i = 0; i < modules.size(); i++) {\n\t\t\twhile (threads[i].isAlive())\n\t\t\t\t;\n\t\t}\n\t}\n\n\tprivate static Thread runLearningThread(int i) {\n\t\tfinal int j = i;\n\t\tThread thread = new Thread(new Runnable() {\n\n\t\t\t@Override\n\t\t\tpublic void run() {\n\t\t\t\tmodules.get(j).learn();\n\t\t\t}\n\t\t});\n\t\tthread.run();\n\t\treturn thread;\n\t}\n}", "public class Request {\n\tLearningRequest learningRequest;\n\tSearchQueryRequest searchRequest;\n\n\tpublic LearningRequest getLearningRequest() {\n\t\treturn learningRequest;\n\t}\n\n\tpublic void setLearningRequest(LearningRequest learningRequest) {\n\t\tthis.learningRequest = learningRequest;\n\t}\n\n\tpublic SearchQueryRequest getSearchRequest() {\n\t\treturn searchRequest;\n\t}\n\n\tpublic void setSearchRequest(SearchQueryRequest searchRequest) {\n\t\tthis.searchRequest = searchRequest;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Request [learningRequest=\" + learningRequest + \", searchRequest=\" + searchRequest\n\t\t\t\t+ \"]\";\n\t}\n}", "public class SearchQueryRequest {\n\tprivate String query;\n\tprivate SearchAttribute[] features;\n\n\tpublic void setFeature(SearchAttribute[] features) {\n\t\tthis.features = features;\n\t}\n\t\n\tpublic SearchAttribute[] getFeatures() {\n\t\treturn this.features;\n\t}\n\t\n\tpublic SearchQueryRequest(String query, SearchAttribute[] features) {\n\t\tsuper();\n\t\tthis.query = query;\n\t\tthis.features = features;\n\t}\n\n\tpublic SearchQueryRequest(String query) {\n\t\tthis.query = query;\n\t}\n\n\tpublic String getQuery() {\n\t\treturn query;\n\t}\n\n\tpublic void setQuery(String query) {\n\t\tthis.query = query;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"SearchQueryRequest [query=\" + query + \", features=\" + Arrays.toString(features)\n\t\t\t\t+ \"]\";\n\t}\n\n}", "public class DiseaseToDrugPrediction {\n\n\t/*\n\t * method to search for a query\n\t */\n\tpublic static UmlsResult predict(String query, SearchAttribute[] features) {\n\n\t\t// get the list for CUI's for this search query\n\t\tLinkedList<String> cuis = MRXWTableOperation.searchCUI(query);\n\t\tSystem.out.println(\"d1\");\n\n\t\t// if list is not empty\n\t\tif (!cuis.isEmpty()) {\n\n\t\t\t// get filter the cui's with semantic type of\n\t\t\t// disease/syndrom/symptom\n\t\t\tLinkedList<SemanticType> types = MRSTYTableOperation\n\t\t\t\t\t.getDiseaseSyndromSymptomByCUI(cuis);\n\t\t\tSystem.out.println(\"d2\");\n\t\t\tcuis = getCuis(types);\n\n\t\t\t// get the Concept name and other info from MRCONSE table for the\n\t\t\t// disease CUI's.\n\t\t\tLinkedList<ConceptModel> diseases = MRCONSETableOperation.getConceptByCUI(cuis);\n\n\t\t\t// get the list of concepts related to the diseases CUI's\n\t\t\tLinkedList<RelationModel> relatedConceptsList = MRRELTableOperation\n\t\t\t\t\t.getRelatedConceptsByCUI(cuis);\n\t\t\tSystem.out.println(\"d3\");\n\t\t\tLinkedList<String> relatedcuis = getRelatedCuis(relatedConceptsList);\n\t\t\tSystem.out.println(relatedcuis.size());\n\n\t\t\t// filter out the Concepts which are drugs from list of related\n\t\t\t// CUI's\n\t\t\tLinkedList<SemanticType> drugtypes = MRSTYTableOperation.getDrugsByCUI(relatedcuis);\n\t\t\tSystem.out.println(\"d4\");\n\t\t\tLinkedList<String> drugCuis = getCuis(drugtypes);\n\n\t\t\t// get the drug concept Info for drug list\n\t\t\tLinkedList<ConceptModel> drugs = MRCONSETableOperation.getDrugConceptsByCUI(drugCuis);\n\t\t\t// showDrugRelations(drugs, relatedConceptsList);\n\t\t\tSystem.out.println(\"d5\");\n\n\t\t\t// add weights to drugs depending upon drug is contra-indicated or\n\t\t\t// it may treat the disease\n\t\t\tLinkedList<UmlsPredictionResult> results = addWeights(relatedConceptsList, drugs);\n\n\t\t\t// add weights to list of disease found for given search query\n\t\t\tLinkedList<UmlsPredictionResult> weightedDiseases = sortResults(getWeightedDiseaseList(\n\t\t\t\t\tdiseases, query));\n\n\t\t\t// get the list of generics out of the list of drugs\n\t\t\tLinkedList<DrugGeneric> generics = getListOfDrugGeneric(results);\n\n\t\t\t// add weights to list of drug generics depending on disease it may\n\t\t\t// treat\n\t\t\tgenerics = addMayTreats(weightedDiseases, generics, relatedConceptsList);\n\n\t\t\t// Use machine learning results to change weights list of generics\n\t\t\tgenerics = getMLPredictions(generics, query, features);\n\n\t\t\t// sort the list of drug generics\n\t\t\tgenerics = sortDrugs(generics);\n\n\t\t\t// limit on top 30 drug generics\n\t\t\tgenerics = limitNoOfDrugs(30, generics);\n\n\t\t\t// remove the suggested diseases with weight less then 0.5\n\t\t\tweightedDiseases = limitNoOfDisease(0.5, weightedDiseases);\n\n\t\t\t// set the umls result for this query\n\t\t\tUmlsResult result = new UmlsResult(weightedDiseases, generics);\n\n\t\t\t// get the definition for this search query(disease)\n\t\t\tresult.setDisDef(getDef(weightedDiseases, query));\n\t\t\treturn result;\n\t\t} else {\n\t\t\treturn new UmlsResult(null, null);\n\t\t}\n\t}\n\n\t/*\n\t * method to remove the suggestions with confidence less the threshold\n\t */\n\tprivate static LinkedList<UmlsPredictionResult> limitNoOfDisease(double thresholdConf,\n\t\t\tLinkedList<UmlsPredictionResult> diseases) {\n\t\tLinkedList<UmlsPredictionResult> results = new LinkedList<UmlsPredictionResult>();\n\t\tfor (UmlsPredictionResult disease : diseases) {\n\t\t\tif (disease.getConfidence() >= thresholdConf) {\n\t\t\t\tresults.add(disease);\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn results;\n\t}\n\n\t/*\n\t * method to limit the number of drugs for a given size\n\t */\n\tprivate static LinkedList<DrugGeneric> limitNoOfDrugs(int size, LinkedList<DrugGeneric> generics) {\n\t\tint i = 0;\n\t\tLinkedList<DrugGeneric> results = new LinkedList<DrugGeneric>();\n\t\tfor (DrugGeneric gen : generics) {\n\t\t\tif (i < size) {\n\t\t\t\tresults.add(gen);\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\ti++;\n\t\t}\n\t\treturn results;\n\t}\n\n\t/*\n\t * Method to get the definition for the search query\n\t */\n\tprivate static ConceptDefination getDef(LinkedList<UmlsPredictionResult> diseases, String query) {\n\t\tConceptDefination temp = null;\n\t\tint i = 0;\n\n\t\t// for 1st 30 disease found for search query\n\t\tfor (UmlsPredictionResult disease : diseases) {\n\t\t\tif (i > 30)\n\t\t\t\tbreak;\n\t\t\ti++;\n\n\t\t\t// if distance of search query from disease name is less the 1 or\n\t\t\t// search query is a short form\n\t\t\tif (LivenstineDistance.getDistance(disease.getValue().getName(), query) <= 1\n\t\t\t\t\t|| queryIsShortForm(disease.getValue().getName(), query)) {\n\n\t\t\t\t// get the definition for this CUI\n\t\t\t\ttemp = MRDEFTableOperation.getDefByCUI(disease.getValue().getCUI(), disease\n\t\t\t\t\t\t.getValue().getName());\n\t\t\t\tif (temp != null) {\n\t\t\t\t\treturn temp;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t/*\n\t * method to check is the given search query is a shortForm. Short Form\n\t * should have all upper case letters\n\t */\n\tprivate static boolean queryIsShortForm(String name, String query) {\n\n\t\t// all characters should be upper case.\n\t\tif (query.toUpperCase().equals(query)) {\n\t\t\tname = name.toLowerCase();\n\t\t\tString[] temp = name.split(\"\\\\s+\");\n\t\t\tquery.replaceAll(\".\", \"\");\n\t\t\tString shortForm = \"\";\n\t\t\tfor (int i = 0; i < temp.length; i++) {\n\t\t\t\tshortForm = shortForm + temp[i].charAt(0);\n\t\t\t}\n\t\t\tif (LivenstineDistance.getDistance(query, shortForm) < 2) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/*\n\t * method that adds the disease that a generic mayTreat given the relations\n\t * between drug and disease in umls\n\t */\n\tprivate static LinkedList<DrugGeneric> addMayTreats(LinkedList<UmlsPredictionResult> diseases,\n\t\t\tLinkedList<DrugGeneric> generics, LinkedList<RelationModel> relations) {\n\n\t\tfor (DrugGeneric generic : generics) {\n\t\t\tfor (UmlsPredictionResult disease : diseases) {\n\t\t\t\tboolean found = false;\n\t\t\t\tfor (UmlsPredictionResult drug : generic.getDrugs()) {\n\t\t\t\t\tfor (RelationModel rel : relations) {\n\t\t\t\t\t\tif (rel.getCUI().equals(disease.getValue().getCUI())\n\t\t\t\t\t\t\t\t&& rel.getRelatedCUI().equals(drug.getValue().getCUI())) {\n\t\t\t\t\t\t\tgeneric.addMayreat(disease.getValue());\n\t\t\t\t\t\t\tgeneric.setConfidence(max(generic.getConfidence(),\n\t\t\t\t\t\t\t\t\tdisease.getConfidence() * drug.getConfidence()));\n\t\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\t\t// System.out.print(\"yes\");\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (found)\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn generics;\n\t}\n\n\tprivate static double max(double x, double y) {\n\t\tif (x > y)\n\t\t\treturn x;\n\t\telse\n\t\t\treturn y;\n\t}\n\n\tprivate static void showDrugRelations(LinkedList<ConceptModel> drugCuis,\n\t\t\tLinkedList<RelationModel> rel) {\n\t\tfor (ConceptModel cui : drugCuis) {\n\t\t\tfor (RelationModel re : rel) {\n\t\t\t\tif (re.getRelatedCUI().equals(cui.getCUI())) {\n\t\t\t\t\tSystem.out.println(re + \"|\" + cui);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/*\n\t * method to get the list of cui's from relations\n\t */\n\tprivate static LinkedList<String> getRelatedCuis(LinkedList<RelationModel> list) {\n\t\tLinkedList<String> cuis = new LinkedList<String>();\n\t\tfor (RelationModel row : list) {\n\t\t\tcuis.add(row.getRelatedCUI());\n\t\t}\n\t\treturn cuis;\n\t}\n\n\t/*\n\t * method to sort the drug generic results\n\t */\n\tprivate static LinkedList<DrugGeneric> sortDrugs(LinkedList<DrugGeneric> list) {\n\n\t\tCollections.sort(list, new Comparator<DrugGeneric>() {\n\n\t\t\t@Override\n\t\t\tpublic int compare(DrugGeneric o1, DrugGeneric o2) {\n\t\t\t\tif (o1.getConfidence() > o2.getConfidence())\n\t\t\t\t\treturn -1;\n\t\t\t\telse if (o1.getConfidence() < o2.getConfidence())\n\t\t\t\t\treturn 1;\n\t\t\t\telse\n\t\t\t\t\treturn 0;\n\t\t\t}\n\t\t});\n\t\treturn list;\n\t}\n\n\t/*\n\t * method to sort the UmlsPredictionResult(disease/drugs)\n\t */\n\tprivate static LinkedList<UmlsPredictionResult> sortResults(\n\t\t\tLinkedList<UmlsPredictionResult> list) {\n\n\t\tCollections.sort(list, new Comparator<UmlsPredictionResult>() {\n\n\t\t\t@Override\n\t\t\tpublic int compare(UmlsPredictionResult o1, UmlsPredictionResult o2) {\n\t\t\t\tif (o1.getConfidence() > o2.getConfidence())\n\t\t\t\t\treturn -1;\n\t\t\t\telse if (o1.getConfidence() < o2.getConfidence())\n\t\t\t\t\treturn 1;\n\t\t\t\telse\n\t\t\t\t\treturn 0;\n\t\t\t}\n\t\t});\n\t\tLinkedList<UmlsPredictionResult> results = new LinkedList<UmlsPredictionResult>();\n\t\tfor (UmlsPredictionResult item : list) {\n\t\t\tboolean found = false;\n\t\t\tfor (UmlsPredictionResult res : results) {\n\t\t\t\tif (item.getValue().getCUI().equals(res.getValue().getCUI())) {\n\t\t\t\t\tfound = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!found) {\n\t\t\t\tresults.add(item);\n\t\t\t}\n\t\t}\n\t\treturn results;\n\t}\n\n\t/*\n\t * method that add the weights for drugs based on whether they are contra\n\t * indicated or may treat relation ship attribute\n\t */\n\tprivate static LinkedList<UmlsPredictionResult> addWeights(LinkedList<RelationModel> rels,\n\t\t\tLinkedList<ConceptModel> drugs) {\n\n\t\tLinkedList<UmlsPredictionResult> results = new LinkedList<UmlsPredictionResult>();\n\t\tfor (ConceptModel drug : drugs) {\n\t\t\tresults.add(new UmlsPredictionResult(1.0, drug));\n\t\t}\n\t\tfor (RelationModel rel : rels) {\n\n\t\t\t// set the weight to 0.0 if the drug is contraindicated for this\n\t\t\t// disease\n\t\t\tif (rel.getRelationAttribute() != null\n\t\t\t\t\t&& rel.getRelationAttribute().equalsIgnoreCase(\"contraindicated_drug\")) {\n\t\t\t\tfor (UmlsPredictionResult result : results) {\n\t\t\t\t\tif (result.getValue().getCUI().equals(rel.getRelatedCUI())) {\n\t\t\t\t\t\tresult.setConfidence(0.0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn results;\n\t}\n\n\t/*\n\t * method to get list of generic and group the drug with those generics\n\t */\n\tprivate static LinkedList<DrugGeneric> getListOfDrugGeneric(\n\t\t\tLinkedList<UmlsPredictionResult> list) {\n\t\tLinkedList<DrugGeneric> results = new LinkedList<DrugGeneric>();\n\t\tfor (UmlsPredictionResult item : list) {\n\t\t\tif (item.getConfidence() > 0.0) {\n\t\t\t\tString generic = getGeneric(item.getValue().getName());\n\t\t\t\tboolean found = false;\n\t\t\t\tfor (DrugGeneric result : results) {\n\t\t\t\t\tif (result.getGeneric().equals(generic)) {\n\t\t\t\t\t\tresult.addDrug(item);\n\t\t\t\t\t\tfound = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (!found) {\n\t\t\t\t\tDrugGeneric temp = new DrugGeneric(generic);\n\t\t\t\t\ttemp.addDrug(item);\n\t\t\t\t\tresults.add(temp);\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn results;\n\t}\n\n\t/*\n\t * get the Generic Name from the Ingredient dosage form of the drug\n\t */\n\tprivate static String getGeneric(String name1) {\n\t\tString temp1[] = name1.split(\"\\\\s+\");\n\n\t\tString generic1 = \"\";\n\t\tint i = 0;\n\t\tif (isNumeric(temp1[0])) {\n\t\t\ti = 2;\n\t\t}\n\t\twhile (i < temp1.length) {\n\t\t\tif (isNumeric(temp1[i])) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tgeneric1 = generic1 + temp1[i] + \" \";\n\t\t\ti++;\n\t\t}\n\n\t\treturn generic1;\n\t}\n\n\tpublic static boolean isNumeric(String str) {\n\t\ttry {\n\t\t\tdouble d = Double.parseDouble(str);\n\t\t} catch (NumberFormatException nfe) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t/*\n\t * method to add semantics types to concept Model\n\t */\n\tpublic static LinkedList<ConceptModel> addSemanticTypes(LinkedList<ConceptModel> concepts,\n\t\t\tLinkedList<SemanticType> types) {\n\t\tfor (SemanticType type : types) {\n\t\t\tfor (ConceptModel concept : concepts) {\n\t\t\t\tif (concept.getCUI().equals(type.getCUI())) {\n\t\t\t\t\tconcept.setSemanticTypes(type);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn concepts;\n\t}\n\n\t/*\n\t * get list of CUI's from the list of semantic type\n\t */\n\tpublic static LinkedList<String> getCuis(LinkedList<SemanticType> types) {\n\t\tLinkedList<String> cuis = new LinkedList<String>();\n\t\tfor (SemanticType type : types) {\n\t\t\tcuis.add(type.getCUI());\n\t\t}\n\t\treturn cuis;\n\t}\n\n\t/*\n\t * add the weights for suggestion diseases using the Livenstine Distance\n\t */\n\tpublic static LinkedList<UmlsPredictionResult> getWeightedDiseaseList(\n\t\t\tLinkedList<ConceptModel> diseases, String query) {\n\t\tLinkedList<UmlsPredictionResult> result = new LinkedList<UmlsPredictionResult>();\n\t\tfor (ConceptModel disease : diseases) {\n\t\t\tresult.add(new UmlsPredictionResult(LivenstineDistance.getWordMatchDistance(\n\t\t\t\t\tdisease.getName(), query), disease));\n\t\t}\n\t\treturn result;\n\t}\n\n\t/*\n\t * method to get the machine learning predictions and increase the weight of\n\t * drug generics found by machine learning\n\t */\n\tpublic static LinkedList<DrugGeneric> getMLPredictions(LinkedList<DrugGeneric> generics,\n\t\t\tString query, SearchAttribute[] features) {\n\t\tLinkedList<PredictionResult> list = LearningModulesPool.predict(query, features);\n\t\tfor (PredictionResult item : list) {\n\t\t\tDrugModel drug = (DrugModel) item.getValue();\n\t\t\t// System.out.print(drug.getName() + \",\" + drug.getGeneric());\n\t\t\tfor (DrugGeneric gen : generics) {\n\t\t\t\tif (belongsToGeneric(drug, gen.getGeneric())) {\n\t\t\t\t\tgen.setConfidence(gen.getConfidence() + item.getConfidence());\n\t\t\t\t\t// System.out.print( \", \" + gen.getGeneric());\n\t\t\t\t}\n\t\t\t}\n\t\t\t// System.out.println();\n\t\t}\n\t\treturn generics;\n\t}\n\n\tpublic static boolean belongsToGeneric(DrugModel drug, String generic) {\n\t\tString gen;\n\t\tif (drug.getGeneric() != null) {\n\t\t\tgen = drug.getGeneric();\n\t\t} else {\n\t\t\tgen = drug.getName();\n\t\t}\n\t\tgen = gen.toLowerCase().replaceAll(\"[^a-zA-Z0-9\\\\s]+\", \"\\\\s\");\n\n\t\tgeneric = generic.toLowerCase().replace(\"[^a-zA-Z0-9\\\\s]+\", \"\\\\s\");\n\n\t\tString[] temp1 = gen.split(\"\\\\s+\");\n\t\tString[] temp2 = generic.split(\"\\\\s+\");\n\t\tboolean found = true;\n\t\tfor (int i = 0; i < 1; i++) {\n\t\t\tboolean temp = false;\n\t\t\tfor (int j = 0; j < temp1.length; j++) {\n\t\t\t\ttemp = (temp1[j].equals(temp2[i]) || temp);\n\t\t\t}\n\t\t\tfound = (found && temp);\n\t\t}\n\t\treturn found;\n\t}\n\n\tpublic static void main(String[] args) {\n\n\t\tUmlsResult result = predict(\"asthma\", new SearchAttribute[0]);\n\n\t\tint i = 0;\n\t\tfor (DrugGeneric drug : result.getDrugs()) {\n\t\t\ti++;\n\t\t\tSystem.out.println(drug);\n\t\t\tif (i > 20)\n\t\t\t\tbreak;\n\t\t}\n\t\tSystem.out.print(result.getDisDef());\n\t}\n}" ]
import java.io.IOException; import java.util.List; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import org.apache.log4j.Logger; import com.google.gson.Gson; import com.learningmodule.association.conceptdrug.PredictionResult; import com.machine.learning.LearningModulesPool; import com.machine.learning.request.Request; import com.machine.learning.request.SearchQueryRequest; import com.umls.search.DiseaseToDrugPrediction;
package com.machine.learning.socket; /* * class that implement the socket interface for umls Learning Module */ @ServerEndpoint(value = "/ml/umls") public class UmlsSocket { private Gson gson = new Gson(); private static Logger log = Logger.getLogger(UmlsSocket.class); private Session session; @OnOpen public void start(Session session) { this.session = session; } @OnClose public void end() { } /* * Method that is invoked when there is msg from client input from client * for querying should be of form "query:<search string>" */ @OnMessage public void onMsg(String query) { System.out.println(query); Request req = gson.fromJson(query, Request.class); if (req.getSearchRequest() != null) { // send the results to client for search string sendResults(req.getSearchRequest()); } }
public void sendResults(SearchQueryRequest query) {
3
Jamling/Android-ORM
cn.ieclipse.aorm.core/test/cn/ieclipse/aorm/SessionTest.java
[ "public final class ContentValues {\n public static final String TAG = \"ContentValues\";\n \n /** Holds the actual values */\n private HashMap<String, Object> mValues;\n \n /**\n * Creates an empty set of values using the default initial size\n */\n public ContentValues() {\n // Choosing a default size of 8 based on analysis of typical\n // consumption by applications.\n mValues = new HashMap<String, Object>(8);\n }\n \n /**\n * Creates an empty set of values using the given initial size\n * \n * @param size\n * the initial size of the set of values\n */\n public ContentValues(int size) {\n mValues = new HashMap<String, Object>(size, 1.0f);\n }\n \n /**\n * Creates a set of values copied from the given set\n * \n * @param from\n * the values to copy\n */\n public ContentValues(ContentValues from) {\n mValues = new HashMap<String, Object>(from.mValues);\n }\n \n /**\n * Creates a set of values copied from the given HashMap. This is used by\n * the Parcel unmarshalling code.\n * \n * @param values\n * the values to start with {@hide}\n */\n private ContentValues(HashMap<String, Object> values) {\n mValues = values;\n }\n \n @Override\n public boolean equals(Object object) {\n if (!(object instanceof ContentValues)) {\n return false;\n }\n return mValues.equals(((ContentValues) object).mValues);\n }\n \n @Override\n public int hashCode() {\n return mValues.hashCode();\n }\n \n /**\n * Adds a value to the set.\n * \n * @param key\n * the name of the value to put\n * @param value\n * the data for the value to put\n */\n public void put(String key, String value) {\n mValues.put(key, value);\n }\n \n /**\n * Adds all values from the passed in ContentValues.\n * \n * @param other\n * the ContentValues from which to copy\n */\n public void putAll(ContentValues other) {\n mValues.putAll(other.mValues);\n }\n \n /**\n * Adds a value to the set.\n * \n * @param key\n * the name of the value to put\n * @param value\n * the data for the value to put\n */\n public void put(String key, Byte value) {\n mValues.put(key, value);\n }\n \n /**\n * Adds a value to the set.\n * \n * @param key\n * the name of the value to put\n * @param value\n * the data for the value to put\n */\n public void put(String key, Short value) {\n mValues.put(key, value);\n }\n \n /**\n * Adds a value to the set.\n * \n * @param key\n * the name of the value to put\n * @param value\n * the data for the value to put\n */\n public void put(String key, Integer value) {\n mValues.put(key, value);\n }\n \n /**\n * Adds a value to the set.\n * \n * @param key\n * the name of the value to put\n * @param value\n * the data for the value to put\n */\n public void put(String key, Long value) {\n mValues.put(key, value);\n }\n \n /**\n * Adds a value to the set.\n * \n * @param key\n * the name of the value to put\n * @param value\n * the data for the value to put\n */\n public void put(String key, Float value) {\n mValues.put(key, value);\n }\n \n /**\n * Adds a value to the set.\n * \n * @param key\n * the name of the value to put\n * @param value\n * the data for the value to put\n */\n public void put(String key, Double value) {\n mValues.put(key, value);\n }\n \n /**\n * Adds a value to the set.\n * \n * @param key\n * the name of the value to put\n * @param value\n * the data for the value to put\n */\n public void put(String key, Boolean value) {\n mValues.put(key, value);\n }\n \n /**\n * Adds a value to the set.\n * \n * @param key\n * the name of the value to put\n * @param value\n * the data for the value to put\n */\n public void put(String key, byte[] value) {\n mValues.put(key, value);\n }\n \n /**\n * Adds a null value to the set.\n * \n * @param key\n * the name of the value to make null\n */\n public void putNull(String key) {\n mValues.put(key, null);\n }\n \n /**\n * Returns the number of values.\n * \n * @return the number of values\n */\n public int size() {\n return mValues.size();\n }\n \n /**\n * Remove a single value.\n * \n * @param key\n * the name of the value to remove\n */\n public void remove(String key) {\n mValues.remove(key);\n }\n \n /**\n * Removes all values.\n */\n public void clear() {\n mValues.clear();\n }\n \n /**\n * Returns true if this object has the named value.\n * \n * @param key\n * the value to check for\n * @return {@code true} if the value is present, {@code false} otherwise\n */\n public boolean containsKey(String key) {\n return mValues.containsKey(key);\n }\n \n /**\n * Gets a value. Valid value types are {@link String}, {@link Boolean}, and\n * {@link Number} implementations.\n * \n * @param key\n * the value to get\n * @return the data for the value\n */\n public Object get(String key) {\n return mValues.get(key);\n }\n \n /**\n * Gets a value and converts it to a String.\n * \n * @param key\n * the value to get\n * @return the String for the value\n */\n public String getAsString(String key) {\n Object value = mValues.get(key);\n return value != null ? value.toString() : null;\n }\n \n /**\n * Gets a value and converts it to a Long.\n * \n * @param key\n * the value to get\n * @return the Long value, or null if the value is missing or cannot be\n * converted\n */\n public Long getAsLong(String key) {\n Object value = mValues.get(key);\n try {\n return value != null ? ((Number) value).longValue() : null;\n } catch (ClassCastException e) {\n if (value instanceof CharSequence) {\n try {\n return Long.valueOf(value.toString());\n } catch (NumberFormatException e2) {\n Log.e(TAG, \"Cannot parse Long value for \" + value\n + \" at key \" + key);\n return null;\n }\n }\n else {\n Log.e(TAG, \"Cannot cast value for \" + key + \" to a Long: \"\n + value, e);\n return null;\n }\n }\n }\n \n /**\n * Gets a value and converts it to an Integer.\n * \n * @param key\n * the value to get\n * @return the Integer value, or null if the value is missing or cannot be\n * converted\n */\n public Integer getAsInteger(String key) {\n Object value = mValues.get(key);\n try {\n return value != null ? ((Number) value).intValue() : null;\n } catch (ClassCastException e) {\n if (value instanceof CharSequence) {\n try {\n return Integer.valueOf(value.toString());\n } catch (NumberFormatException e2) {\n Log.e(TAG, \"Cannot parse Integer value for \" + value\n + \" at key \" + key);\n return null;\n }\n }\n else {\n Log.e(TAG, \"Cannot cast value for \" + key + \" to a Integer: \"\n + value, e);\n return null;\n }\n }\n }\n \n /**\n * Gets a value and converts it to a Short.\n * \n * @param key\n * the value to get\n * @return the Short value, or null if the value is missing or cannot be\n * converted\n */\n public Short getAsShort(String key) {\n Object value = mValues.get(key);\n try {\n return value != null ? ((Number) value).shortValue() : null;\n } catch (ClassCastException e) {\n if (value instanceof CharSequence) {\n try {\n return Short.valueOf(value.toString());\n } catch (NumberFormatException e2) {\n Log.e(TAG, \"Cannot parse Short value for \" + value\n + \" at key \" + key);\n return null;\n }\n }\n else {\n Log.e(TAG, \"Cannot cast value for \" + key + \" to a Short: \"\n + value, e);\n return null;\n }\n }\n }\n \n /**\n * Gets a value and converts it to a Byte.\n * \n * @param key\n * the value to get\n * @return the Byte value, or null if the value is missing or cannot be\n * converted\n */\n public Byte getAsByte(String key) {\n Object value = mValues.get(key);\n try {\n return value != null ? ((Number) value).byteValue() : null;\n } catch (ClassCastException e) {\n if (value instanceof CharSequence) {\n try {\n return Byte.valueOf(value.toString());\n } catch (NumberFormatException e2) {\n Log.e(TAG, \"Cannot parse Byte value for \" + value\n + \" at key \" + key);\n return null;\n }\n }\n else {\n Log.e(TAG, \"Cannot cast value for \" + key + \" to a Byte: \"\n + value, e);\n return null;\n }\n }\n }\n \n /**\n * Gets a value and converts it to a Double.\n * \n * @param key\n * the value to get\n * @return the Double value, or null if the value is missing or cannot be\n * converted\n */\n public Double getAsDouble(String key) {\n Object value = mValues.get(key);\n try {\n return value != null ? ((Number) value).doubleValue() : null;\n } catch (ClassCastException e) {\n if (value instanceof CharSequence) {\n try {\n return Double.valueOf(value.toString());\n } catch (NumberFormatException e2) {\n Log.e(TAG, \"Cannot parse Double value for \" + value\n + \" at key \" + key);\n return null;\n }\n }\n else {\n Log.e(TAG, \"Cannot cast value for \" + key + \" to a Double: \"\n + value, e);\n return null;\n }\n }\n }\n \n /**\n * Gets a value and converts it to a Float.\n * \n * @param key\n * the value to get\n * @return the Float value, or null if the value is missing or cannot be\n * converted\n */\n public Float getAsFloat(String key) {\n Object value = mValues.get(key);\n try {\n return value != null ? ((Number) value).floatValue() : null;\n } catch (ClassCastException e) {\n if (value instanceof CharSequence) {\n try {\n return Float.valueOf(value.toString());\n } catch (NumberFormatException e2) {\n Log.e(TAG, \"Cannot parse Float value for \" + value\n + \" at key \" + key);\n return null;\n }\n }\n else {\n Log.e(TAG, \"Cannot cast value for \" + key + \" to a Float: \"\n + value, e);\n return null;\n }\n }\n }\n \n /**\n * Gets a value and converts it to a Boolean.\n * \n * @param key\n * the value to get\n * @return the Boolean value, or null if the value is missing or cannot be\n * converted\n */\n public Boolean getAsBoolean(String key) {\n Object value = mValues.get(key);\n try {\n return (Boolean) value;\n } catch (ClassCastException e) {\n if (value instanceof CharSequence) {\n return Boolean.valueOf(value.toString());\n }\n else if (value instanceof Number) {\n return ((Number) value).intValue() != 0;\n }\n else {\n Log.e(TAG, \"Cannot cast value for \" + key + \" to a Boolean: \"\n + value, e);\n return null;\n }\n }\n }\n \n /**\n * Gets a value that is a byte array. Note that this method will not convert\n * any other types to byte arrays.\n * \n * @param key\n * the value to get\n * @return the byte[] value, or null is the value is missing or not a byte[]\n */\n public byte[] getAsByteArray(String key) {\n Object value = mValues.get(key);\n if (value instanceof byte[]) {\n return (byte[]) value;\n }\n else {\n return null;\n }\n }\n \n /**\n * Returns a set of all of the keys and values\n * \n * @return a set of all of the keys and values\n */\n public Set<Map.Entry<String, Object>> valueSet() {\n return mValues.entrySet();\n }\n \n /**\n * Returns a set of all of the keys\n * \n * @return a set of all of the keys\n */\n public Set<String> keySet() {\n return mValues.keySet();\n }\n \n /**\n * Unsupported, here until we get proper bulk insert APIs. {@hide}\n */\n @Deprecated\n public void putStringArrayList(String key, ArrayList<String> value) {\n mValues.put(key, value);\n }\n \n /**\n * Unsupported, here until we get proper bulk insert APIs. {@hide}\n */\n @SuppressWarnings(\"unchecked\")\n @Deprecated\n public ArrayList<String> getStringArrayList(String key) {\n return (ArrayList<String>) mValues.get(key);\n }\n \n /**\n * Returns a string containing a concise, human-readable description of this\n * object.\n * \n * @return a printable representation of this object.\n */\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n for (String name : mValues.keySet()) {\n String value = getAsString(name);\n if (sb.length() > 0)\n sb.append(\" \");\n sb.append(name + \"=\" + value);\n }\n return sb.toString();\n }\n}", "@Table(name = \"course\")\npublic class Course implements Serializable {\n \n private static final long serialVersionUID = 4957742859044875650L;\n \n @Column(name = \"_id\", id = true)\n private long id;\n \n @Column(name = \"_name\")\n private String name;\n \n// public long getId() {\n// return id;\n// }\n// \n// public void setId(long id) {\n// this.id = id;\n// }\n// \n// public String getName() {\n// return name;\n// }\n// \n// public void setName(String name) {\n// this.name = name;\n// }\n \n}", "@Table(name = \"grade\")\npublic class Grade implements Serializable {\n \n private static final long serialVersionUID = -8976200526604051847L;\n \n private static final int PASS_GRADE = 60;\n \n @Column(name = \"_id\", id = true)\n private long id;\n \n @Column(name = \"_sid\")\n private long sid;\n \n @Column(name = \"_cid\")\n private long cid;\n \n @Column(name = \"_score\")\n public float score;\n// \n// public long getId() {\n// return id;\n// }\n// \n// public void setId(long id) {\n// this.id = id;\n// }\n// \n// public long getSid() {\n// return sid;\n// }\n// \n// public void setSid(long sid) {\n// this.sid = sid;\n// }\n// \n// public long getCid() {\n// return cid;\n// }\n// \n// public void setCid(long cid) {\n// this.cid = cid;\n// }\n// \n// public float getScore() {\n// return score;\n// }\n// \n// public void setScore(float score) {\n// this.score = score;\n// }\n// \n// public boolean isPass() {\n// return this.score >= PASS_GRADE;\n// }\n}", "@Table(name = \"person\")\npublic class Person {\n \n @Column(id = true, name = \"_id\")\n public long id;\n \n @Column(name = \"_name\", notNull = true)\n public String name;\n \n @Column(name = \"_age\")\n public int age;\n// \n// public long getId() {\n// return id;\n// }\n// \n// public void setId(long id) {\n// this.id = id;\n// }\n// \n// public String getName() {\n// return name;\n// }\n// \n// public void setName(String name) {\n// this.name = name;\n// }\n// \n// public int getAge() {\n// return age;\n// }\n// \n// public void setAge(int age) {\n// this.age = age;\n// }\n}", "@Table(name = \"student\")\r\npublic class Student implements Serializable {\r\n \r\n private static final long serialVersionUID = 8010508999597447226L;\r\n \r\n @Column(name = \"_id\", id = true)\r\n public long id;\r\n \r\n @Column(name=\"_name\")\r\n public String name;\r\n \r\n @Column(name = \"_age\")\r\n public int age;\r\n \r\n @Column(name = \"_phone\")\r\n public String phone;\r\n \r\n public String address;\r\n \r\n// public long getId() {\r\n// return id;\r\n// }\r\n// \r\n// public void setId(long id) {\r\n// this.id = id;\r\n// }\r\n// \r\n// public String getName() {\r\n// return name;\r\n// }\r\n// \r\n// public void setName(String name) {\r\n// this.name = name;\r\n// }\r\n// \r\n// public int getAge() {\r\n// return age;\r\n// }\r\n// \r\n// public void setAge(int age) {\r\n// this.age = age;\r\n// }\r\n// \r\n// public String getPhone() {\r\n// return phone;\r\n// }\r\n// \r\n// public void setPhone(String phone) {\r\n// this.phone = phone;\r\n// }\r\n// \r\n// public String getAddress() {\r\n// return address;\r\n// }\r\n// \r\n// public void setAddress(String address) {\r\n// this.address = address;\r\n// }\r\n public static void main(String[] args) {\r\n List<String> cols = Mapping.getInstance().getColumns(null, Student.class);\r\n System.out.println(cols);\r\n }\r\n}\r", "public class MockDatabase extends SQLiteDatabase {\n \n public MockDatabase(String path) {\n super(path);\n dbName = path;\n }\n \n String dbName;\n Map<String, MockCursor> tables = new HashMap<String, MockCursor>();\n \n public void addTable(String table, Class<?> clazz) {\n MockCursor c = tables.get(table);\n Class<?> tableClass = Mapping.getInstance().getTableClass(table);\n if (c == null) {\n List<String> cols = Mapping.getInstance().getColumns(null, clazz);\n c = new MockCursor(cols.toArray(new String[cols.size()]));\n tables.put(table, c);\n }\n }\n \n public long insert(String table, String nullColumnHack,\n ContentValues values) {\n MockCursor c = tables.get(table);\n String[] cols = c.getColumnNames();\n Object[] args = new Object[cols.length];\n int i = 0;\n for (String key : cols) {\n args[i++] = values.get(key);\n }\n Class<?> clazz = Mapping.getInstance().getTableClass(table);\n String pkc = Mapping.getInstance().getPK(clazz);\n int idx = c.getColumnIndex(pkc);\n args[idx] = c.getCount() + 1;\n c.addRow(args);\n return c.getRowSize();\n }\n \n public int update(String table, ContentValues values, String where,\n String[] args) {\n String query = where;\n if (args != null) {\n for (String a : args) {\n query = query.replaceFirst(\"\\\\?\", a);\n }\n }\n // TODO \n // HashMap<String, Object> vs = new HashMap<String, Object>();\n \n return 0;\n }\n \n public int delete(String table, String where, String[] args) {\n return 0;\n }\n \n @Override\n public Cursor query(boolean distinct, String table, String[] columns,\n String selection, String[] selectionArgs, String groupBy,\n String having, String orderBy, String limit) {\n \n MockCursor sub = new MockCursor(columns);\n MockCursor full = tables.get(table);\n // make full rows;\n ArrayList<Object[]> rows = new ArrayList<Object[]>();\n for (int j = 0; j < full.getCount(); j++) {\n ArrayList<Object> list = new ArrayList<Object>();\n for (int i = 0; i < sub.getColumnCount(); i++) {\n String c = sub.getColumnName(i);\n int idx = full.getColumnIndex(c);\n if (idx >= 0) {\n list.add(full.getString(idx));\n }\n else {\n list.add(null);\n }\n }\n rows.add(list.toArray(new Object[list.size()]));\n }\n // has where\n if (selection != null) {\n String[] where = selection.split(\"=\");\n String c = where[0].trim();\n String v = where[1].trim();\n if (\"?\".equals(v)) {\n v = selectionArgs[0];\n }\n \n for (int i = 0; i < rows.size(); i++) {\n Object[] row = rows.get(i);\n int idx = sub.getColumnIndex(c);\n if (idx >= 0) {\n Object o = row[idx];\n if (v.equals(o)) {\n sub.addRow(row);\n }\n }\n }\n }\n else {\n for (Object[] objects : rows) {\n sub.addRow(objects);\n }\n }\n \n return sub;\n }\n \n public Cursor rawQuery(String sql, String[] args) {\n Matcher m = Pattern.compile(\"(.*)LIMIT (\\\\d+) OFFSET (\\\\d+)\")\n .matcher(sql);\n int offset = 0;\n int limit = 0;\n if (m.find()) {\n String[] limitStr = m.replaceAll(\"$2-$3\").split(\"-\");\n limit = Integer.parseInt(limitStr[0]);\n offset = Integer.parseInt(limitStr[1]);\n sql = m.replaceAll(\"$1\");\n }\n String key = \"SELECT DISTINCT \";\n int pos = sql.indexOf(key);\n int start = 0;\n if (pos < 0) {\n key = \"SELECT \";\n pos = sql.indexOf(key);\n }\n start = pos + key.length();\n \n key = \" FROM \";\n int end = sql.indexOf(key);\n String cs = sql.substring(start, end);\n String[] temp = cs.split(\",\");\n for (int i = 0; i < temp.length; i++) {\n temp[i] = temp[i].trim();\n }\n \n sql = sql.substring(end + key.length());\n start = 0;\n end = sql.indexOf(\" \");\n String table = end > 0 ? sql.substring(start, end) : sql;\n \n key = \"WHERE \";\n start = sql.indexOf(key);\n MockCursor sub = new MockCursor(temp);\n MockCursor full = tables.get(table);\n \n ArrayList<Object[]> rows = new ArrayList<Object[]>();\n for (int j = 0; j < full.getCount(); j++) {\n full.setRowIndex(j);\n ArrayList<Object> list = new ArrayList<Object>();\n for (int i = 0; i < sub.getColumnCount(); i++) {\n String c = sub.getColumnName(i);\n int idx = full.getColumnIndex(c);\n if (idx >= 0) {\n list.add(full.getString(idx));\n }\n }\n rows.add(list.toArray(new Object[list.size()]));\n }\n \n if (start > 0) {\n sql = sql.substring(start + key.length());\n String[] where = sql.split(\"=\");\n String c = where[0].trim();\n String v = where[1].trim().split(\" \")[0];\n if (\"?\".equals(v)) {\n v = args[0];\n }\n \n ArrayList<Object[]> dest = new ArrayList<Object[]>();\n int tmp = 0;\n for (int i = 0; i < rows.size(); i++) {\n Object[] row = rows.get(i);\n int idx = sub.getColumnIndex(c);\n if (idx >= 0) {\n Object o = row[idx];\n if (v.equals(o)) {\n if (tmp < offset) {\n tmp++;\n continue;\n }\n if (limit > 0 && sub.getRowSize() >= limit) {\n break;\n }\n dest.add(row);\n sub.addRow(row);\n }\n }\n }\n }\n else {\n for (int i = 0; i < rows.size(); i++) {\n if (i < offset) {\n continue;\n }\n if (limit > 0 && sub.getRowSize() >= limit) {\n break;\n }\n sub.addRow(rows.get(i));\n }\n }\n \n return sub;\n }\n \n public void execSQL(String sql) {\n }\n \n public void execSQL(String sql, Object[] args) {\n \n }\n \n private void updateRow(MockCursor c) {\n \n }\n}", "public class MockOpenHelper extends SQLiteOpenHelper {\n \n private MockDatabase db;\n \n public MockOpenHelper(String name) {\n this(name, 0);\n }\n \n public MockOpenHelper(String name, int version) {\n super(name, version);\n this.db = new MockDatabase(name);\n }\n \n @Override\n public SQLiteDatabase getReadableDatabase() {\n return db;\n }\n \n @Override\n public SQLiteDatabase getWritableDatabase() {\n return db;\n }\n}" ]
import java.util.ArrayList; import java.util.List; import org.junit.Assert; import android.content.ContentValues; import cn.ieclipse.aorm.bean.Course; import cn.ieclipse.aorm.bean.Grade; import cn.ieclipse.aorm.bean.Person; import cn.ieclipse.aorm.bean.Student; import cn.ieclipse.aorm.test.MockDatabase; import cn.ieclipse.aorm.test.MockOpenHelper; import junit.framework.TestCase;
/* * Copyright 2010-2014 Jamling([email protected]). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.ieclipse.aorm; /** * @author Jamling * */ public class SessionTest extends TestCase { private Session session; private MockDatabase db; @Override protected void setUp() throws Exception { super.setUp(); MockOpenHelper openHelper = new MockOpenHelper("test.db"); db = (MockDatabase) openHelper.getReadableDatabase(); db.addTable("person", Person.class); db.addTable("student", Student.class);
db.addTable("grade", Grade.class);
2
ls1intum/jReto
Source/src/de/tum/in/www1/jReto/routing/packets/LinkStatePacket.java
[ "public class Constants {\n\tpublic static final int PACKET_TYPE_SIZE = 4;\n\tpublic static final int INT_SIZE = 4;\n\tpublic static final int UUID_SIZE = 16;\n}", "public class DataChecker {\n /**\n * Verifies that the data (wrapped in a DataReader) has the expected packet type, and has the minimum required lenght (i.e. number of bytes).\n * @param data The data to check\n * @param expectedType The type the packet is expected to have\n * @param minimumLength The minimum length required for the packet to be valid\n * @return Whether the conditions are met\n */\n\tpublic static boolean check(DataReader data, PacketType expectedType, int minimumLength) {\n\t\tif (!data.checkRemaining(minimumLength)) {\n\t\t\tSystem.err.println(\"Basic data check failed: Not enough data remaining. Needed: \"+minimumLength+\", available: \"+data.getRemainingBytes());\n\t\t\treturn false;\n\t\t}\n\t\tPacketType type = data.getPacketType();\n\t\tif (type != expectedType) {\n\t\t\tSystem.err.println(\"Basic data check failed: Unexpected type. Expected: \"+expectedType+\". Received: \"+type);\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\treturn true;\n\t}\n}", "public class DataReader {\n\tprivate final ByteBuffer data;\n\t\n /** Constructs a DataReader from an ByteBuffer object. */\n\tpublic DataReader(ByteBuffer data) {\n\t\tdata.order(ByteOrder.LITTLE_ENDIAN);\n\t\tthis.data = data;\n\t}\n /**\n * Checks whether more than length bytes can still be read.\n * @param length The number of bytes to check\n * @return true if more than or equal to length bytes can still be read.\n */\n\tpublic boolean checkRemaining(int minimumRemainingBytes) {\n\t\treturn this.data.remaining() >= minimumRemainingBytes;\n\t}\n /**\n * The number of remaining bytes to be read.\n */\n\tpublic int getRemainingBytes() {\n\t\treturn this.data.remaining();\n\t}\n /**\n * Resets the position to zero.\n */\n\tpublic void rewind() {\n\t\tthis.data.rewind();\n\t}\n\t/**\n\t * Reads a PacketType.\n\t * */\n\tpublic PacketType getPacketType() {\n\t\treturn PacketType.fromRaw(this.getInt());\n\t}\n /** \n * Returns the next 4 byte integer.\n */\n\tpublic int getInt() {\n\t\treturn this.data.getInt();\n\t}\n /**\n * Reads an UUID.\n */\n\tpublic UUID getUUID() {\n\t\treturn new UUID(this.data.getLong(), this.data.getLong());\n\t}\n /**\n * Returns all remaining data.\n */\n\tpublic ByteBuffer getRemainingData() {\n\t\tByteBuffer data = this.data.slice();\n\t\tdata.order(ByteOrder.LITTLE_ENDIAN);\n\t\treturn data;\n\t}\n}", "public class DataWriter {\n\tprivate final ByteBuffer data;\n\t\n /** Constructs a data writer with a given length. */\n\tpublic DataWriter(int length) {\n\t\tthis.data = ByteBuffer.allocate(length);\n\t\tthis.data.order(ByteOrder.LITTLE_ENDIAN);\n\t}\n\t/** Appends a PacketType */\n\tpublic void add(PacketType type) {\n\t\tthis.add(type.toRaw());\n\t}\n /** Appends a 4 byte integer */\n\tpublic void add(int integer) {\n\t\tthis.data.putInt(integer);\n\t}\n /** Appends an UUID */\n\tpublic void add(UUID uuid) {\n\t\tthis.data.putLong(uuid.getMostSignificantBits());\n\t\tthis.data.putLong(uuid.getLeastSignificantBits());\n\t}\n /** Appends a ByteBuffer object. */\n\tpublic void add(ByteBuffer data) {\n\t\tthis.data.put(data);\n\t}\n\t\n /** Returns all data that was written. */\n\tpublic ByteBuffer getData() {\n\t\tthis.data.rewind();\n\t\treturn this.data;\n\t}\n}", "public interface Packet {\n\tpublic ByteBuffer serialize();\n}", "public enum PacketType {\t\t\n\tUNKNOWN(0),\n\t\n\t// Routing Layer\n\tLINK_HANDHAKE(1),\n\tROUTING_HANDSHAKE(2),\n\tLINK_STATE(3),\n\tFLOODED_PACKET(4),\n\tROUTED_CONNECTION_ESTABLISHED_CONFIRMATION(5),\n\t\n\t// Connectivity\n\tMANAGED_CONNECTION_HANDSHAKE(10),\n\tCLOSE_REQUEST(11),\n\tCLOSE_ANNOUNCE(12),\n\tCLOSE_ACKNOWLEDGE(13),\n\t\n\t// Data transmission\n\tTRANSFER_STARTED(20),\n\tDATA_PACKET(21),\n\tCANCELLED_TRANSFER(22),\n\tPROGRESS_INFORMATION(23);\n\t\n\tprivate static final Map<Integer, PacketType> intToTypeMap = new HashMap<Integer, PacketType>();\n\tstatic {\n\t for (PacketType type : PacketType.values()) {\n\t intToTypeMap.put(type.value, type);\n\t }\n\t}\n\t\n\tprivate final int value;\n\t\n\tPacketType(int value) {\n\t\tthis.value = value;\n\t}\n\tpublic static PacketType fromRaw(int value) {\n\t\tPacketType result = intToTypeMap.get(value);\n\t\tif (result == null) result = PacketType.UNKNOWN;\n\t\treturn result;\n\t}\n\tpublic static PacketType fromData(ByteBuffer data) {\n\t\tif (data.remaining() < 4) {\n\t\t\tSystem.err.println(\"Insufficient data to get packet type.\");\n\t\t\treturn PacketType.UNKNOWN;\n\t\t}\n\t\t\n\t\tint value = data.getInt();\n\t\tdata.rewind();\n\t\tPacketType type = PacketType.fromRaw(value);\n\t\t\n\t\tif (type == PacketType.UNKNOWN) {\n\t\t\tSystem.err.println(\"Read unknown type, value was: \"+value);\n\t\t}\n\t\t\n\t\treturn type;\n\t}\n\tpublic int toRaw() {\n\t\treturn this.value;\n\t}\n}", "public class LinkStateRoutingTable<T> {\n\t/**\n\t * A Change object contains changes that occurred in the routing table caused by some operation.\n\t * */\n\tpublic static class Change<T> {\n\t\t/**\n\t\t * Contains information about nodes that became reachable.\n\t\t * */\n\t\tpublic static class NowReachableInformation<T> {\n\t\t\t/** The node that became reachable */\n\t\t\tpublic final T node;\n\t\t\t/** The node that is the next hop for reaching this node. */\n\t\t\tpublic final T nextHop;\n\t\t\t/** The total cost for reaching this node. */\n\t\t\tpublic final double cost;\n\t\t\t\n\t\t\t/** Constructs a new NowReachableInformation object. */\n\t\t\tpublic NowReachableInformation(T node, T nextHop, double cost) {\n\t\t\t\tthis.node = node;\n\t\t\t\tthis.nextHop = nextHop;\n\t\t\t\tthis.cost = cost;\n\t\t\t}\n\t\t}\n\t\t/**\n\t\t * Contains informatiown about nodes that have changed routes.\n\t\t * */\n\t\tpublic static class RouteChangedInformation<T> {\n\t\t\t/** The node that became reachable */\n\t\t\tpublic final T node;\n\t\t\t/** The node that is the next hop for reaching this node. */\n\t\t\tpublic final T nextHop;\n\t\t\t/** The previous total cost for reaching this node. */\n\t\t\tpublic final double oldCost;\n\t\t\t/** The total cost for reaching this node. */\n\t\t\tpublic final double cost;\n\t\t\t\n\t\t\t/** Constructs a new RouteChangedInformation object. */\n\t\t\tpublic RouteChangedInformation(T node, T nextHop, double oldCost, double cost) {\n\t\t\t\tthis.node = node;\n\t\t\t\tthis.nextHop = nextHop;\n\t\t\t\tthis.oldCost = oldCost;\n\t\t\t\tthis.cost = cost;\n\t\t\t}\n\t\t}\n\t\t\n\t\t/** Contains information about all nodes that are now reachable. */\n\t\tpublic final List<NowReachableInformation<T>> nowReachable;\n\t\t/** Contains all nodes that are now unreachable. */\n\t\tpublic final List<T> nowUnreachable;\n\t\t/** Contains information about all nodes that have changed routes. */\n\t\tpublic final List<RouteChangedInformation<T>> routeChanged;\n\t\t\n\t\t/** Constructs a new Change object. */\n\t\tpublic Change(List<NowReachableInformation<T>> nowReachable, List<T> nowUnreachable, List<RouteChangedInformation<T>> routeChanged) {\n\t\t\tthis.nowReachable = nowReachable;\n\t\t\tthis.nowUnreachable = nowUnreachable;\n\t\t\tthis.routeChanged = routeChanged;\n\t\t}\n\t\t\n\t\t/** Returns whether this Change object is actually empty. */\n\t\tpublic boolean isEmpty() {\n\t\t\treturn nowReachable.isEmpty() && nowUnreachable.isEmpty() && routeChanged.isEmpty();\n\t\t}\n\t}\n\t\n\t/**\n\t * Stores neighbor information (the neighbor itself and the cost of reaching the neighbor).\n\t * */\n\tpublic static class NeighborInformation<T> {\n\t\t/** The node object representing the neighbor. */\n\t\tpublic final T node;\n\t\t/** The cost of reaching this neighbor. */\n\t\tpublic final double cost;\n\t\t\n\t\t/** Constructs a new neighbor information object. */\n\t\tpublic NeighborInformation(T node, double cost) {\n\t\t\tthis.node = node;\n\t\t\tthis.cost = cost;\n\t\t}\n\t}\n\n\t/** A directed, weighted multigraph used to represent the network of nodes and their link states. */\n\tprivate final DirectedWeightedPseudograph<T, DefaultWeightedEdge> graph = new DirectedWeightedPseudograph<>(DefaultWeightedEdge.class);\n\t/** The local node. In all neighbor related operations, the neighbor is considered a neighbor of this node. */\n\tprivate final T localNode;\n\t\n\t/** Constructs a new LinkStateRoutingTable. */\n\tpublic LinkStateRoutingTable(T localNode) {\n\t\tthis.localNode = localNode;\n\t\tthis.graph.addVertex(localNode);\n\t}\n\t\n\t/**\n\t * Computes the changes to the routing table when updating or adding a new neighbor.\n\t * If the neighbor is not yet known to the routing table, it is added.\n\t * \n\t * @param neighbor The neighbor to update or add.\n\t * @param cost The cost to reach that neighbor.\n\t * @return A LinkStateRoutingTable.Change object representing the changes that occurred in the routing table.\n\t * */\n\tpublic Change<T> getRoutingTableChangeForNeighborUpdate(final T neighbor, final double cost) {\n\t\treturn this.trackGraphChanges(new Runnable() {\n\t\t\t@Override\n\t\t\tpublic void run() {\n\t\t\t\tLinkStateRoutingTable.this.updateNeighbor(neighbor, cost);\n\t\t\t}\n\t\t});\n\t}\n\t/**\n\t * Computes the changes to the routing table when removing a neighbor.\n\t * \n\t * @param neighbor The neighbor to remove\n\t * @return A LinkStateRoutingTable.Change object representing the changes that occurred in the routing table.\n\t * */\n\tpublic Change<T> getRoutingTableChangeForNeighborRemoval(final T neighbor) {\n\t\treturn this.trackGraphChanges(new Runnable() {\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void run() {\n\t\t\t\tLinkStateRoutingTable.this.removeNeighbor(neighbor);\n\t\t\t}\n\t\t});\n\t}\n\t/**\n\t * Computes the changes to the routing table when link state information is received for a given node.\n\t * \n\t * @param node The node for which a list of neighbors (ie. link state information) was received.\n\t * @param neighbors The node's neighbors.\n\t * @return A LinkStateRoutingTable.Change object representing the changes that occurred in the routing table.\n\t * */\n\tpublic Change<T> getRoutingTableChangeForLinkStateInformationUpdate(final T node, final List<NeighborInformation<T>> neighbors) {\n\t\treturn this.trackGraphChanges(new Runnable() {\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic void run() {\n\t\t\t\tLinkStateRoutingTable.this.updateLinkStateInformation(node, neighbors);\n\t\t\t}\n\t\t});\n\t}\n\t\n\t/** Returns a list of neighbors for the local node (ie. link state information). */\n\tpublic List<NeighborInformation<T>> getLinkStateInformation() {\n\t\tList<NeighborInformation<T>> linkStateInformation = new ArrayList<>();\n\t\t\n\t\tfor (DefaultWeightedEdge edge : this.graph.outgoingEdgesOf(this.localNode)) {\n\t\t\tlinkStateInformation.add(new NeighborInformation<T>(this.graph.getEdgeTarget(edge), this.graph.getEdgeWeight(edge)));\n\t\t}\n\t\t\n\t\treturn linkStateInformation;\n\t}\n\t\n\tpublic Tree<T> getNextHopTree(Set<T> destinations) {\n\t\tfor (T destination : destinations) {\n\t\t\tif (!this.graph.containsVertex(destination)) {\n\t\t\t\tSystem.err.println(\"You have attempted to connect to a destination that has not yet been added to the routing table. Most likely, it will be discovered soon.\");\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t\t\n\t\tSet<T> participatingNodes = new HashSet<>(destinations);\n\t\tparticipatingNodes.add(this.localNode);\n\t\t\n\t\treturn MinimumSteinerTreeApproximation.approximateSteinerTree(this.graph, localNode, participatingNodes);\n\t}\n\n\t/** Updates or adds a neighbor. */\n\tprivate void updateNeighbor(T neighbor, double cost) {\n\t\tif (this.graph.edgeSet().contains(neighbor)) this.graph.removeAllEdges(this.localNode, neighbor);\n\t\tthis.graph.addVertex(neighbor);\n\t\tDefaultWeightedEdge edge = this.graph.addEdge(this.localNode, neighbor);\n\t\tthis.graph.setEdgeWeight(edge, cost);\n\t}\n\t/** Removes a neighbor. */\n\tprivate void removeNeighbor(T neighbor) {\n\t\tthis.graph.removeAllEdges(this.localNode, neighbor);\n\t}\n\t/** Updates link state information for a given node. */\n\tprivate void updateLinkStateInformation(T node, List<NeighborInformation<T>> neighbors) {\n\t\t// Remove all edges\n\t\tif (this.graph.vertexSet().contains(node)) {\n\t\t\tSet<DefaultWeightedEdge> outgoingEdges = new HashSet<>(this.graph.outgoingEdgesOf(node));\n\t\t\tthis.graph.removeAllEdges(outgoingEdges);\n\t\t} else {\n\t\t\tthis.graph.addVertex(node);\n\t\t}\n\n\t\t// Add new edges\n\t\tfor (NeighborInformation<T> neighbor : neighbors) {\n\t\t\tthis.graph.addVertex(neighbor.node);\n\t\t\tDefaultWeightedEdge edge = this.graph.addEdge(node, neighbor.node);\n\t\t\tthis.graph.setEdgeWeight(edge, neighbor.cost);\n\t\t}\n\t}\n\t\n\t/**\n\t * Computes a Change object for arbitrary modifications of the graph.\n\t * \n\t * This method first computes the shortest paths to all reachable nodes in the graph, then runs the graph action, and then calculates all shortest paths again.\n\t * \n\t * From changes in which nodes are reachable, and changes in the paths, a LinkStateRoutingTable.Change object is created.\n\t * \n\t * @param graphAction A Runnable that is expected to perform some changes on the graph.\n\t * @return A LinkStateRoutingTable.Change object representing the changes caused by the changes performed by the graphAction.\n\t * */\n\tprivate Change<T> trackGraphChanges(Runnable graphAction) {\n\t\t// Compute shortest paths before and after execting the graph action\n\t\tMap<T, DijkstraShortestPath<T, DefaultWeightedEdge>> previousShortestPaths = new HashMap<>();\n\t\t\n\t\tfor (T node : graph.vertexSet()) {\n\t\t\tDijkstraShortestPath<T, DefaultWeightedEdge> shortestPath = new DijkstraShortestPath<T, DefaultWeightedEdge>(this.graph, this.localNode, node);\n\t\t\tif (shortestPath.getPath() != null) previousShortestPaths.put(node, shortestPath);\n\t\t}\n\n\t\tgraphAction.run();\n\t\t\n\t\tMap<T, DijkstraShortestPath<T, DefaultWeightedEdge>> updatedShortestPaths = new HashMap<>();\n\t\t\n\t\tfor (T node : graph.vertexSet()) {\n\t\t\tDijkstraShortestPath<T, DefaultWeightedEdge> shortestPath = new DijkstraShortestPath<T, DefaultWeightedEdge>(this.graph, this.localNode, node);\n\t\t\tif (shortestPath.getPath() != null) updatedShortestPaths.put(node, shortestPath);\n\t\t}\n\t\t\n\t\t// Compute routing table changes from shortest paths.\n\t\t\n\t\t// 1. Nodes that are now reachable but weren't before.\n\t\tList<NowReachableInformation<T>> nowReachable = new ArrayList<>();\n\t\tSet<T> nowReachableNodes = new HashSet<T>(updatedShortestPaths.keySet());\n\t\tnowReachableNodes.removeAll(previousShortestPaths.keySet());\n\t\tfor (T nowReachableNode : nowReachableNodes) {\n\t\t\tDijkstraShortestPath<T, DefaultWeightedEdge> shortestPath = updatedShortestPaths.get(nowReachableNode);\n\t\t\tDefaultWeightedEdge firstEdge = shortestPath.getPathEdgeList().get(0);\n\t\t\tnowReachable.add(new NowReachableInformation<T>(\n\t\t\t\tnowReachableNode, \n\t\t\t\tthis.graph.getEdgeTarget(firstEdge), \n\t\t\t\tshortestPath.getPathLength())\n\t\t\t);\n\t\t}\n\t\t\n\t\t// 2. Nodes that were reachable before, but are now unreachable.\n\t\tSet<T> nowUnreachableNodes = new HashSet<T>(previousShortestPaths.keySet());\n\t\tnowUnreachableNodes.removeAll(updatedShortestPaths.keySet());\n\t\tList<T> nowUnreachable = new ArrayList<T>(nowUnreachableNodes);\n\t\t\n\t\t// 3. Nodes that were and are still reachable, but have a changed route.\n\t\tSet<T> stillReachable = new HashSet<T>(previousShortestPaths.keySet());\n\t\tstillReachable.retainAll(updatedShortestPaths.keySet());\n\t\t\n\t\tList<RouteChangedInformation<T>> routeChanged = new ArrayList<>();\n\t\t\n\t\tfor (T node : stillReachable) {\n\t\t\tif (node == this.localNode) continue;\n\t\t\t\n\t\t\tDijkstraShortestPath<T, DefaultWeightedEdge> previousShortestPath = previousShortestPaths.get(node);\n\t\t\tDijkstraShortestPath<T, DefaultWeightedEdge> updatedShortestPath = updatedShortestPaths.get(node);\n\t\t\t\n\t\t\tboolean pathLengthChanged = previousShortestPath.getPathLength() != updatedShortestPath.getPathLength();\n\t\t\tboolean nextHopChanged = this.graph.getEdgeTarget(previousShortestPath.getPathEdgeList().get(0)) != this.graph.getEdgeTarget(updatedShortestPath.getPathEdgeList().get(0));\n\t\t\t\n\t\t\tif (pathLengthChanged || nextHopChanged) {\n\t\t\t\trouteChanged.add(new RouteChangedInformation<T>(\n\t\t\t\t\t\tnode, \n\t\t\t\t\t\tthis.graph.getEdgeTarget(updatedShortestPath.getPathEdgeList().get(0)), \n\t\t\t\t\t\tpreviousShortestPath.getPathLength(), \n\t\t\t\t\t\tupdatedShortestPath.getPathLength())\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn new Change<>(nowReachable, nowUnreachable, routeChanged);\n\t}\n}" ]
import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.UUID; import de.tum.in.www1.jReto.packet.Constants; import de.tum.in.www1.jReto.packet.DataChecker; import de.tum.in.www1.jReto.packet.DataReader; import de.tum.in.www1.jReto.packet.DataWriter; import de.tum.in.www1.jReto.packet.Packet; import de.tum.in.www1.jReto.packet.PacketType; import de.tum.in.www1.jReto.routing.algorithm.LinkStateRoutingTable;
package de.tum.in.www1.jReto.routing.packets; /** * A LinkState packet represents a peer's link state, i.e. a list of all of it's neighbors and the cost associated with reaching them. */ public class LinkStatePacket implements Packet { public final static PacketType TYPE = PacketType.LINK_STATE; public final static int MINIMUM_LENGTH = Constants.PACKET_TYPE_SIZE + Constants.UUID_SIZE + Constants.INT_SIZE; /** The identifier of the peer that generated the packet. */ public final UUID peerIdentifier; /** A list of identifier/cost pairs for each of the peer's neighbors. */ public final List<LinkStateRoutingTable.NeighborInformation<UUID>> neighbors; public LinkStatePacket(UUID peerIdentifier, List<LinkStateRoutingTable.NeighborInformation<UUID>> neighbors) { this.peerIdentifier = peerIdentifier; this.neighbors = neighbors; } public static LinkStatePacket deserialize(ByteBuffer data) {
DataReader reader = new DataReader(data);
2
GlitchCog/ChatGameFontificator
src/main/java/com/glitchcog/fontificator/gui/controls/panel/ControlPanelColor.java
[ "public class ConfigColor extends Config\n{\n private static final Logger logger = Logger.getLogger(ConfigColor.class);\n\n private Color bgColor;\n\n private Color fgColor;\n\n private Color borderColor;\n\n private Color highlight;\n\n private Color chromaColor;\n\n private List<Color> palette;\n\n private Boolean colorUsername;\n\n private Boolean colorTimestamp;\n\n private Boolean colorMessage;\n\n private Boolean colorJoin;\n\n private Boolean useTwitchColors;\n\n @Override\n public void reset()\n {\n this.bgColor = null;\n this.fgColor = null;\n this.borderColor = null;\n this.highlight = null;\n this.chromaColor = null;\n this.palette = null;\n this.colorUsername = null;\n this.colorTimestamp = null;\n this.colorMessage = null;\n this.colorJoin = null;\n this.useTwitchColors = null;\n }\n\n private void validateStrings(LoadConfigReport report, String palStr, String userBool, String timeBool, String msgBool, String joinBool, String twitchBool)\n {\n evaluateColorString(props, FontificatorProperties.KEY_COLOR_BG, report);\n evaluateColorString(props, FontificatorProperties.KEY_COLOR_FG, report);\n evaluateColorString(props, FontificatorProperties.KEY_COLOR_BORDER, report);\n evaluateColorString(props, FontificatorProperties.KEY_COLOR_HIGHLIGHT, report);\n evaluateColorString(props, FontificatorProperties.KEY_COLOR_CHROMA_KEY, report);\n\n validateBooleanStrings(report, userBool, timeBool, msgBool, joinBool, twitchBool);\n\n // An empty palette is allowed\n if (!palStr.trim().isEmpty())\n {\n String[] palColStrs = palStr.split(\",\");\n for (int i = 0; i < palColStrs.length; i++)\n {\n evaluateColorString(palColStrs[i], report);\n }\n }\n }\n\n @Override\n public LoadConfigReport load(Properties props, LoadConfigReport report)\n {\n logger.trace(\"Loading config color via raw properties object\");\n\n this.props = props;\n\n reset();\n\n // Check that the values exist\n baseValidation(props, FontificatorProperties.COLOR_KEYS_WITHOUT_PALETTE, report);\n\n if (report.isErrorFree())\n {\n final String paletteStr = props.getProperty(FontificatorProperties.KEY_COLOR_PALETTE);\n\n final String userBool = props.getProperty(FontificatorProperties.KEY_COLOR_USERNAME);\n final String timeBool = props.getProperty(FontificatorProperties.KEY_COLOR_TIMESTAMP);\n final String msgBool = props.getProperty(FontificatorProperties.KEY_COLOR_MESSAGE);\n final String joinBool = props.getProperty(FontificatorProperties.KEY_COLOR_JOIN);\n final String twitchBool = props.getProperty(FontificatorProperties.KEY_COLOR_TWITCH);\n\n // Check that the values are valid\n validateStrings(report, paletteStr, userBool, timeBool, msgBool, joinBool, twitchBool);\n\n // Fill the values\n if (report.isErrorFree())\n {\n bgColor = evaluateColorString(props, FontificatorProperties.KEY_COLOR_BG, report);\n fgColor = evaluateColorString(props, FontificatorProperties.KEY_COLOR_FG, report);\n borderColor = evaluateColorString(props, FontificatorProperties.KEY_COLOR_BORDER, report);\n highlight = evaluateColorString(props, FontificatorProperties.KEY_COLOR_HIGHLIGHT, report);\n chromaColor = evaluateColorString(props, FontificatorProperties.KEY_COLOR_CHROMA_KEY, report);\n\n palette = new ArrayList<Color>();\n String[] palColStrs = paletteStr.isEmpty() ? new String[] {} : paletteStr.split(\",\");\n for (int i = 0; i < palColStrs.length; i++)\n {\n Color palAddition = evaluateColorString(palColStrs[i], report);\n if (palAddition != null)\n {\n palette.add(palAddition);\n }\n }\n\n colorUsername = evaluateBooleanString(props, FontificatorProperties.KEY_COLOR_USERNAME, report);\n colorTimestamp = evaluateBooleanString(props, FontificatorProperties.KEY_COLOR_TIMESTAMP, report);\n colorMessage = evaluateBooleanString(props, FontificatorProperties.KEY_COLOR_MESSAGE, report);\n colorJoin = evaluateBooleanString(props, FontificatorProperties.KEY_COLOR_JOIN, report);\n useTwitchColors = evaluateBooleanString(props, FontificatorProperties.KEY_COLOR_TWITCH, report);\n }\n }\n\n return report;\n }\n\n public Color getBgColor()\n {\n return bgColor;\n }\n\n public void setBgColor(Color bgColor)\n {\n this.bgColor = bgColor;\n props.setProperty(FontificatorProperties.KEY_COLOR_BG, getColorHex(bgColor));\n }\n\n public Color getFgColor()\n {\n return fgColor;\n }\n\n public void setFgColor(Color fgColor)\n {\n this.fgColor = fgColor;\n props.setProperty(FontificatorProperties.KEY_COLOR_FG, getColorHex(fgColor));\n }\n\n public Color getBorderColor()\n {\n return borderColor;\n }\n\n public void setBorderColor(Color borderColor)\n {\n this.borderColor = borderColor;\n props.setProperty(FontificatorProperties.KEY_COLOR_BORDER, getColorHex(borderColor));\n }\n\n public Color getHighlight()\n {\n return highlight;\n }\n\n public void setHighlight(Color highlight)\n {\n this.highlight = highlight;\n props.setProperty(FontificatorProperties.KEY_COLOR_HIGHLIGHT, getColorHex(highlight));\n }\n\n public Color getChromaColor()\n {\n return chromaColor;\n }\n\n public void setChromaColor(Color chromaColor)\n {\n this.chromaColor = chromaColor;\n props.setProperty(FontificatorProperties.KEY_COLOR_CHROMA_KEY, getColorHex(chromaColor));\n }\n\n public List<Color> getPalette()\n {\n return palette == null ? new ArrayList<Color>() : palette;\n }\n\n public void setPalette(List<Color> palette)\n {\n this.palette = palette;\n String paletteString = \"\";\n for (int i = 0; i < palette.size(); i++)\n {\n paletteString += (i == 0 ? \"\" : \",\") + getColorHex(palette.get(i));\n }\n props.setProperty(FontificatorProperties.KEY_COLOR_PALETTE, paletteString);\n }\n\n public boolean isColorUsername()\n {\n return colorUsername;\n }\n\n public void setColorUsername(Boolean colorUsername)\n {\n this.colorUsername = colorUsername;\n props.setProperty(FontificatorProperties.KEY_COLOR_USERNAME, Boolean.toString(colorUsername));\n }\n\n public boolean isColorTimestamp()\n {\n return colorTimestamp;\n }\n\n public void setColorTimestamp(Boolean colorTimestamp)\n {\n this.colorTimestamp = colorTimestamp;\n props.setProperty(FontificatorProperties.KEY_COLOR_TIMESTAMP, Boolean.toString(colorTimestamp));\n }\n\n public boolean isColorMessage()\n {\n return colorMessage;\n }\n\n public void setColorMessage(Boolean colorMessage)\n {\n this.colorMessage = colorMessage;\n props.setProperty(FontificatorProperties.KEY_COLOR_MESSAGE, Boolean.toString(colorMessage));\n }\n\n public boolean isColorJoin()\n {\n return colorJoin;\n }\n\n public void setColorJoin(Boolean colorJoin)\n {\n this.colorJoin = colorJoin;\n props.setProperty(FontificatorProperties.KEY_COLOR_JOIN, Boolean.toString(colorJoin));\n }\n\n public boolean isUseTwitchColors()\n {\n return useTwitchColors;\n }\n\n public void setUseTwitchColors(Boolean useTwitchColors)\n {\n this.useTwitchColors = useTwitchColors;\n props.setProperty(FontificatorProperties.KEY_COLOR_TWITCH, Boolean.toString(useTwitchColors));\n }\n\n public static String getColorHex(Color c)\n {\n return String.format(\"%06X\", (0xFFFFFF & c.getRGB()));\n }\n}", "public class FontificatorProperties extends Properties\n{\n private static final Logger logger = Logger.getLogger(FontificatorProperties.class);\n\n private static final long serialVersionUID = 1L;\n\n /**\n * Copy of properties to compare with when checking if there have been changes\n */\n private FontificatorProperties lastSavedCopy;\n\n private final static String ENC_PASSWORD = \"Eastmost penninsula is the secret.\";\n\n /**\n * The name of the file that holds the location of the last file saved or loaded by a user, to be used when the\n * program starts to automatically load the previously used configuration\n */\n private static final String CONFIG_FILE_LAST_LOCATION = \".fontificator.conf\";\n\n public static final String KEY_IRC_USER = \"ircUser\";\n public static final String KEY_IRC_HOST = \"ircHost\";\n public static final String KEY_IRC_PORT = \"ircPort\";\n public static final String KEY_IRC_AUTH = \"ircAuth\";\n public static final String KEY_IRC_ANON = \"ircAnon\";\n public static final String KEY_IRC_CHAN = \"ircChannel\";\n public static final String KEY_IRC_AUTO_RECONNECT = \"ircAutoReconnect\";\n\n public static final String[] IRC_KEYS = new String[] { KEY_IRC_USER, KEY_IRC_HOST, KEY_IRC_PORT, KEY_IRC_AUTH, KEY_IRC_ANON, KEY_IRC_CHAN, KEY_IRC_AUTO_RECONNECT };\n\n public static final String KEY_FONT_FILE_BORDER = \"fontBorderFile\";\n public static final String KEY_FONT_FILE_FONT = \"fontFile\";\n public static final String KEY_FONT_TYPE = \"fontType\";\n public static final String KEY_FONT_GRID_WIDTH = \"fontGridWidth\";\n public static final String KEY_FONT_GRID_HEIGHT = \"fontGridHeight\";\n public static final String KEY_FONT_SCALE = \"fontScale\";\n public static final String KEY_FONT_BORDER_SCALE = \"fontBorderScale\";\n public static final String KEY_FONT_BORDER_INSET_X = \"fontBorderInsetX\";\n public static final String KEY_FONT_BORDER_INSET_Y = \"fontBorderInsetY\";\n public static final String KEY_FONT_SPACE_WIDTH = \"fontSpaceWidth\";\n public static final String KEY_FONT_BASELINE_OFFSET = \"fontBaselineOffset\";\n public static final String KEY_FONT_UNKNOWN_CHAR = \"fontUnknownChar\";\n public static final String KEY_FONT_EXTENDED_CHAR = \"fontExtendedChar\";\n public static final String KEY_FONT_CHARACTERS = \"fontCharacters\";\n public static final String KEY_FONT_SPACING_LINE = \"fontLineSpacing\";\n public static final String KEY_FONT_SPACING_CHAR = \"fontCharSpacing\";\n public static final String KEY_FONT_SPACING_MESSAGE = \"fontMessageSpacing\";\n\n public static final String[] FONT_KEYS = new String[] { KEY_FONT_FILE_BORDER, KEY_FONT_FILE_FONT, KEY_FONT_TYPE, KEY_FONT_GRID_WIDTH, KEY_FONT_GRID_HEIGHT, KEY_FONT_SCALE, KEY_FONT_BORDER_SCALE, KEY_FONT_BORDER_INSET_X, KEY_FONT_BORDER_INSET_Y, KEY_FONT_SPACE_WIDTH, KEY_FONT_BASELINE_OFFSET, KEY_FONT_UNKNOWN_CHAR, KEY_FONT_EXTENDED_CHAR, KEY_FONT_CHARACTERS, KEY_FONT_SPACING_LINE, KEY_FONT_SPACING_CHAR, KEY_FONT_SPACING_MESSAGE };\n\n public static final String KEY_CHAT_SCROLL = \"chatScrollEnabled\";\n public static final String KEY_CHAT_RESIZABLE = \"chatResizable\";\n public static final String KEY_CHAT_POSITION = \"chatPosition\";\n public static final String KEY_CHAT_POSITION_X = \"chatPositionX\";\n public static final String KEY_CHAT_POSITION_Y = \"chatPositionY\";\n public static final String KEY_CHAT_FROM_BOTTOM = \"chatFromBottom\";\n public static final String KEY_CHAT_WINDOW_WIDTH = \"chatWidth\"; // Legacy, no longer saved, used for chat window, not chat window content pane\n public static final String KEY_CHAT_WINDOW_HEIGHT = \"chatHeight\"; // Legacy, no longer saved, used for chat window, not chat window content pane\n public static final String KEY_CHAT_WIDTH = \"chatPixelWidth\";\n public static final String KEY_CHAT_HEIGHT = \"chatPixelHeight\";\n public static final String KEY_CHAT_CHROMA_ENABLED = \"chromaEnabled\";\n public static final String KEY_CHAT_INVERT_CHROMA = \"invertChroma\";\n public static final String KEY_CHAT_REVERSE_SCROLLING = \"reverseScrolling\";\n public static final String KEY_CHAT_CHROMA_LEFT = \"chromaLeft\";\n public static final String KEY_CHAT_CHROMA_TOP = \"chromaTop\";\n public static final String KEY_CHAT_CHROMA_RIGHT = \"chromaRight\";\n public static final String KEY_CHAT_CHROMA_BOTTOM = \"chromaBottom\";\n public static final String KEY_CHAT_CHROMA_CORNER = \"chromaCornerRadius\";\n public static final String KEY_CHAT_ALWAYS_ON_TOP = \"chatAlwaysOnTop\";\n public static final String KEY_CHAT_ANTIALIAS = \"chatAntialias\";\n\n public static final String[] CHAT_KEYS = new String[] { KEY_CHAT_SCROLL, KEY_CHAT_RESIZABLE, KEY_CHAT_POSITION, KEY_CHAT_POSITION_X, KEY_CHAT_POSITION_Y, KEY_CHAT_FROM_BOTTOM, KEY_CHAT_WIDTH, KEY_CHAT_HEIGHT, KEY_CHAT_CHROMA_ENABLED, KEY_CHAT_INVERT_CHROMA, KEY_CHAT_REVERSE_SCROLLING, KEY_CHAT_CHROMA_LEFT, KEY_CHAT_CHROMA_TOP, KEY_CHAT_CHROMA_RIGHT, KEY_CHAT_CHROMA_BOTTOM, KEY_CHAT_CHROMA_CORNER, KEY_CHAT_ALWAYS_ON_TOP, KEY_CHAT_ANTIALIAS };\n\n public static final String[] CHAT_KEYS_EXCEPT_WINDOW_POSITION = new String[] { KEY_CHAT_SCROLL, KEY_CHAT_RESIZABLE, KEY_CHAT_POSITION, KEY_CHAT_FROM_BOTTOM, KEY_CHAT_WIDTH, KEY_CHAT_HEIGHT, KEY_CHAT_CHROMA_ENABLED, KEY_CHAT_INVERT_CHROMA, KEY_CHAT_REVERSE_SCROLLING, KEY_CHAT_CHROMA_LEFT, KEY_CHAT_CHROMA_TOP, KEY_CHAT_CHROMA_RIGHT, KEY_CHAT_CHROMA_BOTTOM, KEY_CHAT_CHROMA_CORNER, KEY_CHAT_ALWAYS_ON_TOP, KEY_CHAT_ANTIALIAS };\n\n public static final String KEY_COLOR_BG = \"colorBackground\";\n public static final String KEY_COLOR_FG = \"colorForeground\";\n public static final String KEY_COLOR_BORDER = \"colorBorder\";\n public static final String KEY_COLOR_HIGHLIGHT = \"colorHighlight\";\n public static final String KEY_COLOR_CHROMA_KEY = \"chromaKey\";\n public static final String KEY_COLOR_PALETTE = \"colorPalette\";\n public static final String KEY_COLOR_USERNAME = \"colorUsername\";\n public static final String KEY_COLOR_TIMESTAMP = \"colorTimestamp\";\n public static final String KEY_COLOR_MESSAGE = \"colorMessage\";\n public static final String KEY_COLOR_JOIN = \"colorJoin\";\n public static final String KEY_COLOR_TWITCH = \"colorUseTwitch\";\n\n public static final String[] COLOR_KEYS = new String[] { KEY_COLOR_BG, KEY_COLOR_FG, KEY_COLOR_BORDER, KEY_COLOR_HIGHLIGHT, KEY_COLOR_CHROMA_KEY, KEY_COLOR_PALETTE, KEY_COLOR_USERNAME, KEY_COLOR_TIMESTAMP, KEY_COLOR_MESSAGE, KEY_COLOR_JOIN, KEY_COLOR_TWITCH };\n\n public static final String[] COLOR_KEYS_WITHOUT_PALETTE = new String[] { KEY_COLOR_BG, KEY_COLOR_FG, KEY_COLOR_BORDER, KEY_COLOR_HIGHLIGHT, KEY_COLOR_CHROMA_KEY, KEY_COLOR_USERNAME, KEY_COLOR_TIMESTAMP, KEY_COLOR_MESSAGE, KEY_COLOR_JOIN, KEY_COLOR_TWITCH };\n\n public static final String KEY_MESSAGE_JOIN = \"messageShowJoin\";\n public static final String KEY_MESSAGE_USERNAME = \"messageShowUsername\";\n public static final String KEY_MESSAGE_TIMESTAMP = \"messageShowTimestamp\";\n public static final String KEY_MESSAGE_USERFORMAT = \"messageUsernameFormat\";\n public static final String KEY_MESSAGE_TIMEFORMAT = \"messageTimestampFormat\";\n public static final String KEY_MESSAGE_CONTENT_BREAK = \"messageContentBreak\";\n public static final String KEY_MESSAGE_QUEUE_SIZE = \"messageQueueSize\";\n public static final String KEY_MESSAGE_SPEED = \"messageSpeed\";\n public static final String KEY_MESSAGE_EXPIRATION_TIME = \"messageExpirationTime\";\n public static final String KEY_MESSAGE_HIDE_EMPTY_BORDER = \"messageHideEmptyBorder\";\n public static final String KEY_MESSAGE_HIDE_EMPTY_BACKGROUND = \"messageHideEmptyBackground\";\n public static final String KEY_MESSAGE_CASE_TYPE = \"messageUserCase\";\n public static final String KEY_MESSAGE_CASE_SPECIFY = \"messageUserCaseSpecify\";\n public static final String KEY_MESSAGE_CASING = \"messageCasing\";\n\n public static final String[] MESSAGE_KEYS = new String[] { KEY_MESSAGE_JOIN, KEY_MESSAGE_USERNAME, KEY_MESSAGE_TIMESTAMP, KEY_MESSAGE_USERFORMAT, KEY_MESSAGE_TIMEFORMAT, KEY_MESSAGE_CONTENT_BREAK, KEY_MESSAGE_QUEUE_SIZE, KEY_MESSAGE_SPEED, KEY_MESSAGE_EXPIRATION_TIME, KEY_MESSAGE_HIDE_EMPTY_BORDER, KEY_MESSAGE_HIDE_EMPTY_BACKGROUND, KEY_MESSAGE_CASE_TYPE, KEY_MESSAGE_CASE_SPECIFY, KEY_MESSAGE_CASING };\n\n public static final String KEY_EMOJI_ENABLED = \"emojiEnabled\";\n public static final String KEY_EMOJI_ANIMATION = \"emojiAnimationEnabled\";\n public static final String KEY_EMOJI_TWITCH_BADGES = \"badgesEnabled\";\n public static final String KEY_EMOJI_FFZ_BADGES = \"badgesFfzEnabled\";\n public static final String KEY_EMOJI_SCALE_TO_LINE = \"emojiScaleToLine\";\n public static final String KEY_EMOJI_BADGE_SCALE_TO_LINE = \"badgeScaleToLine\";\n public static final String KEY_EMOJI_BADGE_HEIGHT_OFFSET = \"badgeHeightOffset\";\n public static final String KEY_EMOJI_SCALE = \"emojiScale\";\n public static final String KEY_EMOJI_BADGE_SCALE = \"badgeScale\";\n public static final String KEY_EMOJI_DISPLAY_STRAT = \"emojiDisplayStrat\";\n public static final String KEY_EMOJI_TWITCH_ENABLE = \"emojiTwitchEnabled\";\n public static final String KEY_EMOJI_TWITCH_CACHE = \"emojiTwitchCached\";\n public static final String KEY_EMOJI_FFZ_ENABLE = \"emojiFfzEnabled\";\n public static final String KEY_EMOJI_FFZ_CACHE = \"emojiFfzCached\";\n public static final String KEY_EMOJI_BTTV_ENABLE = \"emojiBttvEnabled\";\n public static final String KEY_EMOJI_BTTV_CACHE = \"emojiBttvCached\";\n public static final String KEY_EMOJI_TWITTER_ENABLE = \"emojiTwitterEnabled\";\n\n public static final String[] EMOJI_KEYS = new String[] { KEY_EMOJI_ENABLED, KEY_EMOJI_ANIMATION, KEY_EMOJI_TWITCH_BADGES, KEY_EMOJI_FFZ_BADGES, KEY_EMOJI_SCALE_TO_LINE, KEY_EMOJI_BADGE_SCALE_TO_LINE, KEY_EMOJI_BADGE_HEIGHT_OFFSET, KEY_EMOJI_SCALE, KEY_EMOJI_BADGE_SCALE, KEY_EMOJI_DISPLAY_STRAT, KEY_EMOJI_TWITCH_ENABLE, KEY_EMOJI_TWITCH_CACHE, KEY_EMOJI_FFZ_ENABLE, KEY_EMOJI_FFZ_CACHE, KEY_EMOJI_BTTV_ENABLE, KEY_EMOJI_BTTV_CACHE, KEY_EMOJI_TWITTER_ENABLE };\n\n public static final String KEY_CENSOR_ENABLED = \"censorEnabled\";\n public static final String KEY_CENSOR_PURGE_ON_TWITCH_BAN = \"censorPurgeOnTwitchBan\";\n public static final String KEY_CENSOR_URL = \"censorUrl\";\n public static final String KEY_CENSOR_FIRST_URL = \"censorFirstUrl\";\n public static final String KEY_CENSOR_UNKNOWN_CHARS = \"censorUnknownChars\";\n public static final String KEY_CENSOR_UNKNOWN_CHARS_PERCENT = \"censorUnknownCharsPercent\";\n public static final String KEY_CENSOR_WHITE = \"censorWhitelist\";\n public static final String KEY_CENSOR_BLACK = \"censorBlacklist\";\n public static final String KEY_CENSOR_BANNED = \"censorBannedWords\";\n\n public static final String[] CENSOR_KEYS = new String[] { KEY_CENSOR_ENABLED, KEY_CENSOR_PURGE_ON_TWITCH_BAN, KEY_CENSOR_URL, KEY_CENSOR_FIRST_URL, KEY_CENSOR_UNKNOWN_CHARS, KEY_CENSOR_UNKNOWN_CHARS_PERCENT, KEY_CENSOR_WHITE, KEY_CENSOR_BLACK, KEY_CENSOR_BANNED };\n\n public static final String[][] ALL_KEYS_EXCEPT_CHAT_WINDOW_POSITION = new String[][] { IRC_KEYS, FONT_KEYS, CHAT_KEYS_EXCEPT_WINDOW_POSITION, COLOR_KEYS, MESSAGE_KEYS, EMOJI_KEYS, CENSOR_KEYS };\n\n public static final String[][] ALL_KEYS = new String[][] { IRC_KEYS, FONT_KEYS, CHAT_KEYS, COLOR_KEYS, MESSAGE_KEYS, EMOJI_KEYS, CENSOR_KEYS };\n\n /**\n * Get all the property keys to be tested to determine if two fProps are equal. The parameter FontificatorProperties\n * is to be used as a collection of configuration that is used to select which properties matter. For example, if\n * chat window position should be remembered or not, so if remember position is unchecked, it doesn't ask you to\n * save changes just because you moved the window.\n * \n * @param fProps\n * contains configuration to be used to determine which keys are needed\n * @return all keys to be tested for equals\n */\n private static String[][] getKeysForEqualsTest(FontificatorProperties fProps)\n {\n if (fProps != null && fProps.getChatConfig() != null && fProps.getChatConfig().isRememberPosition())\n {\n return ALL_KEYS_EXCEPT_CHAT_WINDOW_POSITION;\n }\n\n return ALL_KEYS;\n }\n\n private ConfigIrc ircConfig = new ConfigIrc();\n\n private ConfigFont fontConfig = new ConfigFont();\n\n private ConfigChat chatConfig = new ConfigChat();\n\n private ConfigColor colorConfig = new ConfigColor();\n\n private ConfigMessage messageConfig = new ConfigMessage();\n\n private ConfigEmoji emojiConfig = new ConfigEmoji();\n\n private ConfigCensor censorConfig = new ConfigCensor();\n\n public FontificatorProperties()\n {\n }\n\n @Override\n public void clear()\n {\n ircConfig.reset();\n fontConfig.reset();\n chatConfig.reset();\n colorConfig.reset();\n messageConfig.reset();\n emojiConfig.reset();\n censorConfig.reset();\n super.clear();\n }\n\n public ConfigIrc getIrcConfig()\n {\n return ircConfig;\n }\n\n public ConfigFont getFontConfig()\n {\n return fontConfig;\n }\n\n public ConfigChat getChatConfig()\n {\n return chatConfig;\n }\n\n public ConfigColor getColorConfig()\n {\n return colorConfig;\n }\n\n public ConfigMessage getMessageConfig()\n {\n return messageConfig;\n }\n\n public ConfigEmoji getEmojiConfig()\n {\n return emojiConfig;\n }\n\n public ConfigCensor getCensorConfig()\n {\n return censorConfig;\n }\n\n /**\n * Called whenever unsaved changes might be lost to let the user have the option to save them\n * \n * @param ctrlWindow\n * @return okayToContinue\n */\n public boolean checkForUnsavedProps(ControlWindow ctrlWindow, Component parent)\n {\n if (hasUnsavedChanges())\n {\n int response = JOptionPane.showConfirmDialog(parent, \"Save configuration changes?\", \"Unsaved Changes\", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);\n if (response == JOptionPane.YES_OPTION)\n {\n if (ctrlWindow.saveConfig())\n {\n return true;\n }\n }\n else if (response == JOptionPane.NO_OPTION)\n {\n return true;\n }\n\n return false;\n }\n else\n {\n return true;\n }\n }\n\n /**\n * Load configuration from the file indicated by the specified filename, or a preset file contained in the classpath\n * resource directory\n * \n * @param filename\n * @return report\n * @throws Exception\n */\n public LoadConfigReport loadFile(String filename) throws Exception\n {\n if (filename.startsWith(ConfigFont.INTERNAL_FILE_PREFIX))\n {\n final String plainFilename = filename.substring(ConfigFont.INTERNAL_FILE_PREFIX.length());\n\n if (getClass().getClassLoader().getResource(plainFilename) == null)\n {\n LoadConfigReport report = new LoadConfigReport();\n final String errorMsg = \"Preset theme \" + plainFilename + \" not found\";\n ChatWindow.popup.handleProblem(errorMsg);\n report.addError(errorMsg, LoadConfigErrorType.FILE_NOT_FOUND);\n return report;\n }\n\n InputStream is = getClass().getClassLoader().getResourceAsStream(plainFilename);\n LoadConfigReport report = loadFile(is, filename, true);\n\n if (report.isErrorFree())\n {\n // This is a temporary copy, not to be saved to the last saved file for loading next time, but to avoid\n // having to not save when switching between presets\n this.lastSavedCopy = getCopy();\n }\n\n is.close();\n return report;\n }\n else\n {\n return loadFile(new File(filename));\n }\n }\n\n /**\n * Load configuration from the specified file\n * \n * @param file\n * @return report\n * @throws Exception\n */\n public LoadConfigReport loadFile(File file) throws Exception\n {\n logger.trace(\"Loading file \" + file.getAbsolutePath());\n InputStream is = new FileInputStream(file);\n LoadConfigReport report = loadFile(is, file.getAbsolutePath(), false);\n is.close();\n return report;\n }\n\n /**\n * Load file from InputStream. Does not close InputStream\n * \n * @param is\n * @param filename\n * @param isPreset\n * @return report\n * @throws Exception\n */\n private LoadConfigReport loadFile(InputStream is, String filename, boolean isPreset) throws Exception\n {\n final String prevAuth = getProperty(KEY_IRC_AUTH);\n super.load(is);\n final String currAuth = getProperty(KEY_IRC_AUTH);\n\n // Only decrypt the auth token here if there wasn't a previously loaded one that was already decrypted. This is\n // determined by whether the previous authorization wasn't loaded (null) or if there has been a change. If the\n // inputstream data didn't have an auth token, then the previous and current ones will match, meaning a new one\n // wasn't loaded and there's no need to decrypt.\n if (prevAuth == null || !prevAuth.equals(currAuth))\n {\n decryptProperty(KEY_IRC_AUTH);\n }\n\n LoadConfigReport report = loadConfigs(!isPreset);\n\n if (report.isErrorFree() && !isPreset)\n {\n rememberLastConfigFile(filename);\n }\n\n return report;\n }\n\n /**\n * Store the specified path to a configuration file in the last config file location conf file\n * \n * @param path\n * The path of the configuration file to remember\n */\n public void rememberLastConfigFile(String path)\n {\n logger.trace(\"Remembering last loaded file \" + path);\n\n // Keep track of the last saved or loaded copy to compare with to see if a save prompt is required when exiting\n this.lastSavedCopy = getCopy();\n\n BufferedWriter writer = null;\n try\n {\n writer = new BufferedWriter(new FileWriter(CONFIG_FILE_LAST_LOCATION, false));\n writer.write(path);\n }\n catch (Exception e)\n {\n // Don't alert the user, just log behind the scenes, not important enough to warrant a popup\n logger.error(\"Unable to save last file loaded\", e);\n }\n finally\n {\n if (writer != null)\n {\n try\n {\n writer.close();\n }\n catch (Exception e)\n {\n logger.error(e.toString(), e);\n }\n }\n }\n }\n\n /**\n * Delete the last config file location conf file that stored the path to a configuration file. To be used to remove\n * a file that is not found or has errors.\n */\n public void forgetLastConfigFile()\n {\n logger.trace(\"Forgetting last loaded\");\n\n File f = new File(CONFIG_FILE_LAST_LOCATION);\n f.delete();\n }\n\n /**\n * Save the configuration to the specified file\n * \n * @param file\n * @throws Exception\n */\n public void saveFile(File file) throws Exception\n {\n OutputStream os = new FileOutputStream(file);\n encryptProperty(KEY_IRC_AUTH);\n super.store(os, null);\n decryptProperty(KEY_IRC_AUTH);\n rememberLastConfigFile(file.getAbsolutePath());\n }\n\n public void encryptProperty(String key)\n {\n BasicTextEncryptor textEncryptor = new BasicTextEncryptor();\n textEncryptor.setPassword(ENC_PASSWORD);\n\n final String decryptedValue = getProperty(key);\n if (decryptedValue != null && !decryptedValue.isEmpty())\n {\n try\n {\n final String encryptedValue = textEncryptor.encrypt(decryptedValue);\n setProperty(key, encryptedValue);\n }\n catch (Exception e)\n {\n final String errorMessage = \"Error encrypting value for \" + key + \" property\";\n logger.error(errorMessage, e);\n ChatWindow.popup.handleProblem(errorMessage);\n setProperty(key, \"\");\n }\n }\n }\n\n public void decryptProperty(String key)\n {\n BasicTextEncryptor textEncryptor = new BasicTextEncryptor();\n textEncryptor.setPassword(ENC_PASSWORD);\n final String encryptedValue = getProperty(key);\n if (encryptedValue != null && !encryptedValue.isEmpty())\n {\n try\n {\n final String decryptedValue = textEncryptor.decrypt(encryptedValue);\n setProperty(key, decryptedValue);\n }\n catch (Exception e)\n {\n final String errorMessage = \"Error decrypting value for \" + key + \" property\";\n logger.error(errorMessage, e);\n ChatWindow.popup.handleProblem(errorMessage);\n setProperty(key, \"\");\n }\n }\n }\n\n /**\n * Try to load the configuration file stored i the last config file location conf file.\n * \n * @return report\n * @throws Exception\n */\n public LoadConfigReport loadLast() throws Exception\n {\n logger.trace(\"Load last\");\n\n final String previousConfigNotFound = \"Previous configuration not found.\";\n final String previousConfigError = \"Error loading previous configuration.\";\n\n BufferedReader reader = null;\n try\n {\n File lastFile = new File(CONFIG_FILE_LAST_LOCATION);\n if (!lastFile.exists())\n {\n LoadConfigReport errorReport = new LoadConfigReport();\n errorReport.addError(previousConfigNotFound, LoadConfigErrorType.FILE_NOT_FOUND);\n return errorReport;\n }\n reader = new BufferedReader(new FileReader(lastFile));\n final String lastConfigFilename = reader.readLine();\n reader.close();\n LoadConfigReport report = loadFile(lastConfigFilename);\n if (report.isProblem())\n {\n report.setMainMessage(previousConfigError);\n }\n return report;\n }\n finally\n {\n if (reader != null)\n {\n try\n {\n reader.close();\n }\n catch (Exception e)\n {\n logger.error(e.toString(), e);\n }\n }\n }\n }\n\n /**\n * Set a value only if it isn't already set, optionally overriding if specified\n * \n * @param key\n * @param value\n * @param override\n */\n private void setPropertyOverride(final String key, final String value, final boolean override)\n {\n final boolean valueExists = getProperty(key) != null && !getProperty(key).isEmpty();\n if (override || !valueExists)\n {\n setProperty(key, value);\n }\n }\n\n /**\n * Load a default configuration, for if something goes wrong, or if no previously used configuration file is stored\n * \n * @param override\n * Whether to override values should they already exist\n */\n public void loadDefaultValues(boolean override)\n {\n logger.trace(\"Loading default values\");\n\n final String trueString = Boolean.toString(true);\n final String falseString = Boolean.toString(false);\n\n setPropertyOverride(KEY_IRC_HOST, \"irc.twitch.tv\", override);\n setPropertyOverride(KEY_IRC_PORT, Integer.toString(6667), override);\n setPropertyOverride(KEY_IRC_ANON, trueString, override);\n setPropertyOverride(KEY_IRC_AUTO_RECONNECT, trueString, override);\n\n setPropertyOverride(KEY_FONT_FILE_BORDER, ConfigFont.INTERNAL_FILE_PREFIX + \"borders/dw3_border.png\", override);\n setPropertyOverride(KEY_FONT_FILE_FONT, ConfigFont.INTERNAL_FILE_PREFIX + \"fonts/dw3_font.png\", override);\n setPropertyOverride(KEY_FONT_TYPE, FontType.FIXED_WIDTH.name(), override);\n setPropertyOverride(KEY_FONT_GRID_WIDTH, Integer.toString(8), override);\n setPropertyOverride(KEY_FONT_GRID_HEIGHT, Integer.toString(12), override);\n setPropertyOverride(KEY_FONT_SCALE, Integer.toString(2), override);\n setPropertyOverride(KEY_FONT_BORDER_SCALE, Integer.toString(3), override);\n setPropertyOverride(KEY_FONT_BORDER_INSET_X, Integer.toString(1), override);\n setPropertyOverride(KEY_FONT_BORDER_INSET_Y, Integer.toString(1), override);\n setPropertyOverride(KEY_FONT_SPACE_WIDTH, Integer.toString(25), override);\n setPropertyOverride(KEY_FONT_BASELINE_OFFSET, Integer.toString(0), override);\n setPropertyOverride(KEY_FONT_CHARACTERS, SpriteFont.NORMAL_ASCII_KEY, override);\n setPropertyOverride(KEY_FONT_UNKNOWN_CHAR, Character.toString((char) 127), override);\n setPropertyOverride(KEY_FONT_EXTENDED_CHAR, trueString, override);\n setPropertyOverride(KEY_FONT_SPACING_LINE, Integer.toString(2), override);\n setPropertyOverride(KEY_FONT_SPACING_CHAR, Integer.toString(0), override);\n setPropertyOverride(KEY_FONT_SPACING_MESSAGE, Integer.toString(0), override);\n\n setPropertyOverride(KEY_CHAT_SCROLL, falseString, override);\n setPropertyOverride(KEY_CHAT_RESIZABLE, trueString, override);\n setPropertyOverride(KEY_CHAT_POSITION, falseString, override);\n setPropertyOverride(KEY_CHAT_POSITION_X, Integer.toString(0), override);\n setPropertyOverride(KEY_CHAT_POSITION_Y, Integer.toString(0), override);\n setPropertyOverride(KEY_CHAT_FROM_BOTTOM, falseString, override);\n setPropertyOverride(KEY_CHAT_WIDTH, Integer.toString(550), override);\n setPropertyOverride(KEY_CHAT_HEIGHT, Integer.toString(450), override);\n setPropertyOverride(KEY_CHAT_CHROMA_ENABLED, falseString, override);\n setPropertyOverride(KEY_CHAT_INVERT_CHROMA, falseString, override);\n setPropertyOverride(KEY_CHAT_REVERSE_SCROLLING, falseString, override);\n setPropertyOverride(KEY_CHAT_CHROMA_LEFT, Integer.toString(10), override);\n setPropertyOverride(KEY_CHAT_CHROMA_TOP, Integer.toString(10), override);\n setPropertyOverride(KEY_CHAT_CHROMA_RIGHT, Integer.toString(10), override);\n setPropertyOverride(KEY_CHAT_CHROMA_BOTTOM, Integer.toString(10), override);\n setPropertyOverride(KEY_CHAT_CHROMA_CORNER, Integer.toString(10), override);\n setPropertyOverride(KEY_CHAT_ALWAYS_ON_TOP, falseString, override);\n setPropertyOverride(KEY_CHAT_ANTIALIAS, falseString, override);\n\n setPropertyOverride(KEY_COLOR_BG, \"000000\", override);\n setPropertyOverride(KEY_COLOR_FG, \"FFFFFF\", override);\n setPropertyOverride(KEY_COLOR_BORDER, \"FFFFFF\", override);\n setPropertyOverride(KEY_COLOR_HIGHLIGHT, \"6699FF\", override);\n setPropertyOverride(KEY_COLOR_PALETTE, \"F7977A,FDC68A,FFF79A,A2D39C,6ECFF6,A187BE,F6989D\", override);\n setPropertyOverride(KEY_COLOR_CHROMA_KEY, \"00FF00\", override);\n setPropertyOverride(KEY_COLOR_USERNAME, trueString, override);\n setPropertyOverride(KEY_COLOR_TIMESTAMP, falseString, override);\n setPropertyOverride(KEY_COLOR_MESSAGE, falseString, override);\n setPropertyOverride(KEY_COLOR_JOIN, falseString, override);\n setPropertyOverride(KEY_COLOR_TWITCH, falseString, override);\n\n setPropertyOverride(KEY_MESSAGE_JOIN, falseString, override);\n setPropertyOverride(KEY_MESSAGE_USERNAME, trueString, override);\n setPropertyOverride(KEY_MESSAGE_TIMESTAMP, falseString, override);\n setPropertyOverride(KEY_MESSAGE_USERFORMAT, ConfigMessage.USERNAME_REPLACE, override);\n setPropertyOverride(KEY_MESSAGE_TIMEFORMAT, \"[HH:mm:ss]\", override);\n setPropertyOverride(KEY_MESSAGE_CONTENT_BREAK, ConfigMessage.DEFAULT_CONTENT_BREAKER, override);\n setPropertyOverride(KEY_MESSAGE_QUEUE_SIZE, Integer.toString(64), override);\n setPropertyOverride(KEY_MESSAGE_SPEED, Integer.toString((int) (ConfigMessage.MAX_MESSAGE_SPEED * 0.25f)), override);\n setPropertyOverride(KEY_MESSAGE_EXPIRATION_TIME, Integer.toString(0), override);\n setPropertyOverride(KEY_MESSAGE_HIDE_EMPTY_BORDER, falseString, override);\n setPropertyOverride(KEY_MESSAGE_HIDE_EMPTY_BACKGROUND, falseString, override);\n setPropertyOverride(KEY_MESSAGE_CASE_TYPE, UsernameCaseResolutionType.NONE.name(), override);\n setPropertyOverride(KEY_MESSAGE_CASE_SPECIFY, falseString, override);\n setPropertyOverride(KEY_MESSAGE_CASING, MessageCasing.MIXED_CASE.name(), override);\n\n setPropertyOverride(KEY_EMOJI_ENABLED, trueString, override);\n setPropertyOverride(KEY_EMOJI_ANIMATION, falseString, override);\n setPropertyOverride(KEY_EMOJI_TWITCH_BADGES, trueString, override);\n setPropertyOverride(KEY_EMOJI_FFZ_BADGES, falseString, override);\n setPropertyOverride(KEY_EMOJI_SCALE_TO_LINE, trueString, override);\n setPropertyOverride(KEY_EMOJI_BADGE_SCALE_TO_LINE, falseString, override);\n setPropertyOverride(KEY_EMOJI_BADGE_HEIGHT_OFFSET, Integer.toString(0), override);\n setPropertyOverride(KEY_EMOJI_SCALE, Integer.toString(100), override);\n setPropertyOverride(KEY_EMOJI_BADGE_SCALE, Integer.toString(100), override);\n setPropertyOverride(KEY_EMOJI_DISPLAY_STRAT, EmojiLoadingDisplayStragegy.SPACE.name(), override);\n setPropertyOverride(KEY_EMOJI_TWITCH_ENABLE, trueString, override);\n setPropertyOverride(KEY_EMOJI_TWITCH_CACHE, falseString, override);\n setPropertyOverride(KEY_EMOJI_FFZ_ENABLE, falseString, override);\n setPropertyOverride(KEY_EMOJI_FFZ_CACHE, falseString, override);\n setPropertyOverride(KEY_EMOJI_BTTV_ENABLE, falseString, override);\n setPropertyOverride(KEY_EMOJI_BTTV_CACHE, falseString, override);\n setPropertyOverride(KEY_EMOJI_TWITTER_ENABLE, trueString, override);\n\n setPropertyOverride(KEY_CENSOR_ENABLED, trueString, override);\n setPropertyOverride(KEY_CENSOR_PURGE_ON_TWITCH_BAN, trueString, override);\n setPropertyOverride(KEY_CENSOR_URL, falseString, override);\n setPropertyOverride(KEY_CENSOR_FIRST_URL, falseString, override);\n setPropertyOverride(KEY_CENSOR_UNKNOWN_CHARS, falseString, override);\n setPropertyOverride(KEY_CENSOR_UNKNOWN_CHARS_PERCENT, Integer.toString(20), override);\n setPropertyOverride(KEY_CENSOR_WHITE, \"\", override);\n setPropertyOverride(KEY_CENSOR_BLACK, \"\", override);\n setPropertyOverride(KEY_CENSOR_BANNED, \"\", override);\n\n loadConfigs(true);\n }\n\n private FontificatorProperties getCopy()\n {\n FontificatorProperties copy = new FontificatorProperties();\n for (String key : stringPropertyNames())\n {\n copy.setProperty(key, getProperty(key));\n }\n return copy;\n }\n\n /**\n * Load properties into specialized config objects. This method returns its own report.\n * \n * @return success\n */\n private LoadConfigReport loadConfigs(boolean loadNonFontConfig)\n {\n LoadConfigReport report = new LoadConfigReport();\n if (loadNonFontConfig)\n {\n ircConfig.load(this, report);\n chatConfig.load(this, report);\n messageConfig.load(this, report);\n emojiConfig.load(this, report);\n censorConfig.load(this, report);\n }\n fontConfig.load(this, report);\n colorConfig.load(this, report);\n\n if (!report.isErrorFree())\n {\n if (report.isOnlyMissingKeys())\n {\n report.setMainMessage(\"<center>Please resave the configuration file<br />to fix these issues:</center>\");\n }\n ChatWindow.popup.handleProblem(report);\n }\n\n return report;\n }\n\n private boolean hasUnsavedChanges()\n {\n return !equals(lastSavedCopy);\n }\n\n @Override\n public int hashCode()\n {\n final int prime = 31;\n int result = super.hashCode();\n result = prime * result + ((chatConfig == null) ? 0 : chatConfig.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj)\n {\n if (this == obj)\n return true;\n if (!super.equals(obj))\n return false;\n if (getClass() != obj.getClass())\n return false;\n\n FontificatorProperties otherFp = (FontificatorProperties) obj;\n\n return FontificatorProperties.propertyBatchMatch(getKeysForEqualsTest(this), this, otherFp);\n }\n\n private static boolean propertyBatchMatch(String[][] keys, FontificatorProperties a, FontificatorProperties b)\n {\n for (int i = 0; i < keys.length; i++)\n {\n for (int j = 0; j < keys[i].length; j++)\n {\n if (!propertyEquals(a.getProperty(keys[i][j]), b.getProperty(keys[i][j])))\n {\n return false;\n }\n }\n }\n return true;\n }\n\n private static boolean propertyEquals(String one, String two)\n {\n if (one == null)\n {\n return two == null;\n }\n else\n {\n return one.equals(two);\n }\n }\n\n}", "public class LoadConfigReport\n{\n private static final int MAX_NUMBER_OF_NON_PROBLEMS = 15;\n\n private String mainMessage;\n\n /**\n * A set of types of errors that have been collected in this report\n */\n private Set<LoadConfigErrorType> types;\n\n /**\n * Human-readable messages describing the errors collected so far\n */\n private List<String> messages;\n\n /**\n * Instantiates an empty report\n */\n public LoadConfigReport()\n {\n types = new HashSet<LoadConfigErrorType>();\n messages = new ArrayList<String>();\n }\n\n /**\n * Instantiate this report with only a type, when there is no need for human-readable explanations\n * \n * @param type\n */\n public LoadConfigReport(LoadConfigErrorType type)\n {\n this();\n types.add(type);\n }\n\n /**\n * Add an error to this report\n * \n * @param message\n * @param type\n */\n public void addError(String message, LoadConfigErrorType type)\n {\n messages.add(message);\n types.add(type);\n }\n\n /**\n * Whether no errors have been reported, whether they are problems or not. This check identifies the load as being capable of handling any subsequent work, no need to supplement the results with defaults.\n * \n * @return error free\n */\n public boolean isErrorFree()\n {\n return messages.isEmpty();\n }\n\n /**\n * Get the opposite of whether there is a problem\n * \n * @return success\n */\n public boolean isSuccess()\n {\n return !isProblem();\n }\n\n /**\n * Get whether there is a problem. A problem is whenever at least one of the types of errors is marked as a problem-type error.\n * \n * @return problem\n */\n public boolean isProblem()\n {\n for (LoadConfigErrorType result : types)\n {\n if (result.isProblem())\n {\n return true;\n }\n }\n // No real problems exist, but if there are more than the max number allowed, consider it a problem. For\n // example, someone might be loading a random text file as a config file that has nothing to do with this\n // program. That should be a problem, even though it will register as merely having a bunch of missing values\n return messages.size() > MAX_NUMBER_OF_NON_PROBLEMS;\n }\n\n /**\n * Get whether all the load problems are just missing keys\n * \n * @return whether all errors are missing keys\n */\n public boolean isOnlyMissingKeys()\n {\n for (LoadConfigErrorType result : types)\n {\n if (result != LoadConfigErrorType.MISSING_KEY)\n {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Get the messages\n * \n * @return messages\n */\n public List<String> getMessages()\n {\n return messages;\n }\n\n /**\n * Get the types\n * \n * @return types\n */\n public Set<LoadConfigErrorType> getTypes()\n {\n return types;\n }\n\n /**\n * Adds all the contents of the specified other report to this report\n * \n * @param otherReport\n */\n public void addFromReport(LoadConfigReport otherReport)\n {\n for (String msg : otherReport.getMessages())\n {\n messages.add(msg);\n }\n for (LoadConfigErrorType rslt : otherReport.getTypes())\n {\n types.add(rslt);\n }\n }\n\n public String getMainMessage()\n {\n return mainMessage;\n }\n\n public void setMainMessage(String mainMessage)\n {\n this.mainMessage = mainMessage;\n }\n}", "public class ChatWindow extends JFrame\n{\n private static final long serialVersionUID = 1L;\n\n /**\n * A stored reference to the chat panel, used whenever some part of the system has a reference to this ChatWindow,\n * but needs to modify something on the panel. This is in lieu of putting a bunch of accessor methods here to do\n * pass through the function to the panel in an encapsulated way.\n */\n private ChatPanel chatPanel;\n\n /**\n * A static copy of this ChatWindow for accessing it globally\n */\n public static ChatWindow me;\n\n /**\n * The popup for submitting errors that the user needs to see\n */\n public static FontificatorError popup;\n\n /**\n * Mouse listeners for dragging the Chat Window around when dragging the mouse inside the chat\n */\n private ChatMouseListeners mouseListeners;\n\n /**\n * Escape stroke to close popups\n */\n private static final KeyStroke escapeStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);\n\n /**\n * Construct the Chat Window\n */\n public ChatWindow()\n {\n me = this;\n setTitle(\"Fontificator Chat\");\n popup = new FontificatorError(null);\n }\n\n /**\n * Sets the properties to get hooks into the properties' configuration models; Sets the ControlWindow to get hooks\n * back into the controls; Sets the loaded member Boolean to indicate it has everything it needs to begin rendering\n * the visualization\n * \n * @param fProps\n * @param ctrlWindow\n * @throws IOException\n */\n public void initChat(final FontificatorProperties fProps, final ControlWindow ctrlWindow) throws IOException\n {\n chatPanel = new ChatPanel();\n add(chatPanel);\n\n mouseListeners = new ChatMouseListeners(this, ctrlWindow);\n addMouseListener(mouseListeners);\n addMouseMotionListener(mouseListeners);\n addMouseWheelListener(chatPanel);\n setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);\n\n setChatSize(fProps.getChatConfig());\n\n setResizable(fProps.getChatConfig().isResizable());\n setAlwaysOnTop(fProps.getChatConfig().isAlwaysOnTop());\n\n chatPanel.setConfig(fProps);\n chatPanel.initExpirationTimer();\n\n addWindowListener(new WindowListener()\n {\n @Override\n public void windowOpened(WindowEvent e)\n {\n }\n\n @Override\n public void windowClosing(WindowEvent e)\n {\n callExit(e.getComponent());\n }\n\n @Override\n public void windowClosed(WindowEvent e)\n {\n }\n\n @Override\n public void windowIconified(WindowEvent e)\n {\n }\n\n @Override\n public void windowDeiconified(WindowEvent e)\n {\n }\n\n @Override\n public void windowActivated(WindowEvent e)\n {\n }\n\n @Override\n public void windowDeactivated(WindowEvent e)\n {\n }\n\n /**\n * Calls exit from the control window\n */\n private void callExit(Component caller)\n {\n ctrlWindow.attemptToExit(caller);\n }\n });\n\n }\n\n /**\n * Handles sizing the Chat Window, clearing out old JFrame-based config values in the ConfigChat model if they were\n * the only ones available\n * \n * @param chatConfig\n */\n public void setChatSize(ConfigChat chatConfig)\n {\n if (chatConfig.getWindowWidth() != null && chatConfig.getWindowHeight() != null)\n {\n setSize(chatConfig.getWindowWidth(), chatConfig.getWindowHeight());\n chatConfig.setWidth(getContentPane().getWidth());\n chatConfig.setHeight(getContentPane().getHeight());\n chatConfig.clearLegacyWindowSize();\n }\n else if (chatConfig.getWidth() > 0 && chatConfig.getHeight() > 0)\n {\n getContentPane().setPreferredSize(new Dimension(chatConfig.getWidth(), chatConfig.getHeight()));\n getContentPane().setSize(chatConfig.getWidth(), chatConfig.getHeight());\n pack();\n }\n }\n\n /**\n * Does the work required to make the parameter JDialog be hidden when pressing escape\n * \n * @param popup\n */\n public static void setupHideOnEscape(final JDialog popup)\n {\n Action aa = new AbstractAction()\n {\n private static final long serialVersionUID = 1L;\n\n public void actionPerformed(ActionEvent event)\n {\n popup.setVisible(false);\n }\n };\n final String mapKey = \"escapePressed\";\n JRootPane root = popup.getRootPane();\n root.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escapeStroke, mapKey);\n root.getActionMap().put(mapKey, aa);\n }\n\n /**\n * Access to the chat panel through this window, for any places there is a reference to just the ChatWindow, but\n * that needs to affect the ChatPanel, which has all the actual chat options\n * \n * @return chatPanel\n */\n public ChatPanel getChatPanel()\n {\n return chatPanel;\n }\n\n /**\n * This is a small hack to expose the ctrl window to the message control panel so its username case map can be\n * cleared out if the user changes the type of username case resolution\n */\n public void clearUsernameCases()\n {\n mouseListeners.clearUsernameCases();\n }\n\n}", "public class ColorButton extends JPanel\n{\n private static final long serialVersionUID = 1L;\n\n /**\n * The text label for identifying the color button component\n */\n private JLabel label;\n\n /**\n * The button that displays the color\n */\n private JButton button;\n\n /**\n * A reference to the control panel this button sits on, so its update method to use the newly selected colors can\n * be called\n */\n private final ControlPanelBase control;\n\n public ColorButton(final String label, Color value, final String explanation, ControlPanelBase controlPanel)\n {\n super();\n this.control = controlPanel;\n this.button = new JButton();\n this.button.setToolTipText(\"\");\n this.label = new JLabel(label);\n setColor(value == null ? Color.BLACK : value);\n button.setBackground(value);\n\n // So the button color shows up on Mac OS\n button.setOpaque(true);\n\n add(this.label);\n add(this.button);\n\n this.button.addActionListener(new ActionListener()\n {\n public void actionPerformed(ActionEvent e)\n {\n Color color = JColorChooser.showDialog(ControlWindow.me, \"Select Color\" + (label == null ? \"\" : \" for \" + label), getColor());\n if (color != null)\n {\n setColor(color);\n control.update();\n }\n }\n });\n }\n\n /**\n * Get the selected color\n * \n * @return color\n */\n public Color getColor()\n {\n return button.getBackground();\n }\n\n /**\n * Set the selected color\n * \n * @param value\n */\n public void setColor(Color value)\n {\n button.setBackground(value);\n }\n\n /**\n * Get the label text\n * \n * @return labelText\n */\n public String getLabel()\n {\n return label.getText();\n }\n\n}", "public class Palette extends JPanel\n{\n private static final long serialVersionUID = 1L;\n\n private JLabel label;\n\n private JButton buttonAdd;\n\n private JButton buttonRem;\n\n private SwatchPanel swatchPanel;\n\n private JScrollPane paletteScrollPane;\n\n private final ControlPanelBase control;\n\n public Palette(Color bgColor, ControlPanelBase controlPanel)\n {\n this(null, bgColor, controlPanel);\n }\n\n public Palette(final String label, Color bgColor, ControlPanelBase controlPanel)\n {\n super(new GridBagLayout());\n\n this.control = controlPanel;\n\n GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0);\n\n this.buttonAdd = new JButton(\"+\");\n this.buttonRem = new JButton(\"-\");\n if (label != null)\n {\n this.label = new JLabel(label);\n }\n this.swatchPanel = new SwatchPanel(bgColor);\n\n gbc.weightx = 0.0;\n\n if (label != null)\n {\n gbc.gridheight = 2;\n add(this.label, gbc);\n gbc.gridx++;\n }\n gbc.gridheight = 1;\n add(this.buttonAdd, gbc);\n gbc.gridy++;\n add(this.buttonRem, gbc);\n gbc.gridy = 0;\n gbc.gridx++;\n gbc.gridheight = 2;\n\n paletteScrollPane = new JScrollPane(this.swatchPanel, JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);\n paletteScrollPane.setPreferredSize(new Dimension(512, getHeight()));\n\n gbc.weightx = 0.0;\n gbc.fill = GridBagConstraints.VERTICAL;\n gbc.anchor = GridBagConstraints.EAST;\n add(paletteScrollPane, gbc);\n gbc.gridx++;\n\n ActionListener al = new ActionListener()\n {\n public void actionPerformed(ActionEvent e)\n {\n JButton source = (JButton) e.getSource();\n\n if (source == buttonAdd)\n {\n Color c = JColorChooser.showDialog(ControlWindow.me, \"Add Color to Palette\" + (label == null ? \"\" : \" for \" + label), swatchPanel.isEmpty() ? null : swatchPanel.getColors().get(swatchPanel.getCount() - 1));\n if (c != null)\n {\n addColor(c);\n control.update();\n validate();\n repaint();\n }\n }\n else if (source == buttonRem)\n {\n swatchPanel.removeSelectedColors();\n control.update();\n validate();\n repaint();\n }\n\n }\n };\n\n this.buttonAdd.addActionListener(al);\n this.buttonRem.addActionListener(al);\n\n }\n\n public List<Color> getColors()\n {\n return swatchPanel.getColors();\n }\n\n public String getLabel()\n {\n return label.getText();\n }\n\n public void setBgColor(Color bgColor)\n {\n swatchPanel.setBackground(bgColor);\n }\n\n public void addColor(Color col)\n {\n swatchPanel.addColor(col);\n }\n\n public void reset()\n {\n swatchPanel.clear();\n }\n\n public void refreshComponents()\n {\n swatchPanel.validate();\n swatchPanel.repaint();\n }\n\n}" ]
import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JCheckBox; import javax.swing.JPanel; import javax.swing.border.TitledBorder; import com.glitchcog.fontificator.config.ConfigColor; import com.glitchcog.fontificator.config.FontificatorProperties; import com.glitchcog.fontificator.config.loadreport.LoadConfigReport; import com.glitchcog.fontificator.gui.chat.ChatWindow; import com.glitchcog.fontificator.gui.component.ColorButton; import com.glitchcog.fontificator.gui.component.palette.Palette;
package com.glitchcog.fontificator.gui.controls.panel; /** * Control Panel containing all the color options * * @author Matt Yanos */ public class ControlPanelColor extends ControlPanelBase { private static final long serialVersionUID = 1L; /** * Background color button */
private ColorButton bgColorButton;
4
mit-dig/punya
appinventor/components/src/com/google/appinventor/components/runtime/FusiontablesControl.java
[ "public enum PropertyCategory {\n // TODO(user): i18n category names\n BEHAVIOR(\"Behavior\"),\n APPEARANCE(\"Appearance\"),\n LINKED_DATA(\"Linked Data\"),\n DEPRECATED(\"Deprecated\"),\n UNSET(\"Unspecified\");\n\n private String name;\n\n PropertyCategory(String categoryName) {\n name = categoryName;\n }\n\n public String getName() {\n return name;\n }\n}", "public enum ComponentCategory{\n // TODO(user): i18n category names\n USERINTERFACE(\"User Interface\"),\n LAYOUT(\"Layout\"),\n MEDIA(\"Media\"),\n ANIMATION(\"Drawing and Animation\"),\n SENSORS(\"Sensors\"),\n SOCIAL(\"Social\"),\n STORAGE(\"Storage\"),\n CONNECTIVITY(\"Connectivity\"),\n MAPVIZ(\"Map & Visualization\"),\n CLOUDSTORAGE(\"Cloud Storage\"),\n LINKEDDATA(\"Linked Data\"),\n LEGOMINDSTORMS(\"LEGO\\u00AE MINDSTORMS\\u00AE\"),\n EXPERIMENTAL(\"Experimental\"),\n //OBSOLETE(\"Old stuff\"),// removed to remove old stuff from the menu\n INTERNAL(\"For internal use only\"),\n // UNINITIALIZED is used as a default value so Swing libraries can still compile\n UNINITIALIZED(\"Uninitialized\");\n\n // Mapping of component categories to names consisting only of lower-case letters,\n // suitable for appearing in URLs.\n private static final Map<String, String> DOC_MAP =\n new HashMap<String, String>();\n static {\n DOC_MAP.put(\"User Interface\", \"userinterface\");\n DOC_MAP.put(\"Layout\", \"layout\");\n DOC_MAP.put(\"Media\", \"media\");\n DOC_MAP.put(\"Drawing and Animation\", \"animation\");\n DOC_MAP.put(\"Sensors\", \"sensors\");\n DOC_MAP.put(\"Social\", \"social\");\n DOC_MAP.put(\"Storage\", \"storage\");\n DOC_MAP.put(\"Connectivity\", \"connectivity\");\n DOC_MAP.put(\"LEGO\\u00AE MINDSTORMS\\u00AE\", \"legomindstorms\");\n DOC_MAP.put(\"Semantic Web\", \"semanticweb\");\n DOC_MAP.put(\"Experimental\", \"experimental\");\n }\n\n private String name;\n\n ComponentCategory(String categoryName) {\n name = categoryName;\n }\n\n /**\n * Returns the display name of this category, as used on the Designer palette, such\n * as \"Not ready for prime time\". To get the enum name (such as \"EXPERIMENTAL\"),\n * use {@link #toString}.\n *\n * @return the display name of this category\n */\n public String getName() {\n return name;\n }\n\n /**\n * Returns a version of the name of this category consisting of only lower-case\n * letters, meant for use in a URL. For example, for the category with the enum\n * name \"EXPERIMENTAL\" and display name \"Not ready for prime time\", this returns\n * \"experimental\".\n *\n * @return a name for this category consisting of only lower-case letters\n */\n public String getDocName() {\n return DOC_MAP.get(name);\n }\n}", "public class PropertyTypeConstants {\n private PropertyTypeConstants() {}\n\n /**\n * User-uploaded assets.\n * @see\n * com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidAssetSelectorPropertyEditor\n */\n public static final String PROPERTY_TYPE_ASSET = \"asset\";\n\n /**\n * Instances of {@link com.google.appinventor.components.runtime.BluetoothClient}\n * in the current project.\n */\n public static final String PROPERTY_TYPE_BLUETOOTHCLIENT = \"BluetoothClient\";\n\n /**\n * Boolean values.\n * @see\n * com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidBooleanPropertyEditor\n */\n public static final String PROPERTY_TYPE_BOOLEAN = \"boolean\";\n\n /**\n * Arrangement alignment.\n * @see\n * com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidHorizontalAlignmentChoicePropertyEditor\n */\n public static final String PROPERTY_TYPE_HORIZONTAL_ALIGNMENT = \"horizontal_alignment\";\n public static final String PROPERTY_TYPE_VERTICAL_ALIGNMENT = \"vertical_alignment\";\n\n /**\n * Accelerometer sensitivity.\n * @see\n * com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidAccelerometerSensitvityChoicePropertyEditor\n */\n public static final String PROPERTY_TYPE_ACCELEROMETER_SENSITIVITY = \"accelerometer_sensitivity\";\n\n /**\n * Button shapes.\n * @see\n * com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidButtonShapeChoicePropertyEditor\n */\n public static final String PROPERTY_TYPE_BUTTON_SHAPE = \"button_shape\";\n\n /**\n * Any of the colors specified in {@link\n * com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidColorChoicePropertyEditor}.\n */\n public static final String PROPERTY_TYPE_COLOR = \"color\";\n\n /**\n * Component instances in the current project.\n * @see\n * com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidComponentSelectorPropertyEditor\n */\n public static final String PROPERTY_TYPE_COMPONENT = \"component\";\n\n /**\n * Concept URI field for Semantic Web components.\n * @see com.google.appinventor.client.widgets.properties.SemanticWebPropertyEditor\n */\n public static final String PROPERTY_TYPE_CONCEPT_URI = \"concept_uri\";\n\n /**\n * Floating-point values.\n * @see com.google.appinventor.client.widgets.properties.FloatPropertyEditor\n */\n public static final String PROPERTY_TYPE_FLOAT = \"float\";\n\n /**\n * Integer values.\n * @see com.google.appinventor.client.widgets.properties.IntegerPropertyEditor\n */\n public static final String PROPERTY_TYPE_INTEGER = \"integer\";\n\n /**\n * Lego NXT sensor ports.\n * @see\n * com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidLegoNxtSensorPortChoicePropertyEditor\n */\n public static final String PROPERTY_TYPE_LEGO_NXT_SENSOR_PORT = \"lego_nxt_sensor_port\";\n\n /**\n * Colors recognizable by Lego NXT sensors.\n * @see\n * com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidColorChoicePropertyEditor#NXT_GENERATED_COLORS\n */\n public static final String PROPERTY_TYPE_LEGO_NXT_GENERATED_COLOR = \"lego_nxt_generated_color\";\n\n /**\n * Non-negative (positive or zero) floating-point values.\n * @see com.google.appinventor.client.widgets.properties.NonNegativeFloatPropertyEditor\n */\n public static final String PROPERTY_TYPE_NON_NEGATIVE_FLOAT = \"non_negative_float\";\n\n /**\n * Non-negative (positive or zero) integers.\n * @see com.google.appinventor.client.widgets.properties.NonNegativeIntegerPropertyEditor\n */\n public static final String PROPERTY_TYPE_NON_NEGATIVE_INTEGER = \"non_negative_integer\";\n\n /**\n * Property URI field for Semantic Web components.\n * @see com.google.appinventor.client.widgets.properties.SemanticWebPropertyEditor\n */\n public static final String PROPERTY_TYPE_PROPERTY_URI = \"property_uri\";\n\n /**\n * Choices of screen orientations offered by {@link\n * com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidScreenOrientationChoicePropertyEditor}.\n */\n public static final String PROPERTY_TYPE_SCREEN_ORIENTATION = \"screen_orientation\";\n\n /**\n * Choices of screen animations offered by {@link\n * com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidScreenAnimationChoicePropertyEditor}.\n */\n public static final String PROPERTY_TYPE_SCREEN_ANIMATION = \"screen_animation\";\n\n /**\n * Minimum distance interval, in meters, that the location sensor will try to use\n * for sending out location updates. See {@link com.google.appinventor.components.runtime.LocationSensor}.\n */\n public static final String PROPERTY_TYPE_SENSOR_DIST_INTERVAL = \"sensor_dist_interval\";\n\n /**\n * Minimum time interval, in milliseconds, that the location sensor use to send out\n * location updates. See {@link com.google.appinventor.components.runtime.LocationSensor}.\n */\n public static final String PROPERTY_TYPE_SENSOR_TIME_INTERVAL = \"sensor_time_interval\";\n\n /**\n * Strings. This has the same effect as, but is preferred in component\n * definitions to, {@link #PROPERTY_TYPE_TEXT}).\n * @see com.google.appinventor.client.widgets.properties.StringPropertyEditor\n */\n public static final String PROPERTY_TYPE_STRING = \"string\";\n\n /**\n * Text. This has the same effect as {@link #PROPERTY_TYPE_STRING}, which\n * is preferred everywhere except as the default value for {@link\n * com.google.appinventor.components.annotations.DesignerProperty#editorType}.\n * @see com.google.appinventor.client.widgets.properties.TextPropertyEditor\n * @see com.google.appinventor.client.widgets.properties.TextAreaPropertyEditor\n */\n public static final String PROPERTY_TYPE_TEXT = \"text\";\n\n public static final String PROPERTY_TYPE_TEXTAREA = \"textArea\";\n\n /**\n * Choices of text alignment (left, center, right) offered by {@link\n * com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidAlignmentChoicePropertyEditor}.\n */\n public static final String PROPERTY_TYPE_TEXTALIGNMENT = \"textalignment\";\n\n /**\n * Choices of toast display length (short, long) offered by {@link\n * com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidToastLengthChoicePropertyEditor}.\n */\n public static final String PROPERTY_TYPE_TOAST_LENGTH = \"toast_length\";\n\n /**\n * Choices of typefaces offered by {@link\n * com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidFontTypefaceChoicePropertyEditor}.\n */\n public static final String PROPERTY_TYPE_TYPEFACE = \"typeface\";\n\n /**\n * Choices of visibility for view components offered by {@link\n * com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidVisibilityChoicePropertyEditor}.\n */\n public static final String PROPERTY_TYPE_VISIBILITY = \"visibility\";\n\n /**\n * Choices of Text Receiving options. {@link\n * com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidTextReceivingPropertyEditor}.\n */\n public static final String PROPERTY_TYPE_TEXT_RECEIVING = \"text_receiving\";\n \n /**\n * Choices of Survey Style options. {@link\n * com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidSurveyStylePropertyEditor}.\n\n */\n public static final String PROPERTY_TYPE_SURVEY_STYLE = \"survey_style\";\n \n \n\n /**\n * Uri for semantic web resources.\n */\n public static final String PROPERTY_TYPE_URI = \"uri\";\n\n /**\n * Base URI for creating semantic web resources.\n */\n public static final String PROPERTY_TYPE_BASEURI = \"baseuri\";\n\n /**\n * Base URI for creating semantic web resources with auto-generating timestamp.\n */\n public static final String PROPERTY_TYPE_BASEURI_AUTOGEN = \"baseuri_autogen\";\n\n /**\n * Choices of text-to-speech countries. {@link\n * com.google.appinventor.client.widgets.properties.CountryChoicePropertyEditor}.\n */\n public static final String PROPERTY_TYPE_TEXT_TO_SPEECH_COUNTRIES = \"countries\";\n\n /**\n * Choices of text-to-speech languages. {@link\n * com.google.appinventor.client.widgets.properties.LanguageChoicePropertyEditor}.\n */\n public static final String PROPERTY_TYPE_TEXT_TO_SPEECH_LANGUAGES = \"languages\";\n\n /**\n * Choices of the \"Sizing\" property in Form.java. Used to specify if we are going to use\n * the true size of the real screen (responsize) or scale automatically to make all devices\n * look like an old phone (fixed).\n */\n public static final String PROPERTY_TYPE_SIZING = \"sizing\";\n\n /**\n * FirebaseURL -- A type of String property that has a special default value\n * selected via a checkbox.\n */\n\n public static final String PROPERTY_TYPE_FIREBASE_URL = \"FirbaseURL\";\n\n /**\n * Specifies how a picture is scaled when its dimensions are changed.\n * Choices are 0 - Scale proportionally, 1 - Scale to fit\n * See {@link com.google.appinventor.client.widgets.properties.ScalingChoicePropertyEditor}\n */\n public static final String PROPERTY_TYPE_SCALING = \"scaling\";\n}", "public class YaVersion {\n private YaVersion() {\n }\n\n // ............................ Young Android System Version Number .............................\n\n // YOUNG_ANDROID_VERSION must be incremented when either the blocks language or a component\n // changes.\n // TODO(lizlooney) - should this version number be generated so that it is automatically\n // incremented when the blocks language or a component changes?\n\n // For YOUNG_ANDROID_VERSION 2:\n // - The Logger component was removed. The Notifier component should be used instead.\n // - TINYWEBDB_COMPONENT_VERSION was incremented to 2.\n // For YOUNG_ANDROID_VERSION 3:\n // - BLOCKS_LANGUAGE_VERSION was incremented to 2.\n // For YOUNG_ANDROID_VERSION 4:\n // - The LegoNxtConnection component was added.\n // For YOUNG_ANDROID_VERSION 5:\n // - The Camera component was added.\n // For YOUNG_ANDROID_VERSION 6:\n // - FORM_COMPONENT_VERSION was incremented to 2.\n // For YOUNG_ANDROID_VERSION 7:\n // - The Bluetooth component was added.\n // For YOUNG_ANDROID_VERSION 8:\n // - PLAYER_COMPONENT_VERSION was incremented to 2.\n // - SOUND_COMPONENT_VERSION was incremented to 2.\n // - VIDEOPLAYER_COMPONENT_VERSION was incremented to 2.\n // For YOUNG_ANDROID_VERSION 9:\n // - The LegoNxtConnection component was removed without backwards compatibility.\n // - The LegoMindstormsNxtDirect component was added.\n // - The LegoMindstormsNxtDrive component was added.\n // - The Bluetooth component was removed without backwards compatibility.\n // - The BluetoothClient component was added.\n // - The BluetoothServer component was added.\n // For YOUNG_ANDROID_VERSION 10:\n // - ACTIVITYSTARTER_COMPONENT_VERSION was incremented to 2.\n // For YOUNG_ANDROID_VERSION 11:\n // - BLUETOOTHCLIENT_COMPONENT_VERSION was incremented to 2.\n // - BLUETOOTHSERVER_COMPONENT_VERSION was incremented to 2.\n // For YOUNG_ANDROID_VERSION_12:\n // - TWITTER_COMPONENT_VERSION was incremented to 2.\n // - The Twitter component was changed to support OAuth authentication.\n // For YOUNG_ANDROID_VERSION 13:\n // - The LegoMindstormsNxtTouchSensor component was added.\n // - The LegoMindstormsNxtLightSensor component was added.\n // - The LegoMindstormsNxtSoundSensor component was added.\n // - The LegoMindstormsNxtUltrasonicSensor component was added.\n // For YOUNG_ANDROID_VERSION 14:\n // - LegoMindstormsNXT* components were renamed.\n // For YOUNG_ANDROID_VERSION 15:\n // - TEXTBOX_COMPONENT_VERSION was incremented to 2.\n // For YOUNG_ANDROID_VERSION 16:\n // - FORM_COMPONENT_VERSION was incremented to 3.\n // For YOUNG_ANDROID_VERSION 17:\n // - BLOCKS_LANGUAGE_VERSION was incremented to 3.\n // For YOUNG_ANDROID_VERSION 18:\n // - ACTIVITYSTARTER_COMPONENT_VERSION was incremented to 3.\n // - BLUETOOTHCLIENT_COMPONENT_VERSION was incremented to 3.\n // - BLUETOOTHSERVER_COMPONENT_VERSION was incremented to 3.\n // - FORM_COMPONENT_VERSION was incremented to 4.\n // - PLAYER_COMPONENT_VERSION was incremented to 3.\n // - SOUND_COMPONENT_VERSION was incremented to 3.\n // - VIDEOPLAYER_COMPONENT_VERSION was incremented to 3.\n // For YOUNG_ANDROID_VERSION 19:\n // - The NxtColorSensor component was added.\n // For YOUNG_ANDROID_VERSION 20:\n // - The SoundRecorder component was added.\n // For YOUNG_ANDROID_VERSION 21:\n // - BUTTON_COMPONENT_VERSION was incremented to 2.\n // - CHECKBOX_COMPONENT_VERSION was incremented to 2.\n // - CONTACTPICKER_COMPONENT_VERSION was incremented to 2.\n // - EMAILPICKER_COMPONENT_VERSION was incremented to 2.\n // - IMAGEPICKER_COMPONENT_VERSION was incremented to 2.\n // - LABEL_COMPONENT_VERSION was incremented to 2.\n // - LISTPICKER_COMPONENT_VERSION was incremented to 2.\n // - PASSWORDTEXTBOX_COMPONENT_VERSION was incremented to 2.\n // - PHONENUMBERPICKER_COMPONENT_VERSION was incremented to 2.\n // - TEXTBOX_COMPONENT_VERSION was incremented to 3.\n // For YOUNG_ANDROID_VERSION 22:\n // - BLOCKS_LANGUAGE_VERSION was incremented to 4.\n // - CANVAS_COMPONENT_VERSION was incremented to 2.\n // For YOUNG_ANDROID_VERSION 23:\n // - IMAGESPRITE_COMPONENT_VERSION was incremented to 2.\n // For YOUNG_ANDROID_VERSION 24:\n // - BLOCKS_LANGUAGE_VERSION was incremented to 5.\n // For YOUNG_ANDROID_VERSION 25:\n // - BLOCKS_LANGUAGE_VERSION was incremented to 6.\n // For YOUNG_ANDROID_VERSION 26:\n // - In .scm files, values for asset, BluetoothClient, component, lego_nxt_sensor_port,\n // and string properties no longer contain leading and trailing quotes.\n // For YOUNG_ANDROID_VERSION 27:\n // - BLUETOOTHCLIENT_COMPONENT_VERSION was incremented to 4.\n // - BLUETOOTHSERVER_COMPONENT_VERSION was incremented to 4.\n // For YOUNG_ANDROID_VERSION 28:\n // - BLOCKS_LANGUAGE_VERSION was incremented to 7.\n // For YOUNG_ANDROID_VERSION 29:\n // - BLOCKS_LANGUAGE_VERSION was incremented to 8.\n // For YOUNG_ANDROID_VERSION 30:\n // - BLOCKS_LANGUAGE_VERSION was incremented to 9.\n // For YOUNG_ANDROID_VERSION 31:\n // - BLOCKS_LANGUAGE_VERSION was incremented to 10.\n // For YOUNG_ANDROID_VERSION 32:\n // - LISTPICKER_COMPONENT_VERSION was incremented to 3.\n // For YOUNG_ANDROID_VERSION 33:\n // - CANVAS_COMPONENT_VERSION was incremented to 3.\n // For YOUNG_ANDROID_VERSION 34:\n // - IMAGESPRITE_COMPONENT_VERSION was incremented to 3.\n // - BALL_COMPONENT_VERSION was incremented to 2.\n // For YOUNG_ANDROID_VERSION 35:\n // - FORM_COMPONENT_VERSION was incremented to 5.\n // For YOUNG_ANDROID_VERSION 36:\n // - FusiontablesControl component was added\n // - BLOCKS_LANGUAGE_VERSION was incremented to 11 (CSV-related list functions)\n // For YOUNG_ANDROID_VERSION 37:\n // - CANVAS_COMPONENT_VERSION was incremented to 4.\n // For YOUNG_ANDROID_VERSION 38:\n // - CONTACTPICKER_COMPONENT_VERSION was incremented to 3.\n // - IMAGEPICKER_COMPONENT_VERSION was incremented to 3.\n // - LISTPICKER_COMPONENT_VERSION was incremented to 4.\n // - PHONENUMBERPICKER_COMPONENT_VERSION was incremented to 3.\n // For YOUNG_ANDROID_VERSION 39:\n // - BLOCKS_LANGUAGE_VERSION was incremented to 12\n // For YOUNG_ANDROID_VERSION 40:\n // - BUTTON_COMPONENT_VERSION was incremented to 3.\n // For YOUNG_ANDROID_VERSION 41:\n // - FORM_COMPONENT_VERSION was incremented to 6.\n // - BLOCKS_LANGUAGE_VERSION was incremented to 13\n // For YOUNG_ANDROID_VERSION 42:\n // - The Web component was added.\n // For YOUNG_ANDROID_VERSION 43:\n // - BALL_COMPONENT_VERSION was incremented to 3.\n // - IMAGESPRITE_COMPONENT_VERSION was incremented to 4.\n // For YOUNG_ANDROID_VERSION 44:\n // - BLOCKS_LANGUAGE_VERSION was incremented to 14\n // For YOUNG_ANDROID_VERSION 45:\n // - ORIENTATIONSENSOR_COMPONENT_VERSION was incremented to 2.\n // For YOUNG_ANDROID_VERSION 46:\n // - BLOCKS_LANGUAGE_VERSION was incremented to 15.\n // For YOUNG_ANDROID_VERSION 47:\n // - WebViewer component was added\n // For YOUNG_ANDROID_VERSION 48:\n // - WEB_COMPONENT_VERSION was incremented to 2.\n // For YOUNG_ANDROID_VERSION 49:\n // - WEBVIEWER_COMPONENT_VERSION was incremented to 2.\n // For YOUNG_ANDROID_VERSION 50:\n // - TEXTBOX_COMPONENT_VERSION was incremented to 4:\n // For YOUNG_ANDROID_VERSION 51:\n // - CANVAS_VERSION was incremented to 5.\n // - BLOCKS_LANGUAGE_VERSION was incremented to 16.\n // For YOUNG_ANDROID_VERSION 52:\n // - BLOCKS_LANGUAGE_VERSION was incremented to 17.\n // For YOUNG_ANDROID_VERSION 53:\n // - BLUETOOTHCLIENT_COMPONENT_VERSION was incremented to 5.\n // - BLUETOOTHSERVER_COMPONENT_VERSION was incremented to 5.\n // For YOUNG_ANDROID_VERSION 54:\n // - BUTTON_COMPONENT_VERSION was incremented to 4.\n // - CONTACTPICKER_COMPONENT_VERSION was incremented to 4.\n // - IMAGEPICKER_COMPONENT_VERSION was incremented to 4.\n // - LISTPICKER_COMPONENT_VERSION was incremented to 5.\n // - PHONENUMBERPICKER_COMPONENT_VERSION was incremented to 4.\n // For YOUNG_ANDROID_VERSION 55:\n // - ACCELEROMETERSENSOR_COMPONENT_VERSION was incremented to 2.\n // For YOUNG_ANDROID_VERSION 56\n // - LOCATIONSENSOR_COMPONENT_VERSION was incremented to 2\n // For YOUNG_ANDROID_VERSION 57:\n // - PLAYER_COMPONENT_VERSION was incremented to 4.\n // For YOUNG_ANDROID_VERSION 58:\n // - FORM_COMPONENT_VERSION was incremented to 7.\n // For YOUNG_ANDROID_VERION 59:\n // - The Camcorder component was added.\n // For YOUNG_ANDROID_VERSION 60:\n // - VIDEOPLAYER_COMPONENT_VERSION was incremented to 4.\n // For YOUNG_ANDROID_VERSION 61:\n // - HORIZONTALARRANGEMENT_COMPONENT_VERSION was incremented to 2\n // - VERTICALARRANGEMENT_COMPONENT_VERSION was incremented to 2\n // - FORM_COMPONENT_VERSION was incremented to 8\n // For YOUNG_ANDROID_VERSION 62:\n // - BALL_COMPONENT_VERSION was incremented to 4.\n // - CANVAS_COMPONENT_VERSION was incremented to 6.\n // - IMAGESPRITE_COMPONENT_VERSION was incremented to 5.\n // For YOUNG_ANDROID_VERSION 63:\n // - ACTIVITYSTARTER_COMPONENT_VERSION was incremented to 4.\n // - FORM_COMPONENT_VERSION was incremented to 9.\n // - LISTPICKER_COMPONENT_VERSION was incremented to 6.\n // For YOUNG_ANDROID_VERSION 64:\n // - FUSIONTABLESCONTROL_COMPONENT_VERSION was incremented to 2.\n // For YOUNG_ANDROID_VERSION 65:\n // - BALL_COMPONENT_VERSION was incremented to 5.\n // - CANVAS_COMPONENT_VERSION was incremented to 7.\n // - IMAGESPRITE_COMPONENT_VERSION was incremented to 6.\n // For YOUNG_ANDROID_VERSION 66:\n // - FORM_COMPONENT_VERSION was incremented to 10.\n // For YOUNG_ANDROID_VERSION 67:\n // - TEXTING_COMPONENT_VERSION was incremented to 2.\n // For YOUNG_ANDROID_VERSION 68:\n // - Phone Status Block was added.\n // For YOUNG_ANDROID_VERSION 69:\n // - IMAGEPICKER_COMPONENT_VERSION was incremented to 5.\n // For YOUNG_ANDROID_VERSION 70:\n // - TEXTING_COMPONENT_VERSION was incremented to 3.\n // For YOUNG_ANDROID_VERSION 71:\n // - NOTIFIER_COMPONENT_VERSION was incremented to 2.\n // For YOUNG_ANDROID_VERSION 72:\n // - WEBVIEWER_COMPONENT_VERSION was incremented to 3\n // For YOUNG_ANDROID_VERSION 73:\n // - BUTTON_COMPONENT_VERSION was incremented to 5.\n // For YOUNG_ANDROID_VERSION 74:\n // - SLIDER_COMPONENT_VERSION was incremented to 1.\n // For YOUNG_ANDROID_VERSION 75:\n // - WEBVIEWER_COMPONENT_VERSION was incremented to 3\n // For YOUNG_ANDROID_VERSION 76:\n // - PLAYER_COMPONENT_VERSION was incremented to 5\n // For YOUNG_ANDROID_VERSION 77:\n // - TWITTER_COMPONENT_VERSION was incremented to 3\n // For YOUNG_ANDROID_VERSION 78:\n // - NEARFIELD_COMPONENT_VERSION was incremented to 1\n // For YOUNG_ANDROID_VERSION 79:\n // - GOOGLECLOUDMESSAGING_COMPONENT_VERSION was incremented to 1\n // For YOUNG_ANDROID_VERSION 80:\n // - LISTPICKER_COMPONENT_VERSION was incremented to 7.\n // For YOUNG_ANDROID_VERSION 81:\n // - NOTIFIER_COMPONENT_VERSION was incremented to 3.\n // For YOUNG_ANDROID_VERSION 82:\n // - ACCELEROMETERSENSOR_COMPONENT_VERSION was incremented to 3.\n // For YOUNG_ANDROID_VERSION 83:\n // - LISTPICKER_COMPONENT_VERSION was incremented to 8.\n // - FORM_COMPONENT_VERSION was incremented to 11.\n // For YOUNG_ANDROID_VERSION 84;\n // - The Google Map component was added\n // For YOUNG_ANDROID_VERSION 85;\n // - The Wifi Sensor component was added\n // For YOUNG_ANDROID_VERSION 86;\n // - The proximity sensor component was added\n // For YOUNG_ANDROID_VERSION 87;\n // - The social proximity sensor component was added\n // For YOUNG_ANDROID_VERSION 88;\n // - The activity probe sensor component was added\n // For YOUNG_ANDROID_VERSION 89;\n // - The batter probe sensor component was added\n // For YOUNG_ANDROID_VERSION 90;\n // - The calllog probe component was added\n // For YOUNG_ANDROID_VERSION 91;\n // - The celltower probe component was added\n // FOR YOUNG_ANDROID_VERSION 91;\n // - The light sensor component was added\n // FOR YOUNG_ANDROID_VERSION 93;\n // - The location probe sensor component was added\n // FOR YOUNG_ANDROID_VERSION 94;\n // - THe pedometer sensor component was added\n // FOR YOUNG_ANDROID_VERSION 95;\n // - The Running application probe component was added\n // FOR YOUNG_ANDROID_VERSION 96;\n // - The Screen probe component was added\n // FOR YOUNG_ANDROID_VRESION 97;\n // - The SMS log probe component was added\n // FOR YOUNG_ANDROID_VERSION 98\n // - The Telephony probe component was added\n // FOR YOUNG_ANDROID_VERSION 99\n // - The Timer component was added\n // FOR YOUNG_ANDROID_VERSION 100\n // - The Dropbox component was added\n // FOR YOUNG_ANDROID_VERSION 101\n // - The SensorDB component was added\n // FOR YOUNG_ANDROID_VERSION 102\n // - The Survey component was added\n // FOR YOUNG_ANDROID_VERSION 103\n // - The Google Drive component was added\n // FOR YOUNG_ANDROID_VERSION 104\n // - The Contact info component was added\n // For YOUNG_ANDROID_VERSION 105:\n // - SEMANTIC_FORM_COMPONENT_VERSION was added.\n // - SEMANTIC_WEB_LISTPICKER_COMPONENT_VERSION was added.\n // - TEXTBOX_COMPONENT_VERSION was incremented to 5.\n // For YOUNG_ANDROID_VERSION 106:\n // - EMAILPICKER_COMPONENT_VERSION was incremented to 3.\n // - PASSWORDTEXTBOX_COMPONENT_VERSION was incremented to 3.\n // - SEMANTIC_FORM_COMPONENT_VERSION was incremented to 2.\n // - TEXTBOX_COMPONENT_VERSION was incremented to 6.\n // For YOUNG_ANDROID_VERSION 107:\n // - SemanticForm Component is renamed to LinkedDataForm Component\n // - SEMANTIC_FORM_COMPONENT_VERSION is renamed to LINKED_DATA_FORM_COMPONENT_VERSION\n // - SemanticWeb Component is renamed to LinkedData Component\n // - SEMANTIC_WEB_COMPONENT_VERSION is renamed to LINKED_DATA_COMPONENT_VERSION\n // - SemanticListPicker Component is renamed to LinkedDataListPicker Component\n // - SEMANTIC_LISTPICKER_COMPONENT_VERSION is renamed to LINKED_DATA_LISTPICKER_COMPONENT_VERSION\n // - The pebbleSmartWatch component was added.\n // For YOUNG_ANDROID_VERSION 108:\n // - LINKED_DATA_LISTPICKER_COMPONENT_VERSION was incremented to 3.\n // For YOUNG_ANDROID_VERSION 109:\n // - LINKED_DATA_COMPONENT_VERSION was incremented to 3.\n \n // For YOUNG_ANDROID_VERSION 110:\n // - FORM_COMPONENT_VERSION was incremented to 12.\n // For YOUNG_ANDROID_VERSION 111:\n // - CAMERA_COMPONENT_VERSION was incremented to 2.\n // For YOUNG_ANDROID_VERSION 112:\n // - VIDEOPLAYER_COMPONENT_VERSION was incremented to 5.\n // - The Sharing Component was added\n // For YOUNG_ANDROID_VERSION 113:\n // - WEBVIEWER_COMPONENT_VERSION was incremented to 4.\n // For YOUNG_ANDROID_VERSION 114:\n // - SPINNER_COMPONENT_VERSION was incremented to 1\n // For YOUNG_ANDROID_VERSION 115:\n // - LISTVIEW_COMPONENT_VERSION was incremented to 1.\n // For YOUNG_ANDROID_VERSION 116:\n // - TEXTTOSPEECH_COMPONENT_VERSION was incremented to 2\n // For YOUNG_ANDROID_VERSION 117:\n // - DATEPICKER_COMPONENT_VERSION was incremented to 1.\n // For YOUNG_ANDROID_VERSION 118:\n // - TIMEPICKER_COMPONENT_VERSION was incremented to 1\n // For YOUNG_ANDROID_VERSION 119:\n // - FILE_COMPONENT_VERSION was incremented to 1.\n // For YOUNG_ANDROID_VERSION 120:\n // - YANDEX_COMPONENT_VERSION was incremented to 1.\n // For YOUNG_ANDROID_VERSION 121:\n // - BUTTON_COMPONENT_VERSION was incremented to 6.\n // For YOUNG_ANDROID_VERSION 122:\n // - LinkedDataStreamingClient was added.\n // For YOUNG_ANDROID_VERSION 123:\n // - Update Twitter uploadImage (removed the twitpick).\n // For YOUNG_ANDROID_VERSION 124 (mit-cml/master YaVersion 96):\n // - TIMEPICKER_COMPONENT_VERSION was incremented to 2.\n // For YOUNG_ANDROID_VERSION 125 (mit-cml/master YaVersion 97):\n // - PLAYER_COMPONENT_VERSION was incremented to 6\n // For YOUNG_ANDROID_VERSION 126 (mit-cml/master YaVersion 98):\n // - PHONECALL_COMPONENT_VERSION was incremented to 2.\n // For YOUNG_ANDROID_VERSION 127 (mit-cml/master YaVersion 99):\n // - CONTACTPICKER_COMPONENT_VERSION was incremented to 5\n // For YOUNG_ANDROID_VERSION 128 (mit-cml/master YaVersion 100):\n // - DATEPICKER_COMPONENT_VERSION was incremented to 2.\n // For YOUNG_ANDROID_VERSION 129 (mit-cml/master YaVersion 101):\n // - FORM_COMPONENT_VERSION was incremented to 13.\n // For YOUNG_ANDROID_VERSION 130 (mit-cml/master YaVersion 102):\n // - FUSIONTABLESCONTROL_COMPONENT_VERSION was incremented to 3.\n // For YOUNG_ANDROID_VERSION 131 (mit-cml/master YaVersion 103):\n // - LISTVIEW_COMPONENT_VERSION was incremented to 2.\n // For YOUNG_ANDROID_VERSION 132 (mit-cml/master YaVersion 104):\n // - TWITTER_COMPONENT_VERSION was incremented to 4.\n // For YOUNG_ANDROID_VERSION 133 (mit-cml/master YaVersion 105):\n // - WEB_COMPONENT_VERSION was incremented to 4.\n // For YOUNG_ANDROID_VERSION 134:\n // - TWITTER_COMPONENT_VERSION was incremented to 5.\n // For YOUNG_ANDROID_VERSION 135 (mit-cml/master YaVersion 106):\n // - LISTVIEW_COMPONENT_VERSION was incremented to 3.\n // For YOUNG_ANDROID_VERSION 136 (mit-cml/master YaVersion 107):\n // - WEBVIEWER_COMPONENT_VERSION was incremented to 5\n // For YOUNG_ANDROID_VERSION 137 (mit-cml/master YaVersion 108):\n // - New Obsfucate Text Block was added and BLOCKS_LANGUAGE_VERSION incremented to 18\n // For YOUNG_ANDROID_VERION 138 (mit-cml/master YaVersion 109):\n // - Added PROXIMITYSENSOR_COMPONENT_VERSION\n // For YOUNG_ANDROID_VERSION 139 (mit-cml/master YaVersion 110):\n // - LABEL_COMPONENT_VERSION was incremented to 3.\n // For YOUNG_ANDROID_VERSION 140 (mit-cml/master YaVersion 111):\n // - BARCODESCANNER_COMPONENT_VERSION was incremented to 2.\n // For YOUNG_ANDROID_VERSION 141 (mit-cml/master YaVersion 112):\n // First test of new upgrading architecture: Dave Wolber's Canvas name changes\n // For YOUNG_ANDROID_VERSION 142 (mit-cml/master YaVersion 113):\n // Second test of new upgrading architecture: Evan Thomas's fillCircle argument for Canvas.DrawCircle\n // - CANVAS_COMPONENT_VERSION was incremented to 9.\n // For YOUNG_ANDROID_VERSION 143 (mit-cml/master YaVersion 114):\n // - FORM_COMPONENT_VERSION was incremented to 14.\n // For YOUNG_ANDROID_VERSION 144 (mit-cml/master YaVersion 115):\n // - CANVAS_COMPONENT_VERSION was incremented to 10.\n // For YOUNG_ANDROID_VERSION 145 (mit-cml/master YaVersion 116):\n // - LISTPICKER_COMPONENT_VERSION was incremented to 9.\n // For YOUNG_ANDROID_VERSION 146 (mit-cml/master YaVersion 117):\n // - LISTVIEW_COMPONENT_VERSION was incremented to 4.\n // For YOUNG_ANDROID_VERSION 147 (mit-cml/master YaVersion 118):\n // - SOUND_RECORDER_COMPONENT_VERSION was incremented to 2.\n // For YOUNG_ANDROID_VERSION 148 (mit-cml/master YaVersion 119):\n // - TEXTBOX_COMPONENT_VERSION was incremented to 5\n // - WEBVIEWER_COMPONENT_VERSION was incremented to 6\n // For YOUNG_ANDROID_VERSION 149 (mit-cml/master YaVersion 120):\n // - SLIDER_COMPONENT_VERSION was incremented to 2\n // For YOUNG_ANDROID_VERSION 150 (mit-cml/master YaVersion 121):\n // - NOTIFIER_COMPONENT_VERSION was incremented to 4\n // For YOUNG_ANDROID_VERSION 151 (mit-cml/master YaVersion 122):\n // - EMAILPICKER_COMPONENT_VERSION was incremented to 3\n // - PASSWORDTEXTBOX_COMPONENT_VERSION was incremented to 3\n // For YOUNG_ANDROID_VERSION 152 (mit-cml/master YaVersion 123):\n // - TEXTTOSPEECH_COMPONENT_VERSION was incremented to 3\n // For YOUNG_ANDROID_VERSION 153 (mit-cml/master YaVersion 124):\n // - FORM_COMPONENT_VERSION was incremented to 15.\n // For YOUNG_ANDROID_VERSION 154 (mit-cml/master YaVersion 125):\n // - LISTVIEW_COMPONENT_VERSION was incremented to 5\n // For YOUNG_ANDROID_VERSION 155 (mit-cml/master YaVersion 126):\n // - ACTIVITYSTARTER_COMPONENT_VERSION was incremented to 5\n // For YOUNG_ANDROID_VERSION 156 (mit-cml/master YaVersion 127):\n // - FORM_COMPONENT_VERSION was incremented to 16.\n // For YOUNG_ANDROID_VERSION 157 (mit-cml/master YaVersion 128):\n // - BLOCKS_LANGUAGE_VERSION was incremented to 19\n // For YOUNG_ANDROID_VERSION 158 (mit-cml/master YaVersion 129):\n // - CLOCK_COMPONENT_VERSION was incremented to 2\n // For YOUNG_ANDROID_VERSION 159 (mit-cml/master YaVersion 130):\n // - TEXTTOSPEECH_COMPONENT_VERSION was incremented to 4\n // For YOUNG_ANDROID_VERSION 160 (mit-cml/master YaVersion 131):\n // - CONTACTPICKER_COMPONENT_VERSION was incremented to 6.\n // For YOUNG_ANDROID_VERSION 161 (mit-cml/master YaVersion 132):\n // - TEXTTOSPEECH_COMPONENT_VERSION was incremented to 5\n // For YOUNG_ANDROID_VERSION 162 (mit-cml/master YaVersion 133):\n // - FILE_COMPONENT_VERSION was incremented to 2\n // For YOUNG_ANDROID_VERSION 163 (mit-cml/master YaVersion 134):\n // - DATEPICKER_COMPONENT_VERSION was incremented to 3\n // - TIMEPICKER_COMPONENT_VERSION was incremented to 3\n // For YOUNG_ANDROID_VERSION 164 (mit-cml/master YaVersion 135):\n // - ACTIVITYSTARTER_COMPONENT_VERSION was incremented to 6\n // For YOUNG_ANDROID_VERSION 165 (mit-cml/master YaVersion 136):\n // - FORM_COMPONENT_VERSION was incremented to 17.\n // For YOUNG_ANDROID_VERSION 166 (mit-cml/master YaVersion 137):\n // - FORM_COMPONENT_VERSION was incremented to 18.\n // For YOUNG_ANDROID_VERSION 167 (mit-cml/master YaVersion 138):\n // - MEDIASTORE_COMPONENT_VERSION was incremented to 1\n // For YOUNG_ANDROID_VERSION 168 (mit-cml/master YaVersion 139):\n // - Reserved for FIRST Tech Challenge.\n // For YOUNG_ANDROID_VERSION 169 (mit-cml/master YaVersion 140):\n // - HORIZONTALARRANGEMENT_COMPONENT_VERSION was incremented to 3.\n // - VERTICALARRANGEMENT_COMPONENT_VERSION was incremented to 3\n // For YOUNG_ANDROID_VERSION 170 (mit-cml/master YaVersion 141):\n // - Reserved for FIRST Tech Challenge.\n // For YOUNG_ANDROID_VERSION 171 (mit-cml/master YaVersion 142):\n // - FORM_COMPONENT_VERSION was incremented to 19.\n // For YOUNG_ANDROID_VERSION 172 (mit-cml/master YaVersion 143):\n // - GyroscopeSensor component was added\n // For YOUNG_ANDROID_VERSION 173 (mit-cml/master YaVersion 144):\n // - Reserved for FIRST Tech Challenge.\n // For YOUNG_ANDROID_VERSION 174 (mit-cml/master YaVersion 145):\n // - Spelling of \"obsfucate\" was corrected to obfuscate and BLOCKS_LANGUAGE_VERSION incremented to 20\n // For YOUNG_ANDROID_VERSION 175 (mit-cml/master YaVersion 146):\n // - CAMERA_COMPONENT_VERSION was incremented to 3.\n // For YOUNG_ANDROID_VERSION 176 (mit-cml/master YaVersion 147):\n // - IMAGE_COMPONENT_VERSION was incremented to 2.\n // For YOUNG_ANDROID_VERSION 177 (mit-cml/master YaVersion 148):\n // - FIREBASE_COMPONENT_VERSION was incremented to 1\n // For YOUNG_ANDROID_VERSION 178 (mit-cml/master YaVersion 149):\n // - CLOCK_COMPONENT_VERSION was incremented to 3\n // For YOUNG_ANDROID_VERSION 179 (mit-cml/master YaVersion 150):\n // - IMAGE_COMPONENT_VERSION was incremented to 3\n\n public static final int YOUNG_ANDROID_VERSION = 179;\n\n // ............................... Blocks Language Version Number ...............................\n\n // NOTE(lizlooney,user) - when the blocks language changes:\n // 1. Increment YOUNG_ANDROID_VERSION above.\n // 2. Increment BLOCKS_LANGUAGE_VERSION here\n // 3. ***Add code in yacodeblocks.BlockSaveFile#upgradeLanguage to upgrade the .blk file contents\n // 4. Add code in YoungAndroidFormUpgrader to upgrade the source file\n // *** BlockSaveFile is no longer used in App Inventor 2 (Feb. 2014)\n \n\n // For BLOCKS_LANGUAGE_VERSION 2:\n // - Allow arguments of different procedures and events to have the same names.\n // For BLOCKS_LANGUAGE_VERSION 3:\n // - Some String operations were added: text<, text=, text>, trim, upcase, downcase\n // For BLOCKS_LANGUAGE_VERSION 4:\n // Added: replace all, copy list, insert list item, for each in range\n // For BLOCKS_LANGUAGE_VERSION 5:\n // - The Math trigonometry functions' formal parameter names were changed, and two\n // blocks (degrees-to-radians and radians-to-degrees) were added.\n // For BLOCKS_LANGUAGE_VERSION 6:\n // - Text blocks, comments, and complaints are encoded on save and decoded on load to\n // preserve international characters.\n // For BLOCKS_LANGUAGE_VERSION 7:\n // - Corrupted character sequences in comments are replaced with * when .blk files are upgraded.\n // For BLOCKS_LANGUAGE_VERSION 8:\n // - Socket labels of some text blocks were changed.\n // For BLOCKS_LANGUAGE_VERSION 9:\n // - Socket labels for degrees-to-radians and radians-to-degrees were fixed.\n // For BLOCKS_LANGUAGE_VERSION 10:\n // - Added not-equal block. Add \"as\" descriptor to def block.\n // For BLOCKS_LANGUAGE_VERSION 11:\n // - CSV-related list functions were added (list to csv row, list to csv table,\n // list from csv row, list from csv table)\n // For BLOCKS_LANGUAGE_VERSION 12:\n // - Changed multiply symbol from star to times; change subtract symbol from hyphen to minus\n // For BLOCKS_LANGUAGE_VERSION 13:\n // - Added open-screen and open-screen-with-start-text.\n // For BLOCKS_LANGUAGE_VERSION 14:\n // - Added generated blocks for component object methods and properties.\n // For BLOCKS_LANGUAGE_VERSION 15:\n // - Added \"is text empty?\" to Text drawer.\n // For BLOCKS_LANGUAGE_VERSION 16:\n // - Added make-color and split-color to Color drawer.\n // For BLOCKS_LANGUAGE_VERSION 17:\n // - Changed open-screen to open-another-screen\n // - Changed open-screen-with-start-text to open-another-screen-with-start-value\n // - Marked get-startup-text as a bad block\n // - Added get-start-value\n // - Added get-plain-start-text\n // - Marked close-screen-with-result as a bad block\n // - Added close-screen-with-value\n // - Added close-screen-with-plain-text\n // For BLOCKS_LANGUAGE_VERSION 18:\n // - New Obsfucate Text Block was added\n // For BLOCKS_LANGUAGE_VERSION 19:\n // The is-number block was modified to include dropdowns for base10, hex, and binary\n // The number-convert blocks was added\n // For BLOCKS_LANGUAGE_VERSION 20:\n // - Spelling of \"Obsfucate\" was corrected to Obfuscate in Text Block\n public static final int BLOCKS_LANGUAGE_VERSION = 20;\n\n // ................................. Component Version Numbers ..................................\n\n // NOTE(lizlooney,user) - when a new component is added:\n // 1. Increment YOUNG_ANDROID_VERSION above.\n // 2. Add the version number for the new component below\n // 3. Add documentation to the appropriate html file in docs/reference/components.\n\n // NOTE(lizlooney,user) - when a component changes:\n // 1. Increment YOUNG_ANDROID_VERSION above.\n // 2. Increment the version number for that component below\n // 3. Add code in com.google.appinventor.client.youngandroid.YoungAndroidFormUpgrader#\n // upgradeComponentProperties to upgrade the .scm file contents\n // *** OBSOLETE 4. Add code in openblocks.yacodeblocks.BlockSaveFile#upgradeComponentBlocks to\n // *** OBSOLETE upgrade the .blk file contents (not used in AI 2)\n // 4. For AI2, update the table in blocklyeditor/src/versioning.js\n // 5. Update documentation in the appropriate html file in docs/reference/components.\n\n\n // Note added after internationalization (8/25/2014)\n // If you add any properties, events or methods to a component you *must*:\n\n // Add an entry for each new property/event/method into\n // OdeMessages.java iff a property with that name doesn't already\n // exist (so if you are adding a property that has the same name as\n // another property in a different component, you don't do it a\n // second time). To add the \"Foo\" property you would add:\n\n // @defaultMessage(\"Foo\")\n // @description(\"\")\n // String FooProperties();\n\n // If you edit the description of a component (but not yet a\n // property,method or event of that component) you must also find and\n // update the description in OdeMessages.java\n\n\n\n //For ACCELEROMETERSENSOR_COMPONENT_VERSION 2:\n // - AccelerometerSensor.MinimumInterval property was added.\n // - AccelerometerSensor.AccelerationChanged method was modified to wait for\n // the minimum interval to elapse before calling a shaking event when necessary.\n //For ACCELEROMETERSENSOR_COMPONENT_VERSION 3:\n // - AccelerometerSensor.Sensitivty property was added.\n public static final int ACCELEROMETERSENSOR_COMPONENT_VERSION = 3;\n\n // For ACTIVITYSTARTER_COMPONENT_VERSION 2:\n // - The ActivityStarter.DataType, ActivityStarter.ResultType, and ActivityStarter.ResultUri\n // properties were added.\n // - The ActivityStarter.ResolveActivity method was added.\n // - The ActivityStarter.ActivityError event was added.\n // For ACTIVITYSTARTER_COMPONENT_VERSION 3:\n // - The ActivityStarter.ActivityError event was marked userVisible false and is no longer used.\n // For ACTIVITYSTARTER_COMPONENT_VERSION 4:\n // - The ActivityStarter.StartActivity was edited to use the parent Form's open screen\n // animation to transition to next activity.\n // For ACTIVITYSTARTER_COMPONENT_VERSION 5:\n // - The ActivityStarter.ActivityCanceled event was added.\n // For ACTIVITYSTARTER_COMPONENT_VERSION 6:\n // - Extras property was added to accept a list of key-value pairs to put to the intent\n public static final int ACTIVITYSTARTER_COMPONENT_VERSION = 6;\n\n // For BALL_COMPONENT_VERSION 2:\n // - The PointTowards method was added (for all sprites)\n // - The heading property was changed from int to double (for all sprites\n // For BALL_COMPONENT_VERSION 3:\n // - The Z property was added (also for ImageSprite)\n // For BALL_COMPONENT_VERSION 4:\n // - The TouchUp, TouchDown, and Flung events were added. (for all sprites)\n // For BALL_COMPONENT_VERSION 5:\n // - Callback parameters speed and heading were added to Flung. (for all sprites)\n public static final int BALL_COMPONENT_VERSION = 5;\n\n public static final int BARCODESCANNER_COMPONENT_VERSION = 1;\n\n // For BLUETOOTHCLIENT_COMPONENT_VERSION 2:\n // - The BluetoothClient.Enabled property was added.\n // For BLUETOOTHCLIENT_COMPONENT_VERSION 3:\n // - The BluetoothClient.BluetoothError event was marked userVisible false and is no longer used.\n // For BLUETOOTHCLIENT_COMPONENT_VERSION 4:\n // - The BluetoothClient.DelimiterByte property was added.\n // For BLUETOOTHCLIENT_COMPONENT_VERSION 5:\n // - The BluetoothClient.Secure property was added.\n public static final int BLUETOOTHCLIENT_COMPONENT_VERSION = 5;\n\n // For BLUETOOTHSERVER_COMPONENT_VERSION 2:\n // - The BluetoothServer.Enabled property was added.\n // For BLUETOOTHSERVER_COMPONENT_VERSION 3:\n // - The BluetoothServer.BluetoothError event was marked userVisible false and is no longer used.\n // For BLUETOOTHSERVER_COMPONENT_VERSION 4:\n // - The BluetoothServer.DelimiterByte property was added.\n // For BLUETOOTHSERVER_COMPONENT_VERSION 5:\n // - The BluetoothServer.Secure property was added.\n public static final int BLUETOOTHSERVER_COMPONENT_VERSION = 5;\n\n // For BUTTON_COMPONENT_VERSION 2:\n // - The Alignment property was renamed to TextAlignment.\n // For BUTTON_COMPONENT_VERSION 3:\n // - The LongClick event was added.\n // For BUTTON_COMPONENT_VERSION 4:\n // - The Shape property was added.\n \n // For BUTTON_COMPONENT_VERSION 5:\n // - The ShowFeedback property was added.\n // For BUTTON_COMPONENT_VERSION 6:\n // - Added TouchUp and TouchDown events\n // - FontSize, FontBold, FontItalic properties made visible in block editor\n public static final int BUTTON_COMPONENT_VERSION = 6;\n \n public static final int CAMCORDER_COMPONENT_VERSION = 1;\n\n // For CAMERA_COMPONENT_VERSION 2:\n // - The UseFront property was added.\n // For CAMERA_COMPONENT_VERSION 3:\n // - The UseFront property was removed :-( .\n public static final int CAMERA_COMPONENT_VERSION = 3;\n\n // For CANVAS_COMPONENT_VERSION 2:\n // - The LineWidth property was added.\n // For CANVAS_COMPONENT_VERSION 3:\n // - The FontSize property was added.\n // - The TextAlignment property was added.\n // - The DrawText method was added.\n // - The DrawTextAtAngle method was added.\n // For CANVAS_COMPONENT_VERSION 4:\n // - Added Save and SaveAs methods\n // For CANVAS_COMPONENT_VERSION 5:\n // - Added GetBackgroundPixelColor, GetPixelColor, and SetBackgroundPixelColor methods.\n // For CANVAS_COMPONENT_VERSION 6:\n // - Added TouchDown, TouchUp, and Flung events.\n // For CANVAS_COMPONENT_VERSION 7:\n // - Callback parameters speed and heading were added to Flung. (for all sprites)\n // For CANVAS_COMPONENT_VERSION 8:\n // Dave Wolber's Canvas name changes:\n // - DrawCircle parameter names changed to centerx,centery, radius\n // - Touched parameter touchedSprite name changed to touchedAnySprite\n // - Dragged parameter draggedSprite name changed to draggedAnySprite\n // For CANVAS_COMPONENT_VERSION 9:\n // - DrawCircle has new fourth parameter (for isFilled), due to Evan Thomas\n // For CANVAS_COMPONENT_VERSION 10:\n // - The default value of the TextAlignment property was changed to Component.ALIGNMENT_CENTER\n public static final int CANVAS_COMPONENT_VERSION = 10;\n\n // For CHECKBOX_COMPONENT_VERSION 2:\n // - The Value property was renamed to Checked.\n public static final int CHECKBOX_COMPONENT_VERSION = 2;\n\n // For CLOCK_COMPONENT_VERSION 2:\n // - The pattern parameter was added to the FormatDate and FormatDateTime.\n // - Add Duration Support\n public static final int CLOCK_COMPONENT_VERSION = 3;\n\n // For CONTACTPICKER_COMPONENT_VERSION 2:\n // - The Alignment property was renamed to TextAlignment.\n // For CONTACTPICKER_COMPONENT_VERSION 3:\n // - The method Open was added.\n // For CONTACTPICKER_COMPONENT_VERSION 4:\n // - The Shape property was added.\n // For CONTACTPICKER_COMPONENT_VERSION 5:\n // - Added PhoneNumber, PhoneNumberList, and EmailAddressList to ContactPicker.\n // - For Eclair and up, we now use ContactsContract instead of the deprecated Contacts.\n // For CONTACTPICKER_COMPONENT_VERSION 6:\n // - The ContactUri property was added\n public static final int CONTACTPICKER_COMPONENT_VERSION = 6;\n\n // For EMAILPICKER_COMPONENT_VERSION 2:\n // - The Alignment property was renamed to TextAlignment.\n // For EMAILPICKER_COMPONENT_VERSION 3:\n // - The ConceptURI property was renamed to ObjectType\n // - RequestFocus function was added (via TextBoxBase)\n public static final int EMAILPICKER_COMPONENT_VERSION = 3;\n\n // For DATEPICKER_COMPONENT_VERSION 2:\n // The datepicker dialog was updated to show the current date\n // instead of the last set date by default.\n // The SetDateToDisplay and LaunchPicker methods were added to\n // give the user more control of what time is displayed in the\n // datepicker dialog.\n // For DATEPICKER_COMPONENT_VERSION 3:\n // - SetDateToDisplayFromInstant, and Instant property are added.\n public static final int DATEPICKER_COMPONENT_VERSION = 3;\n\n // For FILE_COMPONENT_VERSION 2:\n // - The AfterFileSaved event was added.\n public static final int FILE_COMPONENT_VERSION = 2;\n\n // For FORM_COMPONENT_VERSION 2:\n // - The Screen.Scrollable property was added.\n // For FORM_COMPONENT_VERSION 3:\n // - The Screen.Icon property was added.\n // For FORM_COMPONENT_VERSION 4:\n // - The Screen.ErrorOccurred event was added.\n // For FORM_COMPONENT_VERSION 5:\n // - The Screen.ScreenOrientation property and Screen.ScreenOrientationChanged event were added.\n // For FORM_COMPONENT_VERSION 6:\n // - The SwitchForm and SwitchFormWithArgs methods were removed and the OtherScreenClosed event\n // was added.\n // For FORM_COMPONENT_VERSION 7:\n // - The VersionCode and VersionName properties were added.\n // For FROM_COMPONENT_VERSION 8:\n // - The AlignHorizontal property was added\n // - The AlignVertical property was added\n // For FORM_COMPONENT_VERSION 9:\n // - The OpenScreenAnimation property was added\n // - The CloseScreenAnimation property was added\n // For FORM_COMPONENT_VERSION 10:\n // - The BackPressed event was added.\n // For FORM_COMPONENT_VERSION 11:\n // - OpenScreenAnimation and CloseScreenAnimation are now properties.\n // For FORM_COMPONENT_VERSION 12:\n // - AboutScreen property was added\n // For FORM_COMPONENT_VERSION 13:\n // - The Screen.Scrollable property was set to False by default\n // For FORM_COMPONENT_VERSION 14:\n // - The Screen1.AppName was added and no block need to be changed.\n // For FORM_COMPONENT_VERSION 15:\n // - The Screen.ShowStatusBar was added.\n // For FORM_COMPONENT_VERSION 16:\n // - TitleVisible property was added\n // For FORM_COMPONENT_VERSION 17:\n // - The Screen.CompatibilityMode property was added\n // For FORM_COMPONENT_VERSION 18:\n // - Screen.CompatibilityMode property morphed into the\n // Sizing property\n // For FORM_COMPONENT_VERSION 19:\n // - Added HideKeyboard method\n public static final int FORM_COMPONENT_VERSION = 19;\n\n\n // For FUSIONTABLESCONTROL_COMPONENT_VERSION 2:\n // - The Fusiontables API was migrated from SQL to V1\n // For FUSIONTABLESCONTROL_COMPONENT_VERSION 3:\n // - InsertRow, GetRows and GetRowsWithConditions was added.\n // - KeyFile, UseServiceAuthentication and ServiceAccountEmail\n // were added.\n public static final int FUSIONTABLESCONTROL_COMPONENT_VERSION = 3;\n\n public static final int GAMECLIENT_COMPONENT_VERSION = 1;\n\n public static final int GYROSCOPESENSOR_COMPONENT_VERSION = 1;\n\n // For HORIZONTALARRANGEMENT_COMPONENT_VERSION 2:\n // - The AlignHorizontal property was added\n // - The AlignVertical property was added\n // - Added background color & image\n public static final int HORIZONTALARRANGEMENT_COMPONENT_VERSION = 3;\n\n // For IMAGE_COMPONENT_VERSION 2:\n // - The RotationAngle property was added.\n // For IMAGE_COMPONENT_VERSION 3:\n // - Scaling Property added, but hidden for now\n public static final int IMAGE_COMPONENT_VERSION = 3;\n\n // For IMAGEPICKER_COMPONENT_VERSION 2:\n // - The Alignment property was renamed to TextAlignment.\n // For IMAGEPICKER_COMPONENT_VERSION 3:\n // - The method Open was added.\n // For IMAGEPICKER_COMPONENT_VERSION 4:\n // - The Shape property was added.\n // For IMAGEPICKER_COMPONENT_VERSION 5:\n // - The ImagePath property was changed to Selection, and now returns a file path to\n // external storage\n\n public static final int IMAGEPICKER_COMPONENT_VERSION = 5;\n\n // For IMAGESPRITE_COMPONENT_VERSION 2:\n // - The Rotates property was added.\n // For IMAGESPRITE_COMPONENT_VERSION 3:\n // - The PointTowards method was added (for all sprites)\n // - The heading property was changed from int to double (for all sprites)\n // For IMAGESPRITE_COMPONENT_VERSION 4:\n // - The Z property was added (also for Ball)\n // For IMAGESPRITE_COMPONENT_VERSION 5:\n // - The TouchUp, TouchDown, and Flung events were added. (for all sprites)\n // For IMAGESPRITE_COMPONENT_VERSION 6:\n // - Callback parameters speed and heading were added to Flung. (for all sprites)\n public static final int IMAGESPRITE_COMPONENT_VERSION = 6;\n\n // For LABEL_COMPONENT_VERSION 2:\n // - The Alignment property was renamed to TextAlignment.\n // For LABEL_COMPONENT_VERSION 3:\n // - The HasMargins property was added\n public static final int LABEL_COMPONENT_VERSION = 3;\n\n // For LISTPICKER_COMPONENT_VERSION 2:\n // - The Alignment property was renamed to TextAlignment.\n // For LISTPICKER_COMPONENT_VERSION 3:\n // - The SelectionIndex read-write property was added.\n // For LISTPICKER_COMPONENT_VERSION 4:\n // - The method Open was added.\n // For LISTPICKER_COMPONENT_VERSION 5:\n // - The Shape property was added.\n // For LISTPICKER_COMPONENT_VERSION 6:\n // - The getIntent method was modified to provide the ListPickerActivity\n // with the parent Form's open screen animation.\n // For LISTPICKER_COMPONENT_VERSION 7:\n // - Added ShowFilterBar property\n // For LISTPICKER_COMPONENT_VERSION 8:\n // - Added title property\n // For LISTPICKER_COMPONENT_VERSION 9:\n // - Added ItemTextColor, ItemBackgroundColor\n public static final int LISTPICKER_COMPONENT_VERSION = 9;\n\n // For LISTVIEW_COMPONENT_VERSION 1:\n // - Initial version.\n // For LISTVIEW_COMPONENT_VERSION 2:\n // - Added Elements property\n // For LISTVIEW_COMPONENT_VERSION 3:\n // - Added BackgroundColor Property\n // - Added TextColor Property\n // For LISTVIEW_COMPONENT_VERSION 4:\n // - Added TextSize Property\n // For LISTVIEW_COMPONENT_VERSION 5:\n // - Added SelectionColor Property\n public static final int LISTVIEW_COMPONENT_VERSION = 5;\n\n // For LOCATIONSENSOR_COMPONENT_VERSION 2:\n // - The TimeInterval and DistanceInterval properties were added.\n public static final int LOCATIONSENSOR_COMPONENT_VERSION = 2;\n\n // For NEARFIELD_COMPONENT_VERSION 1:\n public static final int NEARFIELD_COMPONENT_VERSION = 1;\n\n // For NOTIFIER_COMPONENT_VERSION 2:\n // - To ShowChooseDialog and ShowTextDialog, new arg was added to indicate if dialog is cancelable\n // For NOTIFIER_COMPONENT_VERSION 3:\n // - Added NotifierColor, TextColor and NotifierLength options\n // For NOTIFIER_COMPONENT_VERSION 4:\n // - Added a ShowProgressDialog method, and a DismissProgressDialog method\n public static final int NOTIFIER_COMPONENT_VERSION = 4;\n\n public static final int NXT_COLORSENSOR_COMPONENT_VERSION = 1;\n\n public static final int NXT_DIRECT_COMMANDS_COMPONENT_VERSION = 1;\n\n public static final int NXT_DRIVE_COMPONENT_VERSION = 1;\n\n public static final int NXT_LIGHTSENSOR_COMPONENT_VERSION = 1;\n\n public static final int NXT_SOUNDSENSOR_COMPONENT_VERSION = 1;\n\n public static final int NXT_TOUCHSENSOR_COMPONENT_VERSION = 1;\n\n public static final int NXT_ULTRASONICSENSOR_COMPONENT_VERSION = 1;\n\n // For ORIENTATIONSENSOR_COMPONENT_VERSION = 2:\n // - The Yaw property was renamed to Azimuth.\n // - The yaw parameter to OrientationChanged was renamed to azimuth.\n public static final int ORIENTATIONSENSOR_COMPONENT_VERSION = 2;\n \n public static final int SOCIALPROXIMITYSENSOR_COMPONENT_VERSION = 1;\n \n public static final int WIFISENSOR_COMPONENT_VERSION = 1;\n \n public static final int LOCATIONPROBESENSOR_COMPONENT_VERSION = 1;\n \n public static final int CELLTOWERPROBESENSOR_COMPONENT_VERSION = 1;\n \n public static final int ACTIVITYPROBESENSOR_COMPONENT_VERSION = 1;\n \n public static final int RUNNINGAPPLICATIONS_COMPONENT_VERSION = 1;\n \n public static final int SCREENSTATUS_COMPONENT_VERSION = 1;\n \n public static final int LIGHTSENSOR_COMPONENT_VERSION = 1;\n \n public static final int CALLLOGHISTORY_COMPONENT_VERSION = 1;\n \n public static final int TIMER_COMPONENT_VERSION = 1;\n \n public static final int BATTERYSENSOR_COMPONENT_VERSION = 1;\n public static final int PEDOMETERSENSOR_COMPONENT_VERSION = 1;\n public static final int SURVEY_COMPONENT_VERSION = 1;\n public static final int TELEPHONY_COMPONENT_VERSION = 1;\n\n // For PASSWORDTEXTBOX_COMPONENT_VERSION 2:\n // - The Alignment property was renamed to TextAlignment.\n // For PASSWORDTEXTBOX_COMPONENT_VERSION 3\n // - The ConceptURI property was renamed to ObjectType.\n // - Added RequestFocus Function (via TextBoxBase)\n public static final int PASSWORDTEXTBOX_COMPONENT_VERSION = 3;\n\n public static final int PEDOMETER_COMPONENT_VERSION = 1;\n\n // For PHONECALL_COMPONENT_VERSION 2:\n // - The PhoneCallStarted event was added.\n // - The PhoneCallEnded event was added.\n // - The IncomingCallAnswered event was added.\n public static final int PHONECALL_COMPONENT_VERSION = 2;\n\n // For PHONENUMBERPICKER_COMPONENT_VERSION 2:\n // - The Alignment property was renamed to TextAlignment.\n // For PHONENUMBERPICKER_COMPONENT_VERSION 3:\n // - The method Open was added.\n // For PHONENUMBERPICKER_COMPONENT_VERSION 4:\n // - The Shape property was added.\n public static final int PHONENUMBERPICKER_COMPONENT_VERSION = 4;\n\n public static final int PHONESTATUS_COMPONENT_VERSION = 1;\n\n // For PLAYER_COMPONENT_VERSION 2:\n // - The Player.PlayerError event was added.\n // For PLAYER_COMPONENT_VERSION 3:\n // - The Player.PlayerError event was marked userVisible false and is no longer used.\n // For PLAYER_COMPONENT_VERSION 4:\n // - The Player.Completed event was added.\n // - The IsLooping property was added.\n // - The Volume property was added.\n // - The IsPlaying method was added.\n // For PLAYER_COMPONENT_VERSION 5:\n // - The IsLooping property was renamed to Loop.\n // For PLAYER_COMPONENT_VERSION 6:\n // - The PlayInForeground property was added.\n // - The OtherPlayerStarted event was added.\n\n public static final int PLAYER_COMPONENT_VERSION = 6;\n\n public static final int SHARING_COMPONENT_VERSION = 1;\n\n // For SLIDER_COMPONENT_VERSION 1:\n // - Initial version.\n // For SLIDER_COMPONENT_VERSION 2:\n // - Added the property to allow for the removal of the Thumb Slider\n public static final int SLIDER_COMPONENT_VERSION = 2;\n\n // For SPINNER_COMPONENT_VERSION 1:\n public static final int SPINNER_COMPONENT_VERSION = 1;\n\n // For SOUND_COMPONENT_VERSION 2:\n // - The Sound.SoundError event was added.\n // For SOUND_COMPONENT_VERSION 3:\n // - The Sound.SoundError event was marked userVisible false and is no longer used.\n public static final int SOUND_COMPONENT_VERSION = 3;\n\n // For SOUND_RECORDER_COMPONENT_VERSION 2:\n // - The SavedRecording property was added.\n public static final int SOUND_RECORDER_COMPONENT_VERSION = 2;\n\n public static final int SPEECHRECOGNIZER_COMPONENT_VERSION = 1;\n\n public static final int TABLEARRANGEMENT_COMPONENT_VERSION = 1;\n\n // For TEXTBOX_COMPONENT_VERSION 2:\n // - The TextBox.NumbersOnly property was added.\n // For TEXTBOX_COMPONENT_VERSION 3:\n // - The Alignment property was renamed to TextAlignment.\n // For TEXTBOX_COMPONENT_VERSION 4:\n // - The HideKeyboard method was added.\n // - The MultiLine property was added.\n // For TEXTBOX_COMPONENT_VERSION 5:\n // - Implementation of LDComponent was added.\n // For TEXTBOX_COMPONENT_VERSION 6:\n // - The ConceptURI property was renamed to ObjectType.\n // - RequestFocus method was added\n public static final int TEXTBOX_COMPONENT_VERSION = 6;\n\n // For TEXTING_COMPONENT_VERSION 2:\n // Texting over Wifi was implemented using Google Voice\n // This works only on phones with 2.0 (Eclair) or higher.\n // It requires that the user has a Google Voice account\n // and has the mobile Voice app installed on the phone.\n // Access to Google Voice is controlled through OAuth 2.\n // For TEXTING_COMPONENT_VERISON 3:\n // - receivingEnabled is now an integer in the range 1-3\n // instead of a boolean\n public static final int TEXTING_COMPONENT_VERSION = 3;\n\n // For TEXTTOSPEECH_COMPONENT_VERSION 2:\n // - added speech pitch and rate\n // For TEXTTOSPEECH_COMPONENT_VERSION 3:\n // - the AvailableLanguages property was added\n // - the AvailableCountries property was added\n // For TEXTTOSPEECH_COMPONENT_VERSION 4:\n // - the Country designer property was changed to use a ChoicePropertyEditor\n // - the Language designer property was changed to use a ChoicePropertyEditor\n // For TEXTTOSPEECH_COMPONENT_VERSION 5:\n // - default value was added to the Country designer property\n // - default value was added to the Language designer property\n public static final int TEXTTOSPEECH_COMPONENT_VERSION = 5;\n\n // For TIMEPICKER_COMPONENT_VERSION 2:\n // After feedback from the forum, the timepicker dialog was updated\n // to show the current time instead of the last set time by default.\n // The SetTimeToDisplay and LaunchPicker methods were added to\n // give the user more control of what time is displayed in the\n // timepicker dialog.\n // For TIMEPICKER_COMPONENT_VERSION 3:\n // - SetTimeToDisplayFromInstant, and Instant property are added.\n public static final int TIMEPICKER_COMPONENT_VERSION = 3;\n\n public static final int TINYDB_COMPONENT_VERSION = 1;\n\n // For TINYWEBDB_COMPONENT_VERSION 2:\n // - The TinyWebDB.ShowAlert method was removed. Notifier.ShowAlert should be used instead.\n public static final int TINYWEBDB_COMPONENT_VERSION = 2;\n\n // // For FIREBASE_COMPONENT_VERSION 1:\n // - FirebaseDB component introduced\n public static final int FIREBASE_COMPONENT_VERSION = 1;\n\n // For TWITTER_COMPONENT_VERSION 2:\n // - The Authorize method and IsAuthorized event handler were added to support\n // OAuth authentication (now requred by Twitter). These\n // should be used instead of Login and IsLoggedIn. Login is still there but\n // calling Login pops up a notification to use Authorize. IsLoggedIn will\n // be changed to IsAuthorized when the blocks file is upgraded.\n // - Added CheckAuthorized method to check whether the user is already\n // logged in and call IsAuthorized if so. We save the accessToken across app\n // invocations, so it is possible that the app already has authorization\n // when it starts up.\n // - Added DeAuthorize method to forget authorization token (logout, effectively).\n // - Added ConsumerKey and ConsumerSecret designer properties (required for\n // Authorize)\n // - Added Username read-only property that returns the Twitter username when\n // the user is logged in.\n // - The friend timeline was changed to be a list of tuples (lists), where\n // each sub-list is (username message). The old format was just a list\n // of messages and didn't include the username associated with each message.\n // For TWITTER_COMPONENT_VERSION 3:\n // - The 'SetStatus' procedure has been changed to 'Tweet' to be more intuitive.\n // - Added 'TweetWithImage' which uploads an image to TwitPic and adds it to\n // a tweet to allow a user to tweet with a picture. This requires a TwitPic_API_Key\n // property.\n // For TWITTER_COMPONENT_VERSION 4:\n // - Modified 'TweetWithImage' to upload images to Twitter directly because of the shutdown of\n // TwitPic. The TwitPic_API_Key property is now deprecated and hidden.\n // For TWITTER_COMPONENT_VERSION 5:\n // - Added 'ImageUploaded' event to report when an image is uploaded to Twitter and the\n // associated URL for that image.\n public static final int TWITTER_COMPONENT_VERSION = 5;\n\n // For VERTICALARRANGEMENT_COMPONENT_VERSION 2:\n // - The AlignHorizontal property was added\n // - The AlignVertical property was added\n // - Added background color & image\n public static final int VERTICALARRANGEMENT_COMPONENT_VERSION = 3;\n\n // For VIDEOPLAYER_COMPONENT_VERSION 2:\n // - The VideoPlayer.VideoPlayerError event was added.\n // For VIDEOPLAYER_COMPONENT_VERSION 3:\n // - The VideoPlayer.VideoPlayerError event was marked userVisible false and is no longer used.\n // For VIDEOPLAYER_COMPONENT_VERSION 4:\n // - The VideoPlayer.width and VideoPlayer.height variables were marked as user visible.\n // - The FullScreen property was added to the VideoPlayer.\n // For VIDEOPLAYER_COMPONENT_VERSION 5:\n // - The Volume property (setter only) was added to the VideoPlayer.\n public static final int VIDEOPLAYER_COMPONENT_VERSION = 5;\n\n public static final int VOTING_COMPONENT_VERSION = 1;\n\n // For WEB_COMPONENT_VERSION 2:\n // - The RequestHeaders and AllowCookies properties were added.\n // - The BuildPostData and ClearCookies methods were added.\n // - The existing PostText method was renamed to PostTextWithEncoding, and a new PostText\n // method was added.\n // For WEB_COMPONENT_VERSION 3:\n // - PUT and DELETE Actions added (PutText, PutTextWithEncoding, PutFile, and Delete).\n // For WEB_COMPONENT_VERSION 4:\n // - Added method XMLTextDecode\n public static final int WEB_COMPONENT_VERSION = 4;\n\n // For WEBVIEWER_COMPONENT_VERSION 2:\n // - The CanGoForward and CanGoBack methods were added\n // For WEBVIEWER_COMPONENT_VERSION 3:\n // - Add UsesLocation property to set location permissions\n // For WEBVIEWER_COMPONENT_VERSION 4:\n // - Add WebViewString\n // For WEBVIEWER_COMPONENT_VERSION 5:\n // - IgnoreSslError property added\n // For WEBVIEWER_COMPONENT_VERSION 6:\n // - ClearCaches method was added\n public static final int WEBVIEWER_COMPONENT_VERSION = 6;\n \n public static final int DROPBOX_COMPONENT_VERSION = 1;\n // For LINKED_DATA_COMPONENT_VERSION_2:\n // - Renamed SemanticWeb component to LinkedData component\n // For LINKED_DATA_COMPONENT_VERSION 3:\n // - Removed BaseURL property eclipsed by FormID on Linked Data Form\n public static final int LINKED_DATA_COMPONENT_VERSION = 3;\n\n public static final int LD_COMPONENT_VERSION = 1;\n // For MEDIASTORE_COMPONENT_VERSION 1:\n // - Initial Version.\n public static final int MEDIASTORE_COMPONENT_VERSION = 1;\n\n // For YANDEX_COMPONENT_VERSION 1:\n // - Initial version.\n public static final int YANDEX_COMPONENT_VERSION = 1;\n\n //For PROXIMITYSENSOR_COMPONENT_VERSION: Initial Version\n public static final int PROXIMITYSENSOR_COMPONENT_VERSION = 1;\n\n // Rendezvous Server Location\n\n public static final String RENDEZVOUS_SERVER = \"rendezvous.appinventor.mit.edu\";\n\n // Companion Versions and Update Information\n\n // The PREFERRED_COMPANION is displayed to the end-user if\n // they ask (via the Help->About menu) and if they are told\n // that they need to update their companion\n //\n // ACCEPTABLE_COMPANIONS is a list of Companion VersionNames\n // which are usable with this version of the system.\n //\n // COMPANION_UPDATE_URL is the URL used by the Companion\n // Update Mechanism to find the Companion to download.\n // Note: This new Companion needs to be signed by the same\n // key as the Companion it is replacing, as the Package Manager\n // is invoked from the running Companion.\n\n public static final String PREFERRED_COMPANION = \"2.36punya1\";\n public static final String COMPANION_UPDATE_URL = \"\";\n public static final String COMPANION_UPDATE_URL1 = \"\";\n public static final String [] ACCEPTABLE_COMPANIONS = { \"2.36punya1\" };\n\n // Splash Screen Values\n public static final int SPLASH_SURVEY = 1;\n\n // For GOOGLECLOUDMESSAGING_COMPONENT_VERSION 1:\n // - Initial version.\n public static final int GOOGLECLOUDMESSAGING_COMPONENT_VERSION = 1;\n\n // For LINKED_DATA_LISTPICKER_COMPONENT_VERSION_2:\n // - Renamed SemanticWebListPicker to LinkedDataListPicker\n // For LINKED_DATA_LISTPICKER_COMPONENT_VERSION_3:\n // - Added RelationToObject property\n public static final int LINKED_DATA_LISTPICKER_COMPONENT_VERSION = 3;\n\n // For SEMANTIC_FORM_COMPONENT_VERSION 1:\n // - Initial version.\n // For SEMANTIC_FORM_COMPONENT_VERSION 2:\n // - Renamed BaseURI to Form ID\n // - Renamed ConceptURI to Object Type\n // For LINKED_DATA_FORM_COMPONENT_VERSION 3:\n // - Renamed Semantic Form to Linked Data Form\n\n public static final int LINKED_DATA_FORM_COMPONENT_VERSION = 3;\n \n public static final int GOOGLE_DRIVE_COMPONENT_VERSION = 1;\n\n // For GOOGLEMAP_COMPONENT_VERSION 1:\n // - Initial version.\n public static final int GOOGLE_MAP_COMPONENT_VERSION = 1;\n\n public static final int DATA_VIS_COMPONENT_VERSION = 2;\n \n public static final int SMSLOGHISTORY_COMPONENT_VERSION = 1;\n\n public static final int SENSORDB_COMPONENT_VERSION = 1;\n \n public static final int CONTACTINFO_COMPONENT_VERSION = 1;\t\n\n public static final int PEBBLESMARTWATCH_COMPONENT_VERSION = 1;\t\n \n // For LINKEDDATASTREAMING_COMPONENT_VERSION 1:\n public static final int LINKEDDATASTREAMING_COMPONENT_VERSION = 1;\n\n}", "public final class ErrorMessages {\n // Phone version errors\n public static final int ERROR_FUNCTIONALITY_NOT_SUPPORTED_CONTACT_EMAIL = 1;\n public static final int ERROR_FUNCTIONALITY_NOT_SUPPORTED_EMAIL_PICKER = 2;\n public static final int ERROR_FUNCTIONALITY_NOT_SUPPORTED_FUSIONTABLES_CONTROL = 3;\n public static final int ERROR_FUNCTIONALITY_NOT_SUPPORTED_WEB_COOKIES = 4;\n public static final int ERROR_FUNCTIONALITY_NOT_SUPPORTED_WIFI_DIRECT = 5;\n // LocationSensor errors\n public static final int ERROR_LOCATION_SENSOR_LATITUDE_NOT_FOUND = 101;\n public static final int ERROR_LOCATION_SENSOR_LONGITUDE_NOT_FOUND = 102;\n // Camera errors\n public static final int ERROR_CAMERA_NO_IMAGE_RETURNED = 201;\n // Twitter errors\n public static final int ERROR_TWITTER_UNSUPPORTED_LOGIN_FUNCTION = 301;\n public static final int ERROR_TWITTER_BLANK_CONSUMER_KEY_OR_SECRET = 302;\n public static final int ERROR_TWITTER_EXCEPTION = 303;\n public static final int ERROR_TWITTER_UNABLE_TO_GET_ACCESS_TOKEN = 304;\n public static final int ERROR_TWITTER_AUTHORIZATION_FAILED = 305;\n public static final int ERROR_TWITTER_SET_STATUS_FAILED = 306;\n public static final int ERROR_TWITTER_REQUEST_MENTIONS_FAILED = 307;\n public static final int ERROR_TWITTER_REQUEST_FOLLOWERS_FAILED = 308;\n public static final int ERROR_TWITTER_REQUEST_DIRECT_MESSAGES_FAILED = 309;\n public static final int ERROR_TWITTER_DIRECT_MESSAGE_FAILED = 310;\n public static final int ERROR_TWITTER_FOLLOW_FAILED = 311;\n public static final int ERROR_TWITTER_STOP_FOLLOWING_FAILED = 312;\n public static final int ERROR_TWITTER_REQUEST_FRIEND_TIMELINE_FAILED = 313;\n public static final int ERROR_TWITTER_SEARCH_FAILED = 314;\n public static final int ERROR_TWITTER_INVALID_IMAGE_PATH = 315;\n // LegoMindstormsNXT errors\n public static final int ERROR_NXT_BLUETOOTH_NOT_SET = 401;\n public static final int ERROR_NXT_NOT_CONNECTED_TO_ROBOT = 402;\n public static final int ERROR_NXT_INVALID_RETURN_PACKAGE = 403;\n public static final int ERROR_NXT_ERROR_CODE_RECEIVED = 404;\n public static final int ERROR_NXT_INVALID_PROGRAM_NAME = 405;\n public static final int ERROR_NXT_INVALID_FILE_NAME = 406;\n public static final int ERROR_NXT_INVALID_MOTOR_PORT = 407;\n public static final int ERROR_NXT_INVALID_SENSOR_PORT = 408;\n public static final int ERROR_NXT_INVALID_MAILBOX = 409;\n public static final int ERROR_NXT_MESSAGE_TOO_LONG = 410;\n public static final int ERROR_NXT_DATA_TOO_LARGE = 411;\n public static final int ERROR_NXT_COULD_NOT_DECODE_ELEMENT = 412;\n public static final int ERROR_NXT_COULD_NOT_FIT_ELEMENT_IN_BYTE = 413;\n public static final int ERROR_NXT_INVALID_SOURCE_ARGUMENT = 414;\n public static final int ERROR_NXT_INVALID_DESTINATION_ARGUMENT = 415;\n public static final int ERROR_NXT_UNABLE_TO_DOWNLOAD_FILE = 416;\n public static final int ERROR_NXT_CANNOT_DETECT_COLOR = 417;\n public static final int ERROR_NXT_CANNOT_DETECT_LIGHT = 418;\n public static final int ERROR_NXT_INVALID_GENERATE_COLOR = 419;\n // Bluetooth errors\n public static final int ERROR_BLUETOOTH_NOT_AVAILABLE = 501;\n public static final int ERROR_BLUETOOTH_NOT_ENABLED = 502;\n public static final int ERROR_BLUETOOTH_INVALID_ADDRESS = 503;\n public static final int ERROR_BLUETOOTH_NOT_PAIRED_DEVICE = 504;\n public static final int ERROR_BLUETOOTH_NOT_REQUIRED_CLASS_OF_DEVICE = 505;\n public static final int ERROR_BLUETOOTH_INVALID_UUID = 506;\n public static final int ERROR_BLUETOOTH_UNABLE_TO_CONNECT = 507;\n public static final int ERROR_BLUETOOTH_UNABLE_TO_LISTEN = 508;\n public static final int ERROR_BLUETOOTH_UNABLE_TO_ACCEPT = 509;\n public static final int ERROR_BLUETOOTH_COULD_NOT_DECODE = 510;\n public static final int ERROR_BLUETOOTH_COULD_NOT_FIT_NUMBER_IN_BYTE = 511;\n public static final int ERROR_BLUETOOTH_COULD_NOT_FIT_NUMBER_IN_BYTES = 512;\n public static final int ERROR_BLUETOOTH_COULD_NOT_DECODE_ELEMENT = 513;\n public static final int ERROR_BLUETOOTH_COULD_NOT_FIT_ELEMENT_IN_BYTE = 514;\n public static final int ERROR_BLUETOOTH_NOT_CONNECTED_TO_DEVICE = 515;\n public static final int ERROR_BLUETOOTH_UNABLE_TO_WRITE = 516;\n public static final int ERROR_BLUETOOTH_UNABLE_TO_READ = 517;\n public static final int ERROR_BLUETOOTH_END_OF_STREAM = 518;\n public static final int ERROR_BLUETOOTH_UNSUPPORTED_ENCODING = 519;\n // ActivityStarter errors\n public static final int ERROR_ACTIVITY_STARTER_NO_CORRESPONDING_ACTIVITY = 601;\n // Media errors\n public static final int ERROR_UNABLE_TO_LOAD_MEDIA = 701;\n public static final int ERROR_UNABLE_TO_PREPARE_MEDIA = 702;\n public static final int ERROR_UNABLE_TO_PLAY_MEDIA = 703;\n public static final int ERROR_MEDIA_EXTERNAL_STORAGE_READONLY = 704;\n public static final int ERROR_MEDIA_EXTERNAL_STORAGE_NOT_AVAILABLE = 705;\n public static final int ERROR_MEDIA_IMAGE_FILE_FORMAT = 706;\n public static final int ERROR_MEDIA_CANNOT_OPEN = 707;\n public static final int ERROR_MEDIA_FILE_ERROR = 708;\n public static final int ERROR_UNABLE_TO_FOCUS_MEDIA = 709;\n public static final int ERROR_SOUND_NOT_READY = 710;\n public static final int ERROR_OUT_OF_MEMORY_LOADING_MEDIA = 711;\n // SoundRecorder errors\n public static final int ERROR_SOUND_RECORDER = 801;\n public static final int ERROR_SOUND_RECORDER_CANNOT_CREATE = 802;\n // Form errors\n public static final int ERROR_INVALID_SCREEN_ORIENTATION = 901;\n public static final int ERROR_SCREEN_NOT_FOUND = 902;\n public static final int ERROR_SCREEN_BAD_VALUE_RECEIVED = 903;\n public static final int ERROR_SCREEN_BAD_VALUE_FOR_SENDING = 904;\n public static final int ERROR_SCREEN_INVALID_ANIMATION = 905;\n public static final int ERROR_NO_FOCUSABLE_VIEW_FOUND = 906;\n // Canvas errors\n public static final int ERROR_CANVAS_BITMAP_ERROR = 1001;\n public static final int ERROR_CANVAS_WIDTH_ERROR = 1002;\n public static final int ERROR_CANVAS_HEIGHT_ERROR = 1003;\n // Web errors\n public static final int ERROR_WEB_UNABLE_TO_GET = 1101;\n public static final int ERROR_WEB_UNSUPPORTED_ENCODING = 1102;\n public static final int ERROR_WEB_UNABLE_TO_POST_OR_PUT = 1103;\n public static final int ERROR_WEB_UNABLE_TO_POST_OR_PUT_FILE = 1104;\n public static final int ERROR_WEB_JSON_TEXT_DECODE_FAILED = 1105;\n public static final int ERROR_WEB_HTML_TEXT_DECODE_FAILED = 1106;\n // There is a gap here because two ContactPicker errors below use the numbers 1107 and 1108.\n public static final int ERROR_WEB_MALFORMED_URL = 1109;\n public static final int ERROR_WEB_REQUEST_HEADER_NOT_LIST = 1110;\n public static final int ERROR_WEB_REQUEST_HEADER_NOT_TWO_ELEMENTS = 1111;\n public static final int ERROR_WEB_BUILD_REQUEST_DATA_NOT_LIST = 1112;\n public static final int ERROR_WEB_BUILD_REQUEST_DATA_NOT_TWO_ELEMENTS = 1113;\n public static final int ERROR_WEB_UNABLE_TO_DELETE = 1114;\n public static final int ERROR_WEB_XML_TEXT_DECODE_FAILED = 1115;\n // Contact picker (and PhoneNumberPicker) errors\n public static final int ERROR_PHONE_UNSUPPORTED_CONTACT_PICKER = 1107;\n public static final int ERROR_PHONE_UNSUPPORTED_SEARCH_IN_CONTACT_PICKING = 1108;\n //Camcorder errors\n public static final int ERROR_CAMCORDER_NO_CLIP_RETURNED = 1201;\n \n // VideoPlayer errors\n public static final int ERROR_VIDEOPLAYER_FULLSCREEN_UNAVAILBLE = 1301;\n public static final int ERROR_VIDEOPLAYER_FULLSCREEN_CANT_EXIT = 1302;\n public static final int ERROR_VIDEOPLAYER_FULLSCREEN_UNSUPPORTED = 1303;\n // Arrangement errors\n public static final int ERROR_BAD_VALUE_FOR_HORIZONTAL_ALIGNMENT = 1401;\n public static final int ERROR_BAD_VALUE_FOR_VERTICAL_ALIGNMENT = 1402;\n // BarcodeScanner errors\n public static final int ERROR_NO_SCANNER_FOUND = 1501;\n // ImagePicker errors\n public static final int ERROR_CANNOT_SAVE_IMAGE = 1601;\n public static final int ERROR_CANNOT_COPY_MEDIA = 1602;\n\n // Texting errors\n public static final int ERROR_BAD_VALUE_FOR_TEXT_RECEIVING = 1701;\n\n // Repl Communication Errors\n public static final int ERROR_REPL_SECURITY_ERROR = 1801;\n // AccelerometerSensor Errors\n public static final int ERROR_BAD_VALUE_FOR_ACCELEROMETER_SENSITIVITY = 1901;\n \n // Please start the next group of error numbers at 2001.\n \n // below is error messages only for fuming_wei sensor and cloud compoents\n // Dropbox errors \n public static final int ERROR_DROPBOX_BLANK_APP_KEY_OR_SECRET = 11810;\n public static final int ERROR_DROPBOX_EXCEPTION = 11811;\n public static final int ERROR_DROPBOX_UNLINKED = 11812;\n public static final int ERROR_DROPBOX_FILESIZE = 11813;\n public static final int ERROR_DROPBOX_PARTIALFILE = 1814;\n public static final int ERROR_DROPBOX_SERVER_INSUFFICIENT_STORAGE = 11815;\n public static final int ERROR_DROPBOX_IO = 11816;\n public static final int ERROR_DROPBOX_FILENOTFOUND = 11817;\n public static final int ERROR_DROPBOX_NO_TWO_RUNNING_TASKS = 11818;\n \n // CallLog/smslog errors\n public static final int ERROR_DATE_FORMAT = 11840;\n\n\n public static final int ERROR_GOOGLEDRIVE_EXCEPTION = 11901;\n public static final int ERROR_GOOGLEDRIVE_IO_EXCEPTION = 11902;\n public static final int ERROR_GOOGLEDRIVE_INVALID_CREDENTIALS = 11903;\n public static final int ERROR_GOOGLEDRIVE_NOT_GRANT_PERMISSION = 11904;\n public static final int ERROR_GOOGLEDRIVE_APP_CONFIG_ERROR = 11905;\n public static final int ERROR_GOOGLEDRIVE_APP_BLACKLIST = 11906;\n public static final int ERROR_GOOGLEDRIVE_HTTP_RESPONSE = 11907;\n public static final int ERROR_GOOGLEDRIVE_NEEDLOGIN = 11908;\n \n public static final int ERROR_SENSORDB_NOTAVAILABLE = 12001;\n public static final int ERROR_SENSORDB_NOTACTIVE = 12002;\n \n\n // Please start the next group of error numbers at 2010.\n \n //Sharing Errors\n public static final int ERROR_FILE_NOT_FOUND_FOR_SHARING = 2001;\n\n // File errors\n public static final int ERROR_CANNOT_FIND_FILE = 2101;\n public static final int ERROR_CANNOT_READ_FILE = 2102;\n public static final int ERROR_CANNOT_CREATE_FILE = 2103;\n public static final int ERROR_CANNOT_WRITE_TO_FILE = 2104;\n public static final int ERROR_CANNOT_DELETE_ASSET = 2105;\n public static final int ERROR_CANNOT_WRITE_ASSET = 2106;\n\n // Yandex.Translate errors\n public static final int ERROR_TRANSLATE_NO_KEY_FOUND = 2201;\n public static final int ERROR_TRANSLATE_SERVICE_NOT_AVAILABLE = 2202;\n public static final int ERROR_TRANSLATE_JSON_RESPONSE = 2203;\n\n // TimePicker errors\n public static final int ERROR_ILLEGAL_HOUR = 2301;\n public static final int ERROR_ILLEGAL_MINUTE = 2302;\n\n // DatePicker errors\n public static final int ERROR_ILLEGAL_DATE = 2401;\n\n // WebViewer errors\n public static final int ERROR_WEBVIEW_SSL_ERROR = 2501;\n\n //FusiontablesControl errors\n public static final int FUSION_TABLES_QUERY_ERROR = 2601;\n\n //TextToSpeech errors\n public static final int ERROR_TTS_NOT_READY = 2701;\n\n // AndroidViewComponent errors\n public static final int ERROR_BAD_PERCENT = 2801;\n\n // 2901-2999 are reserved for FIRST Tech Challenge.\n\n // Image errors\n public static final int ERROR_IMAGE_CANNOT_ROTATE = 3001;\n\n // Start the next group of errors at 3100\n\n public static final int ERROR_GOOGLE_MAP_NOT_INSTALLED = 12010;\n public static final int ERROR_GOOGLE_PLAY_NOT_INSTALLED = 12011;\n public static final int ERROR_GOOGLE_MAP_INVALID_INPUT = 12012;\n public static final int ERROR_GOOGLE_MAP_MARKER_NOT_EXIST = 12013;\n public static final int ERROR_GOOGLE_MAP_JSON_FORMAT_DECODE_FAILED = 12014;\n public static final int ERROR_GOOGLE_MAP_CIRCLE_NOT_EXIST = 12015;\n public static final int ERROR_GOOGLE_PLAY_SERVICE_UPDATE_REQUIRED = 12016;\n public static final int ERROR_GOOGLE_PLAY_DISABLED = 12017;\n public static final int ERROR_GOOGLE_PLAY_INVALID = 12018;\n\n // for Google Cloud Messaging\n public static final int ERROR_GCM_APPSERVER_INVALID = 2019;\n public static final int ERROR_GCM_NO_REGID_FOR_MESSAGE = 2020;\n \n // Mapping of error numbers to error message format strings.\n private static final Map<Integer, String> errorMessages;\n static {\n errorMessages = new HashMap<Integer, String>();\n // Phone version errors\n errorMessages.put(ERROR_FUNCTIONALITY_NOT_SUPPORTED_CONTACT_EMAIL,\n \"Warning: This app contains functionality that does not work on this phone: \" +\n \"picking an EmailAddress.\");\n errorMessages.put(ERROR_FUNCTIONALITY_NOT_SUPPORTED_EMAIL_PICKER,\n \"Warning: This app contains functionality that does not work on this phone: \" +\n \"the EmailPicker component.\");\n errorMessages.put(ERROR_FUNCTIONALITY_NOT_SUPPORTED_FUSIONTABLES_CONTROL,\n \"Warning: This app contains functionality that does not work on this phone: \" +\n \"the FusiontablesControl component.\");\n errorMessages.put(ERROR_FUNCTIONALITY_NOT_SUPPORTED_WEB_COOKIES,\n \"Warning: This app contains functionality that does not work on this phone: \" +\n \"using cookies in the Web component.\");\n errorMessages.put(ERROR_FUNCTIONALITY_NOT_SUPPORTED_WIFI_DIRECT,\n \"Warning: This app contains functionality that does not work on this phone: \" +\n \"Wi-Fi peer-to-peer connectivity.\");\n // LocationSensor errors\n errorMessages.put(ERROR_LOCATION_SENSOR_LATITUDE_NOT_FOUND,\n \"Unable to find latitude from %s.\");\n errorMessages.put(ERROR_LOCATION_SENSOR_LONGITUDE_NOT_FOUND,\n \"Unable to find longitude from %s.\");\n // Camera errors\n errorMessages.put(ERROR_CAMERA_NO_IMAGE_RETURNED,\n \"The camera did not return an image.\");\n // Twitter errors\n errorMessages.put(ERROR_TWITTER_UNSUPPORTED_LOGIN_FUNCTION,\n \"Twitter no longer supports this form of Login. Use the Authorize call instead.\");\n errorMessages.put(ERROR_TWITTER_BLANK_CONSUMER_KEY_OR_SECRET,\n \"The ConsumerKey and ConsumerSecret properties must be set in order to authorize access \" +\n \"for Twitter. Please obtain a Comsumer Key and Consumer Secret specific to your app from \" +\n \"http://twitter.com/oauth_clients/new\");\n errorMessages.put(ERROR_TWITTER_EXCEPTION,\n \"Twitter error: %s\");\n errorMessages.put(ERROR_TWITTER_UNABLE_TO_GET_ACCESS_TOKEN,\n \"Unable to get access token: %s\");\n errorMessages.put(ERROR_TWITTER_AUTHORIZATION_FAILED,\n \"Twitter authorization failed\");\n errorMessages.put(ERROR_TWITTER_SET_STATUS_FAILED,\n \"SetStatus failed. %s\");\n errorMessages.put(ERROR_TWITTER_REQUEST_MENTIONS_FAILED,\n \"RequestMentions failed. %s\");\n errorMessages.put(ERROR_TWITTER_REQUEST_FOLLOWERS_FAILED,\n \"RequestFollowers failed. %s\");\n errorMessages.put(ERROR_TWITTER_REQUEST_DIRECT_MESSAGES_FAILED,\n \"RequestDirectMessages failed. %s\");\n errorMessages.put(ERROR_TWITTER_DIRECT_MESSAGE_FAILED,\n \"DirectMessage failed. %s\");\n errorMessages.put(ERROR_TWITTER_FOLLOW_FAILED,\n \"Follow failed. %s\");\n errorMessages.put(ERROR_TWITTER_STOP_FOLLOWING_FAILED,\n \"StopFollowing failed. %s\");\n errorMessages.put(ERROR_TWITTER_REQUEST_FRIEND_TIMELINE_FAILED,\n \"Twitter RequestFriendTimeline failed: %s\");\n errorMessages.put(ERROR_TWITTER_SEARCH_FAILED,\n \"Twitter search failed.\");\n errorMessages.put(ERROR_TWITTER_INVALID_IMAGE_PATH, \"Invalid Path to Image; Update will not \" +\n \"be sent.\");\n // LegoMindstormsNXT errors\n errorMessages.put(ERROR_NXT_BLUETOOTH_NOT_SET,\n \"The Bluetooth property has not been set.\");\n errorMessages.put(ERROR_NXT_NOT_CONNECTED_TO_ROBOT,\n \"Not connected to a robot.\");\n errorMessages.put(ERROR_NXT_INVALID_RETURN_PACKAGE,\n \"Unable to receive return package. Has the robot gone to sleep?\");\n errorMessages.put(ERROR_NXT_ERROR_CODE_RECEIVED,\n \"Error code received from robot: %s.\");\n errorMessages.put(ERROR_NXT_INVALID_PROGRAM_NAME,\n \"Invalid program name.\");\n errorMessages.put(ERROR_NXT_INVALID_FILE_NAME,\n \"Invalid file name.\");\n errorMessages.put(ERROR_NXT_INVALID_MOTOR_PORT,\n \"The NXT does not have a motor port labeled %s.\");\n errorMessages.put(ERROR_NXT_INVALID_SENSOR_PORT,\n \"The NXT does not have a sensor port labeled %s.\");\n errorMessages.put(ERROR_NXT_INVALID_MAILBOX,\n \"The NXT does not have a mailbox number %s.\");\n errorMessages.put(ERROR_NXT_MESSAGE_TOO_LONG,\n \"The NXT only accepts messages up to 58 characters.\");\n errorMessages.put(ERROR_NXT_DATA_TOO_LARGE,\n \"The data is too large; it must be 16 bytes or less.\");\n errorMessages.put(ERROR_NXT_COULD_NOT_DECODE_ELEMENT,\n \"Could not decode element %s as an integer.\");\n errorMessages.put(ERROR_NXT_COULD_NOT_FIT_ELEMENT_IN_BYTE,\n \"Could not fit element %s into 1 byte.\");\n errorMessages.put(ERROR_NXT_INVALID_SOURCE_ARGUMENT,\n \"Invalid source argument.\");\n errorMessages.put(ERROR_NXT_INVALID_DESTINATION_ARGUMENT,\n \"Invalid destination argument.\");\n errorMessages.put(ERROR_NXT_UNABLE_TO_DOWNLOAD_FILE,\n \"Unable to download file to robot: %s\");\n errorMessages.put(ERROR_NXT_CANNOT_DETECT_COLOR,\n \"Cannot detect color when the DetectColor property is set to False.\");\n errorMessages.put(ERROR_NXT_CANNOT_DETECT_LIGHT,\n \"Cannot detect light level when the DetectColor property is set to True.\");\n errorMessages.put(ERROR_NXT_INVALID_GENERATE_COLOR,\n \"The GenerateColor property is limited to None, Red, Green, or Blue.\");\n // Bluetooth errors\n errorMessages.put(ERROR_BLUETOOTH_NOT_AVAILABLE,\n \"Bluetooth is not available.\");\n errorMessages.put(ERROR_BLUETOOTH_NOT_ENABLED,\n \"Bluetooth is not available.\");\n errorMessages.put(ERROR_BLUETOOTH_INVALID_ADDRESS,\n \"The specified address is not a valid Bluetooth MAC address.\");\n errorMessages.put(ERROR_BLUETOOTH_NOT_PAIRED_DEVICE,\n \"The specified address is not a paired Bluetooth device.\");\n errorMessages.put(ERROR_BLUETOOTH_NOT_REQUIRED_CLASS_OF_DEVICE,\n \"The specified address is not the required class of device.\");\n errorMessages.put(ERROR_BLUETOOTH_INVALID_UUID,\n \"The UUID \\\"%s\\\" is not formatted correctly.\");\n errorMessages.put(ERROR_BLUETOOTH_UNABLE_TO_CONNECT,\n \"Unable to connect. Is the device turned on?\");\n errorMessages.put(ERROR_BLUETOOTH_UNABLE_TO_LISTEN,\n \"Unable to listen for a connection from a bluetooth device.\");\n errorMessages.put(ERROR_BLUETOOTH_UNABLE_TO_ACCEPT,\n \"Unable to accept a connection from a bluetooth device.\");\n errorMessages.put(ERROR_BLUETOOTH_COULD_NOT_DECODE,\n \"Could not decode \\\"%s\\\" as an integer.\");\n errorMessages.put(ERROR_BLUETOOTH_COULD_NOT_FIT_NUMBER_IN_BYTE,\n \"Could not fit \\\"%s\\\" into 1 byte.\");\n errorMessages.put(ERROR_BLUETOOTH_COULD_NOT_FIT_NUMBER_IN_BYTES,\n \"Could not fit \\\"%s\\\" into %s bytes.\");\n errorMessages.put(ERROR_BLUETOOTH_COULD_NOT_DECODE_ELEMENT,\n \"Could not decode element %s as an integer.\");\n errorMessages.put(ERROR_BLUETOOTH_COULD_NOT_FIT_ELEMENT_IN_BYTE,\n \"Could not fit element %s into 1 byte.\");\n errorMessages.put(ERROR_BLUETOOTH_NOT_CONNECTED_TO_DEVICE,\n \"Not connected to a Bluetooth device.\");\n errorMessages.put(ERROR_BLUETOOTH_UNABLE_TO_WRITE,\n \"Unable to write: %s\");\n errorMessages.put(ERROR_BLUETOOTH_UNABLE_TO_READ,\n \"Unable to read: %s\");\n errorMessages.put(ERROR_BLUETOOTH_END_OF_STREAM,\n \"End of stream has been reached.\");\n errorMessages.put(ERROR_BLUETOOTH_UNSUPPORTED_ENCODING,\n \"The encoding %s is not supported.\");\n // ActivityStarter errors\n errorMessages.put(ERROR_ACTIVITY_STARTER_NO_CORRESPONDING_ACTIVITY,\n \"No corresponding activity was found.\");\n // Media errors\n errorMessages.put(ERROR_UNABLE_TO_LOAD_MEDIA,\n \"Unable to load %s.\");\n errorMessages.put(ERROR_UNABLE_TO_PREPARE_MEDIA,\n \"Unable to prepare %s.\");\n errorMessages.put(ERROR_UNABLE_TO_PLAY_MEDIA,\n \"Unable to play %s.\");\n errorMessages.put(ERROR_MEDIA_EXTERNAL_STORAGE_READONLY,\n \"External storage is available but read-only.\");\n errorMessages.put(ERROR_MEDIA_EXTERNAL_STORAGE_NOT_AVAILABLE,\n \"External storage is not available.\");\n errorMessages.put(ERROR_MEDIA_IMAGE_FILE_FORMAT,\n \"Image file name must end in \\\".jpg\\\", \\\".jpeg\\\", or \\\".png\\\".\");\n errorMessages.put(ERROR_MEDIA_CANNOT_OPEN,\n \"Cannot open file %s.\");\n errorMessages.put(ERROR_MEDIA_FILE_ERROR, \"Got file error: %s.\");\n errorMessages.put(ERROR_UNABLE_TO_FOCUS_MEDIA,\n \"Unable to grant exclusive lock of audio output stream to %s.\");\n errorMessages.put(ERROR_SOUND_NOT_READY, \"The sound is not ready to play: %s.\");\n errorMessages.put(ERROR_OUT_OF_MEMORY_LOADING_MEDIA, \"Not Enough Memory to load: %s.\");\n // SoundRecorder errors\n errorMessages.put(ERROR_SOUND_RECORDER, \"An unexpected error occurred while recording sound.\");\n errorMessages.put(ERROR_SOUND_RECORDER_CANNOT_CREATE, \"Cannot start recording: %s\");\n // Form errors\n errorMessages.put(ERROR_INVALID_SCREEN_ORIENTATION,\n \"The specified screen orientation is not valid: %s\");\n errorMessages.put(ERROR_SCREEN_NOT_FOUND, \"Screen not found: %s\");\n errorMessages.put(ERROR_SCREEN_BAD_VALUE_RECEIVED,\n \"Bad value received from other screen: %s\");\n errorMessages.put(ERROR_SCREEN_BAD_VALUE_FOR_SENDING,\n \"Bad value for sending to other screen: %s\");\n errorMessages.put(ERROR_SCREEN_INVALID_ANIMATION,\n \"Bad value for screen open/close animation: %s\");\n errorMessages.put(ERROR_NO_FOCUSABLE_VIEW_FOUND,\n \"No Focusable View Found\");\n // Canvas errors\n errorMessages.put(ERROR_CANVAS_BITMAP_ERROR, \"Error getting Canvas contents to save\");\n errorMessages.put(ERROR_CANVAS_WIDTH_ERROR, \"Canvas width cannot be set to non-positive number\");\n errorMessages.put(ERROR_CANVAS_HEIGHT_ERROR, \"Canvas height cannot be set to non-positive number\");\n // Web errors\n errorMessages.put(ERROR_WEB_UNABLE_TO_GET,\n \"Unable to get a response with the specified URL: %s\");\n errorMessages.put(ERROR_WEB_UNSUPPORTED_ENCODING,\n \"The encoding %s is not supported.\");\n errorMessages.put(ERROR_WEB_UNABLE_TO_POST_OR_PUT,\n \"Unable to post or put the text \\\"%s\\\" with the specified URL: %s\");\n errorMessages.put(ERROR_WEB_UNABLE_TO_POST_OR_PUT_FILE,\n \"Unable to post or put the file \\\"%s\\\" with the specified URL %s.\");\n errorMessages.put(ERROR_WEB_JSON_TEXT_DECODE_FAILED,\n \"Unable to decode the JSON text: %s\");\n errorMessages.put(ERROR_WEB_HTML_TEXT_DECODE_FAILED,\n \"Unable to decode the HTML text: %s\");\n errorMessages.put(ERROR_WEB_XML_TEXT_DECODE_FAILED,\n \"Unable to decode the XML text: %s\");\n errorMessages.put(ERROR_WEB_MALFORMED_URL,\n \"The specified URL is not valid: %s\");\n errorMessages.put(ERROR_WEB_REQUEST_HEADER_NOT_LIST,\n \"The specified request headers are not valid: element %s is not a list\");\n errorMessages.put(ERROR_WEB_REQUEST_HEADER_NOT_TWO_ELEMENTS,\n \"The specified request headers are not valid: element %s does not contain two elements\");\n errorMessages.put(ERROR_WEB_BUILD_REQUEST_DATA_NOT_LIST,\n \"Unable to build request data: element %s is not a list\");\n errorMessages.put(ERROR_WEB_BUILD_REQUEST_DATA_NOT_TWO_ELEMENTS,\n \"Unable to build request data: element %s does not contain two elements\");\n errorMessages.put(ERROR_WEB_UNABLE_TO_DELETE,\n \"Unable to delete a resource with the specified URL: %s\");\n // Contact picker (and PhoneNumberPicker) errors\n errorMessages.put(ERROR_PHONE_UNSUPPORTED_CONTACT_PICKER,\n \"The software used in this app cannot extract contacts from this type of phone.\");\n errorMessages.put(ERROR_PHONE_UNSUPPORTED_SEARCH_IN_CONTACT_PICKING,\n \"To pick contacts, pick them directly, without using search.\");\n \n // Camcorder errors\n errorMessages.put(ERROR_CAMCORDER_NO_CLIP_RETURNED,\n \t\"The camcorder did not return a clip.\");\n\n // VideoPlayer errors\n errorMessages.put(ERROR_VIDEOPLAYER_FULLSCREEN_UNAVAILBLE,\n \"Cannot start fullscreen mode.\");\n errorMessages.put(ERROR_VIDEOPLAYER_FULLSCREEN_CANT_EXIT,\n \"Cannot exit fullscreen mode.\");\n errorMessages.put(ERROR_VIDEOPLAYER_FULLSCREEN_UNSUPPORTED,\n \"Fullscreen mode not supported on this version of Android.\");\n // Arrangement errors\n errorMessages.put(ERROR_BAD_VALUE_FOR_HORIZONTAL_ALIGNMENT,\n \"The value -- %s -- provided for HorizontalAlignment was bad. The only legal values \" +\n \"are 1, 2, or 3.\");\n errorMessages.put(ERROR_BAD_VALUE_FOR_VERTICAL_ALIGNMENT,\n \"The value -- %s -- provided for VerticalAlignment was bad. The only legal values \" +\n \"are 1, 2, or 3.\");\n errorMessages.put(ERROR_NO_SCANNER_FOUND,\n \"Your device does not have a scanning application installed.\");\n errorMessages.put(ERROR_CANNOT_SAVE_IMAGE,\n \"Unable to save image: %s\");\n errorMessages.put(ERROR_CANNOT_COPY_MEDIA,\n \"Unable to copy selected media: %s\");\n // Texting errors\n errorMessages.put(ERROR_BAD_VALUE_FOR_TEXT_RECEIVING,\n \"Text Receiving should be either 1, 2 or 3.\");\n errorMessages.put(ERROR_REPL_SECURITY_ERROR,\n \"Security Error Receiving Blocks from Browser.\");\n //AccelerometerSensor errors\n errorMessages.put(ERROR_BAD_VALUE_FOR_ACCELEROMETER_SENSITIVITY,\n \"The value -- %s -- provided for AccelerometerSensor's sensitivity was bad. \" +\n \"The only legal values are 1, 2, or 3.\");\n \n //CallLogs history errors\n errorMessages.put(ERROR_DATE_FORMAT,\n \"The date string has wrong format, please refer to the documentation of the setting method again.\");\n \n errorMessages.put(ERROR_DROPBOX_BLANK_APP_KEY_OR_SECRET, \n \"The AppKey and AppSecret properties must be set in order to authorize access \" +\n \"for Dropbox. Please obtain a App Key and App Secret specific to your app from \" +\n \"https://www.dropbox.com/developers/apps\");\n \n errorMessages.put(ERROR_DROPBOX_EXCEPTION,\n \"Dropbox error: %s\");\n \n errorMessages.put(ERROR_DROPBOX_FILESIZE, \"This file is too big to upload, at most \" +\n \"150 MB.\");\n errorMessages.put(ERROR_DROPBOX_UNLINKED , \"This app wasn't authenticated properly\");\n errorMessages.put(ERROR_DROPBOX_IO, \"Network error while uploading the file.\");\n \n errorMessages.put(ERROR_DROPBOX_PARTIALFILE, \"The operation was canceled by Dropbox\");\n \n errorMessages.put(ERROR_DROPBOX_SERVER_INSUFFICIENT_STORAGE, \"Your dropbox usage is over quota.\");\n \n errorMessages.put(ERROR_DROPBOX_FILENOTFOUND, \"The file to upload was not found.\");\n errorMessages.put(ERROR_DROPBOX_NO_TWO_RUNNING_TASKS, \"Need to stop previous scheduled task first, \" +\n \"by calling <code>StopScheduleUpload</code>.\");\n \n errorMessages.put(ERROR_GOOGLEDRIVE_IO_EXCEPTION, \"Forget to turn on your internet connection?\");\n errorMessages.put(ERROR_GOOGLEDRIVE_EXCEPTION, \"Something wrong with Google Drive\");\n errorMessages.put(ERROR_GOOGLEDRIVE_INVALID_CREDENTIALS, \"Invalid Credentials for this app\");\n errorMessages.put(ERROR_GOOGLEDRIVE_NOT_GRANT_PERMISSION, \"The authenticated user has not granted the app access to the file\");\n errorMessages.put(ERROR_GOOGLEDRIVE_APP_BLACKLIST, \"The app is blacklisted as a Google Drive app\");\n errorMessages.put(ERROR_GOOGLEDRIVE_APP_CONFIG_ERROR, \"Configuration error on app permission\");\n errorMessages.put(ERROR_GOOGLEDRIVE_NEEDLOGIN, \"Need to Authorize the app first?\");\n \n errorMessages.put(ERROR_GOOGLE_PLAY_NOT_INSTALLED, \"Google Play is not installed/available on this phone\");\n errorMessages.put(ERROR_GOOGLE_PLAY_SERVICE_UPDATE_REQUIRED, \"Google Play Service needs update to newest version\");\n errorMessages.put(ERROR_GOOGLE_MAP_NOT_INSTALLED, \"Google Map is not installed on this phone\");\n errorMessages.put(ERROR_GOOGLE_MAP_INVALID_INPUT, \"Invalid input: %s\");\n errorMessages.put(ERROR_GOOGLE_MAP_MARKER_NOT_EXIST, \"Marker with id: %s does not exist\");\n errorMessages.put(ERROR_GOOGLE_MAP_JSON_FORMAT_DECODE_FAILED,\n \"Unable to decode the JSON text: %s\");\n errorMessages.put(ERROR_GOOGLE_MAP_CIRCLE_NOT_EXIST, \"Circle with id: %s does not exist\");\n errorMessages.put(ERROR_GOOGLE_PLAY_DISABLED, \"The installed version of Google Play services \" +\n \"has been disabled on this device.\");\n errorMessages.put(ERROR_GOOGLE_PLAY_INVALID, \"The version of the Google Play services installed \" +\n \"on this device is not authentic.\");\n \n errorMessages.put(ERROR_SENSORDB_NOTACTIVE, \"Sensor: %s is not active\");\n errorMessages.put(ERROR_SENSORDB_NOTAVAILABLE, \"Sensor: %s is not available\");\n errorMessages.put(ERROR_GCM_APPSERVER_INVALID, \"Cannot connect to GCM app server\");\n \n \n //Sharing errors\n errorMessages.put(ERROR_FILE_NOT_FOUND_FOR_SHARING,\n \"The File %s could not be found on your device.\");\n //File Errors\n errorMessages.put(ERROR_CANNOT_FIND_FILE, \"The file %s could not be found\");\n errorMessages.put(ERROR_CANNOT_READ_FILE, \"The file %s could not be opened\");\n errorMessages.put(ERROR_CANNOT_CREATE_FILE, \"The file %s could not be created\");\n errorMessages.put(ERROR_CANNOT_WRITE_TO_FILE, \"Cannot write to file %s\");\n errorMessages.put(ERROR_CANNOT_DELETE_ASSET, \"Cannot delete asset file at %s\");\n errorMessages.put(ERROR_CANNOT_WRITE_ASSET, \"Cannot write asset file at %s\");\n //Yandex.Translate translate Errors\n errorMessages.put(ERROR_TRANSLATE_NO_KEY_FOUND, \"Missing API key for the Yandex.Translate \" +\n \"service.\");\n errorMessages.put(ERROR_TRANSLATE_SERVICE_NOT_AVAILABLE, \"The translation service is not \" +\n \"available; Please try again later.\");\n errorMessages.put(ERROR_TRANSLATE_JSON_RESPONSE, \"The response from the Yandex.Translate \" +\n \"service cannot be parsed; Please try again later.\");\n //TimePicker errors\n errorMessages.put(ERROR_ILLEGAL_HOUR, \"The hour must be set to a value between 0 and 23.\");\n errorMessages.put(ERROR_ILLEGAL_MINUTE, \"The minute must be set to a value between 0 and 59.\");\n //DatePicker errors\n errorMessages.put(ERROR_ILLEGAL_DATE, \"The date you entered is invalid.\");\n errorMessages.put(ERROR_WEBVIEW_SSL_ERROR, \"SSL Connection could not complete.\");\n // FusiontablesControl errors\n errorMessages.put(FUSION_TABLES_QUERY_ERROR, \"Fusion tables returned an error. The query was: %s. \" +\n \"The response was: %s\");\n // TextToSpeech errors\n errorMessages.put(ERROR_TTS_NOT_READY,\n \"TextToSpeech is not yet ready to perform this operation\");\n // AndroidViewComponent errors\n errorMessages.put(ERROR_BAD_PERCENT, \"Percent values should be between 0 and 100.\");\n // Image errors\n errorMessages.put(ERROR_IMAGE_CANNOT_ROTATE,\n \"The version of Android on this device does not support image rotation.\");\n }\n\n private ErrorMessages() {\n }\n\n public static String formatMessage(int errorNumber, Object[] messageArgs) {\n String format = errorMessages.get(errorNumber);\n return String.format(format, messageArgs);\n }\n}" ]
import com.google.android.gms.auth.GoogleAuthException; import com.google.android.gms.auth.UserRecoverableAuthException; import com.google.api.client.extensions.android.http.AndroidHttp; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.googleapis.services.GoogleKeyInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.fusiontables.Fusiontables; import com.google.api.services.fusiontables.Fusiontables.Query.Sql; import com.google.appinventor.components.annotations.DesignerComponent; import com.google.appinventor.components.annotations.DesignerProperty; import com.google.appinventor.components.annotations.PropertyCategory; import com.google.appinventor.components.annotations.SimpleEvent; import com.google.appinventor.components.annotations.SimpleFunction; import com.google.appinventor.components.annotations.SimpleObject; import com.google.appinventor.components.annotations.SimpleProperty; import com.google.appinventor.components.annotations.UsesLibraries; import com.google.appinventor.components.annotations.UsesPermissions; import com.google.appinventor.components.common.ComponentCategory; import com.google.appinventor.components.common.PropertyTypeConstants; import com.google.appinventor.components.common.YaVersion; import com.google.appinventor.components.runtime.GoogleDrive.AccessToken; import com.google.appinventor.components.runtime.util.ClientLoginHelper; import com.google.appinventor.components.runtime.util.ErrorMessages; import com.google.appinventor.components.runtime.util.IClientLoginHelper; import com.google.appinventor.components.runtime.util.MediaUtil; import com.google.appinventor.components.runtime.util.OAuth2Helper; import com.google.appinventor.components.runtime.util.SdkLevel; import android.accounts.AccountManager; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.util.Log; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.HttpConnectionParams; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.File; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList;
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_BOOLEAN, defaultValue = "False") @SimpleProperty public void UseServiceAuthentication(boolean bool) { this.isServiceAuth = bool; } /** * Property for the service account email to use when using service authentication. **/ @SimpleProperty(category = PropertyCategory.BEHAVIOR, description = "The Service Account Email Address when service account authentication " + "is in use.") public String ServiceAccountEmail() { return serviceAccountEmail; } @DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING, defaultValue = "") @SimpleProperty public void ServiceAccountEmail(String email) { this.serviceAccountEmail = email; } /** * Setter for the app developer's API key. */ @DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING, defaultValue = "") @SimpleProperty public void ApiKey(String apiKey) { this.apiKey = apiKey; } /** * Getter for the API key. * @return apiKey the apiKey */ @SimpleProperty( description = "Your Google API Key. For help, click on the question" + "mark (?) next to the FusiontablesControl component in the Palette. ", category = PropertyCategory.BEHAVIOR) public String ApiKey() { return apiKey; } @DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING, defaultValue = DEFAULT_QUERY) @SimpleProperty public void Query(String query) { this.query = query; } @SimpleProperty( description = "The query to send to the Fusion Tables API. " + "<p>For legal query formats and examples, see the " + "<a href=\"https://developers.google.com/fusiontables/docs/v1/getting_started\" target=\"_blank\">Fusion Tables API v1.0 reference manual</a>.</p> " + "<p>Note that you do not need to worry about UTF-encoding the query. " + "But you do need to make sure it follows the syntax described in the reference manual, " + "which means that things like capitalization for names of columns matters, " + "and that single quotes need to be used around column names if there are spaces in them.</p> ", category = PropertyCategory.BEHAVIOR) public String Query() { return query; } @DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_ASSET, defaultValue = "") @SimpleProperty public void KeyFile(String path) { // If it's the same as on the prior call and the prior load was successful, // do nothing. if (path.equals(keyPath)) { return; } // Remove old cached credentials if we are changing the keyPath if (cachedServiceCredentials != null) { cachedServiceCredentials.delete(); cachedServiceCredentials = null; } keyPath = (path == null) ? "" : path; } @SimpleProperty( category = PropertyCategory.BEHAVIOR, description = "Specifies the path of the private key file. " + "This key file is used to get access to the FusionTables API.") public String KeyFile() { return keyPath; } /** * Calls QueryProcessor to execute the API request asynchronously, if * the user has already authenticated with the Fusiontables service. */ @SimpleFunction(description = "Send the query to the Fusiontables server.") public void SendQuery() { // if not Authorized // ask the user to go throug the OAuth flow AccessToken accessToken = retrieveAccessToken(); if(accessToken.accountName.length() == 0){ activity.startActivityForResult(credential.newChooseAccountIntent(), REQUEST_CHOOSE_ACCOUNT); } // if authorized new QueryProcessorV1(activity).execute(query); // } //Deprecated -- Won't work after 12/2012 @Deprecated // [lyn, 2015/12/30] In AI2, now use explicit @Deprecated annotation rather than // userVisible = false to deprecate an event, method, or property. @SimpleFunction( description = "DEPRECATED. This block is deprecated as of the end of 2012. Use SendQuery.") public void DoQuery() { if (requestHelper != null) { new QueryProcessor().execute(query); } else { form.dispatchErrorOccurredEvent(this, "DoQuery",
ErrorMessages.ERROR_FUNCTIONALITY_NOT_SUPPORTED_FUSIONTABLES_CONTROL);
4
USCDataScience/AgePredictor
age-predictor-cli/src/main/java/edu/usc/irds/agepredictor/cmdline/spark/authorage/AgePredictTool.java
[ "public class CLI {\n public static final String CMD = \"bin/authorage\";\n public static final String DEFAULT_FORMAT = AuthorAgeSample.FORMAT_NAME;\n \n private static Map<String, CmdLineTool> toolLookupMap;\n \n static {\n\ttoolLookupMap = new LinkedHashMap<String, CmdLineTool>();\n \n\tList<CmdLineTool> tools = new LinkedList<CmdLineTool>();\n\ttools.add(new AgeClassifyTrainerTool());\n\ttools.add(new AgeClassifyTool());\n\ttools.add(new AgeClassifyEvaluatorTool());\n\ttools.add(new AgeClassifySparkTrainerTool());\n\ttools.add(new AgeClassifySparkEvaluatorTool());\n\ttools.add(new AgePredictTrainerTool());\n\ttools.add(new AgePredictTool());\n\ttools.add(new AgePredictEvaluatorTool());\n\t\n\tAuthorAgeSampleStreamFactory.registerFactory();\n\t\n\tfor (CmdLineTool tool : tools) {\n\t toolLookupMap.put(tool.getName(), tool);\n\t}\n\t\n\ttoolLookupMap = Collections.unmodifiableMap(toolLookupMap);\n }\n \n private static void usage() {\n\tSystem.out.println(\"Usage: \" + CMD + \" TOOL\");\n\tSystem.out.println(\"where TOOL is one of:\");\n\n\t// distance of tool name from line start\n\tint numberOfSpaces = -1;\n\tfor (String toolName : toolLookupMap.keySet()) {\n\t if (toolName.length() > numberOfSpaces) {\n\t\tnumberOfSpaces = toolName.length();\n\t }\n\t}\n\tnumberOfSpaces = numberOfSpaces + 4;\n\n\tfor (CmdLineTool tool : toolLookupMap.values()) {\n\t System.out.print(\" \" + tool.getName());\n\n\t for (int i = 0; i < Math.abs(tool.getName().length() - numberOfSpaces); i++) {\n\t\tSystem.out.print(\" \");\n\t }\n\n\t System.out.println(tool.getShortDescription());\n\t}\n }\n \n public static Set<String> getToolNames() {\n\treturn toolLookupMap.keySet();\n }\n \n public static void main(String[] args) {\n\tif (args.length == 0) {\n\t usage();\n\t System.exit(0);\n\t}\n\t\n\tString toolArguments[] = new String[args.length -1];\n\tSystem.arraycopy(args, 1, toolArguments, 0, toolArguments.length);\n\t\n\tString toolName = args[0];\n\t\n\tString formatName = DEFAULT_FORMAT;\n\tint idx = toolName.indexOf(\".\");\n\tif (-1 < idx) {\n\t formatName = toolName.substring(idx + 1);\n\t toolName = toolName.substring(0, idx);\n\t}\n\tCmdLineTool tool = toolLookupMap.get(toolName);\n\t\n\ttry {\n\t if (null == tool) {\n\t\tthrow new TerminateToolException(1, \"Tool \" + toolName + \" is not found.\");\n\t }\n\n\t if ((0 == toolArguments.length && tool.hasParams()) ||\n\t\t0 < toolArguments.length && \"help\".equals(toolArguments[0])) {\n\t\tif (tool instanceof TypedCmdLineTool) {\n\t\t System.out.println(((TypedCmdLineTool) tool).getHelp(formatName));\n\t\t} else if (tool instanceof BasicCmdLineTool) {\n\t\t System.out.println(tool.getHelp());\n\t\t}\n\n\t\tSystem.exit(0);\n\t }\n\n\t if (tool instanceof TypedCmdLineTool) {\n\t\t((TypedCmdLineTool) tool).run(formatName, toolArguments);\n\t } else if (tool instanceof BasicCmdLineTool) {\n\t\tif (-1 == idx) {\n\t\t ((BasicCmdLineTool) tool).run(toolArguments);\n\t\t} else {\n\t\t throw new TerminateToolException(1, \"Tool \" + toolName + \" does not support formats.\");\n\t\t}\n\t } else {\n\t\tthrow new TerminateToolException(1, \"Tool \" + toolName + \" is not supported.\");\n\t }\n\t}\n\tcatch (TerminateToolException e) {\n\n\t if (e.getMessage() != null) {\n\t\tSystem.err.println(e.getMessage());\n\t }\n\n\t if (e.getCause() != null) {\n\t\tSystem.err.println(e.getCause().getMessage());\n\t\te.getCause().printStackTrace(System.err);\n\t }\n\n\t System.exit(e.getCode());\n\t}\n }\n\n}", "public class AgePredictModel implements Serializable {\n private String languageCode;\n private LassoModel model;\n private String[] vocabulary;\n private AgeClassifyContextGeneratorWrapper wrapper;\n \n public AgePredictModel(String languageCode, LassoModel agePredictModel, String[] vocabulary,\n\t\t\t AgeClassifyContextGeneratorWrapper wrapper) {\n\n\tthis.languageCode = languageCode;\n\tthis.model = agePredictModel;\n\tthis.vocabulary = vocabulary;\n\tthis.wrapper = wrapper;\n }\n \n public static AgePredictModel readModel(File file) throws IOException {\n\t//deserialize from file\n\tAgePredictModel model;\n\ttry{\n\t FileInputStream fin = new FileInputStream(file);\n\t ObjectInputStream ois = new ObjectInputStream(fin);\n\t model = (AgePredictModel) ois.readObject();\n\t ois.close();\n\n\t return model;\n\n\t}catch(Exception e){\n\t e.printStackTrace();\n\t return null;\n\t}\n\t\n }\n \n public AgeClassifyContextGeneratorWrapper getContext() {\n\treturn this.wrapper;\n }\n \n public LassoModel getModel() {\n\treturn this.model;\n }\n \n public String[] getVocabulary() {\n\treturn this.vocabulary;\n }\n \n public static void writeModel(AgePredictModel model, File file) {\n\ttry {\n\t //serialize to file\n\t FileOutputStream fout = new FileOutputStream(file);\n\t ObjectOutputStream oos = new ObjectOutputStream(fout);\n\t oos.writeObject(model);\n\t oos.close();\n\t} catch (Exception e) {\n\t e.printStackTrace();\n\t}\n\t\n }\n \n}", "public class AgeClassifyME {\n protected AgeClassifyContextGenerator contextGenerator;\n \n private AgeClassifyFactory factory;\n private AgeClassifyModel model;\n \n public AgeClassifyME(AgeClassifyModel ageModel) {\n\tthis.model = ageModel;\n\tthis.factory = ageModel.getFactory();\n\n\tthis.contextGenerator = new AgeClassifyContextGenerator(\n\t this.factory.getFeatureGenerators());\n }\n \n \n public String getBestCategory(double[] outcome) {\n\treturn this.model.getMaxentModel().getBestOutcome(outcome);\n }\n \n public int getNumCategories() {\n\treturn this.model.getMaxentModel().getNumOutcomes();\n }\n \n public String getCategory(int index) {\n\treturn this.model.getMaxentModel().getOutcome(index);\n }\n \n public int getIndex(String category) {\n\treturn this.model.getMaxentModel().getIndex(category);\n }\n \n public double[] getProbabilities(String text[]) {\n\treturn this.model.getMaxentModel().eval(\n\t contextGenerator.getContext(text));\n }\n \n public double[] getProbabilities(String documentText) {\n\tTokenizer tokenizer = this.factory.getTokenizer();\n\treturn getProbabilities(tokenizer.tokenize(documentText));\n }\n \n public String predict(String documentText) {\n\tdouble probs[] = getProbabilities(documentText);\n\tString category = getBestCategory(probs);\n\t\n\treturn category;\n }\n \n public Map<String, Double> scoreMap(String documentText) {\n\tMap<String, Double> probs = new HashMap<String, Double>();\n\t\n\tdouble[] categories = getProbabilities(documentText);\n\t\n\tint numCategories = getNumCategories();\n\tfor (int i = 0; i < numCategories; i++) {\n\t String category = getCategory(i);\n\t probs.put(category, categories[getIndex(category)]);\n\t}\n\treturn probs;\n }\n \n public SortedMap<Double, Set<String>> sortedScoreMap(String documentText) {\n\tSortedMap<Double, Set<String>> sortedMap = new TreeMap<Double, Set<String>>();\n\t\n\tdouble[] categories = getProbabilities(documentText);\n\t\n\tint numCategories = getNumCategories();\n\tfor (int i = 0; i < numCategories; i++) {\n\t String category = getCategory(i);\n\t double score = categories[getIndex(category)];\n\t \n\t if (sortedMap.containsKey(score)) {\n\t\tsortedMap.get(score).add(category);\n\t } else {\n\t\tSet<String> newset = new HashSet<String>();\n\t\tnewset.add(category);\n\t\tsortedMap.put(score, newset);\n\t }\n\t}\n\treturn sortedMap;\n }\n \n \n public static AgeClassifyModel train(String languageCode,\n ObjectStream<AuthorAgeSample> samples, TrainingParameters trainParams,\n \tAgeClassifyFactory factory) throws IOException {\n\t\n\tMap<String, String> entries = new HashMap<String, String>();\n\n\tMaxentModel ageModel = null;\n\t\n\tTrainerType trainerType = AgeClassifyTrainerFactory\n\t .getTrainerType(trainParams.getSettings());\n\t\n\tObjectStream<Event> eventStream = new AgeClassifyEventStream(samples,\n\t factory.createContextGenerator());\n\t\n\tEventTrainer trainer = AgeClassifyTrainerFactory\n\t .getEventTrainer(trainParams.getSettings(), entries);\n\tageModel = trainer.train(eventStream);\n\t\n\tMap<String, String> manifestInfoEntries = new HashMap<String, String>();\n\n\treturn new AgeClassifyModel(languageCode, ageModel, manifestInfoEntries,\n\t\t\t\t factory);\n }\n \n\n}", "public class AgeClassifyModel extends BaseModel {\n private static final String COMPONENT_NAME = \"AgeClassifyME\";\n private static final String AUTHORAGE_MODEL_ENTRY_NAME = \"authorage.model\";\n \n public AgeClassifyModel(String languageCode, MaxentModel ageClassifyModel,\n\t\t\t Map<String, String> manifestInfoEntries, AgeClassifyFactory factory) {\n\tsuper(COMPONENT_NAME, languageCode, manifestInfoEntries, factory);\n\tartifactMap.put(AUTHORAGE_MODEL_ENTRY_NAME, ageClassifyModel);\n\tcheckArtifactMap();\n }\n\n\n public AgeClassifyModel(URL modelURL)\n\tthrows IOException, InvalidFormatException {\n\tsuper(COMPONENT_NAME, modelURL);\n }\n\n public AgeClassifyModel(File file) throws InvalidFormatException, IOException {\n\tsuper(COMPONENT_NAME, file);\n }\n \n public AgeClassifyFactory getFactory() {\n\treturn (AgeClassifyFactory) this.toolFactory;\n }\n \n public MaxentModel getMaxentModel() {\n\treturn (MaxentModel) artifactMap.get(AUTHORAGE_MODEL_ENTRY_NAME);\n }\n \n}", "public interface FeatureGenerator {\n\n /**\n * Extract features from given text fragments\n *\n * @param text the text fragments to extract features from\n * @param extraInformation optional extra information to be used by the feature generator\n * @return a collection of features\n */\n Collection<String> extractFeatures(String[] text);\n}" ]
import java.io.File; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.function.VoidFunction; import org.apache.spark.ml.feature.CountVectorizerModel; import org.apache.spark.ml.feature.Normalizer; import org.apache.spark.ml.linalg.SparseVector; import org.apache.spark.mllib.linalg.Vectors; import org.apache.spark.mllib.regression.LassoModel; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.RowFactory; import org.apache.spark.sql.SparkSession; import org.apache.spark.sql.types.ArrayType; import org.apache.spark.sql.types.DataTypes; import org.apache.spark.sql.types.Metadata; import org.apache.spark.sql.types.StructField; import org.apache.spark.sql.types.StructType; import edu.usc.irds.agepredictor.cmdline.CLI; import edu.usc.irds.agepredictor.spark.authorage.AgePredictModel; import opennlp.tools.authorage.AgeClassifyME; import opennlp.tools.authorage.AgeClassifyModel; import opennlp.tools.cmdline.BasicCmdLineTool; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.SystemInputStreamFactory; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.ParagraphStream; import opennlp.tools.util.PlainTextByLineStream; import opennlp.tools.util.featuregen.FeatureGenerator;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.usc.irds.agepredictor.cmdline.spark.authorage; /** * TODO: Documentation */ public class AgePredictTool extends BasicCmdLineTool implements Serializable { @Override public String getShortDescription() { return "age predictor"; } @Override public String getHelp() {
return "Usage: " + CLI.CMD + " " + getName() + " [MaxEntModel] RegressionModel Documents";
0
b0noI/AIF2
src/test/integration/java/io/aif/language/sentence/SimpleSentenceSplitterCharactersExtractorQualityTest.java
[ "public abstract class FileHelper {\n\n public static String readAllText(final InputStream inputStream) throws IOException {\n try (final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {\n\n final StringBuffer buff = new StringBuffer();\n\n String line = null;\n\n while ((line = reader.readLine()) != null) {\n buff.append(line + System.lineSeparator());\n }\n\n return buff.toString();\n } catch (NullPointerException e) {\n throw e;\n }\n }\n\n}", "@FunctionalInterface\npublic interface ISplitter<T1, T2> extends Function<T1, List<T2>> {\n\n public List<T2> split(final T1 target);\n\n @Override\n public default List<T2> apply(final T1 t1) {\n return split(t1);\n }\n}", "public interface ISeparatorExtractor extends IExtractor<List<String>, List<Character>> {\n\n public static enum Type {\n PREDEFINED(new PredefinedSeparatorExtractor()),\n PROBABILITY(new StatSeparatorExtractor()),\n NON_ALPHABETIC_CHARACTERS_EXTRACTOR(new NonAlphabeticCharactersExtractor());\n\n private final ISeparatorExtractor instance;\n\n private Type(final ISeparatorExtractor instance) {\n this.instance = instance;\n }\n\n public static ISeparatorExtractor getDefault() {\n final ISettings settings = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class);\n return settings.useIsAlphabeticMethod() ?\n Type.NON_ALPHABETIC_CHARACTERS_EXTRACTOR.getInstance() :\n Type.PROBABILITY.getInstance();\n }\n\n public ISeparatorExtractor getInstance() {\n return instance;\n }\n\n }\n\n\n}", "public interface ISeparatorsGrouper {\n\n public List<Set<Character>> group(final List<String> tokens, final List<Character> splitters);\n\n public enum Type {\n\n PREDEFINED(new PredefinedGrouper()),\n PROBABILITY(new StatGrouper());\n\n private final ISeparatorsGrouper instance;\n\n Type(ISeparatorsGrouper instance) {\n this.instance = instance;\n }\n\n public ISeparatorsGrouper getInstance() {\n return instance;\n }\n\n }\n\n}", "public class Tokenizer implements ISplitter<String, String> {\n\n private static final Logger logger = Logger.getLogger(Tokenizer.class);\n\n private final IRegexpCooker regexpCooker;\n\n private final ITokenSeparatorExtractor tokenSeparatorExtractor;\n\n public Tokenizer(final ITokenSeparatorExtractor tokenSeparatorExtractor) {\n this(tokenSeparatorExtractor, new RegexpCooker());\n }\n\n public Tokenizer() {\n this(ITokenSeparatorExtractor.Type.PREDEFINED.getInstance(), new RegexpCooker());\n }\n\n @VisibleForTesting\n Tokenizer(final ITokenSeparatorExtractor tokenSeparatorExtractor,\n final IRegexpCooker regexpCooker) {\n this.tokenSeparatorExtractor = tokenSeparatorExtractor;\n this.regexpCooker = regexpCooker;\n }\n\n @VisibleForTesting\n static List<String> filterIncorrectTokens(final List<String> tokens) {\n return tokens.stream()\n .filter(token -> !token.isEmpty())\n .collect(Collectors.toList());\n }\n\n @Override\n public List<String> split(final String txt) {\n logger.debug(String.format(\"Starting splitting text with size %d\", txt.length()));\n final Optional<List<Character>> optionalSeparators = tokenSeparatorExtractor.extract(txt);\n\n if (!optionalSeparators.isPresent() || optionalSeparators.get().isEmpty()) {\n logger.error(\"Failed to extract token splitter character, returning text\");\n return new ArrayList<String>(1) {{\n add(txt);\n }};\n }\n\n final List<Character> separators = optionalSeparators.get();\n logger.debug(String.format(\"Token separators: %s\", Arrays.toString(separators.toArray())));\n final String regExp = regexpCooker.prepareRegexp(separators);\n logger.debug(String.format(\"Regexp for toke splitting: %s\", regExp));\n final List<String> tokens = Arrays.asList(txt.split(regExp));\n logger.debug(String.format(\"Tokens found (before filtering): %d\", tokens.size()));\n return Tokenizer.filterIncorrectTokens(tokens);\n }\n\n}" ]
import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import io.aif.common.FileHelper; import io.aif.language.common.ISplitter; import io.aif.language.sentence.separators.classificators.ISeparatorGroupsClassifier; import io.aif.language.sentence.separators.extractors.ISeparatorExtractor; import io.aif.language.sentence.separators.groupers.ISeparatorsGrouper; import io.aif.language.token.Tokenizer; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue;
{"ITA/Fallaci Oriana - La rabbia e l'orgoglio (2001).txt"}, {"ITA/Fallaci Oriana - Lettera a un bambino mai nato (1975).txt"}, {"ITA/Fallaci Oriana - Niente E Cos Sia (1969).txt"}, {"ITA/Fallaci Oriana - Oriana Fallaci intervista Oriana Fallaci (2004).txt"}, {"ITA/Fallaci Oriana - Penelope Alla Guerra (1962).txt"}, {"ITA/Fallaci Oriana - Risponde (Social forum a Firenze) (2002).txt"}, {"ITA/Fallaci Oriana - Un cappello pieno di ciliege (2005).txt"}, {"ITA/Fallaci Oriana - Un uomo (1979).txt"}, {"ITA/Fallaci Oriana - Wake Up Occidente Sveglia (2002).txt"}, //POL {"POL/Chmielewska Joanna - Autobiografia t 3.txt"}, {"POL/Chmielewska Joanna - Autobiografia t 4.txt"}, {"POL/Chmielewska Joanna - Autobiografia t 5.txt"}, {"POL/Chmielewska Joanna - Depozyt.txt"}, {"POL/Chmielewska Joanna - Drugi watek.txt"}, {"POL/Chmielewska Joanna - Pafnucy.txt"}, {"POL/Chmielewska Joanna - Szajka bez konca.txt"}, {"POL/Chmielewska Joanna - W.txt"}, {"POL/Chmielewska Joanna D.txt"}, {"POL/Chmielewska Joanna Dwie glowy i jedna noga.txt"}, {"POL/Chmielewska Joanna Dwie trzecie sukcesu.txt"}, {"POL/Chmielewska Joanna Klin.txt"}, {"POL/Chmielewska Joanna Krokodyl z Kraju Karoliny.txt"}, {"POL/Chmielewska Joanna L.txt"}, {"POL/Chmielewska Joanna Zbieg okolicznosci.txt"}, {"POL/Chmielewska_Joanna_-_(Nie)boszczyk_maz.txt"}, {"POL/Chmielewska_Joanna_-_Babski_motyw.txt"}, {"POL/Chmielewska_Joanna_-_Bulgarski_bloczek.txt"}, {"POL/Chmielewska_Joanna_-_Pech.txt"}, {"POL/Chmielewska_Joanna_-_Trudny_Trup.txt"}, {"POL/J. Chmielewska Wielkie zaslugi.txt"}, {"POL/J.Chmielewska 1 Wielki diament.txt"}, {"POL/J.Chmielewska 2 Wielki diament.txt"}, {"POL/J.Chmielewska Skarby.txt"}, {"POL/J.Chmielewska Slepe szczescie.txt"}, {"POL/JOANNA CHMIELEWSKA.txt"}, {"POL/Joanna Chmielewska - Harpie.txt"}, {"POL/Joanna Chmielewska Kocie worki.txt"}, {"POL/Joanna Chmielewska Lesio.txt"}, {"POL/Joanna Chmielewska Wszyscy jestesmy podejrzani.txt"}, {"POL/Krowa niebianska.txt"}, {"POL/Nawiedzony dom.txt"}, {"POL/Przekleta Bariera.txt"}, {"POL/Skradziona kolekcja.txt"}, {"POL/Wegiel Marta Jak wytrzymac z Joanna Chmielewska.txt"}, {"POL/Wszystko Czerwone.txt"}, {"POL/Zbieg okolicznosci.txt"}, {"POL/Złota mucha.txt"}, {"POL/BOCZNE DROGI.txt"}, {"POL/Cale zdanie nieboszczyka.txt"}, {"POL/Chmielewska J. Jak wytrzymac ze wspolczesna kobieta.txt"}, {"POL/Chmielewska Joanna - Autobiografia t 1.txt"}, {"POL/Chmielewska Joanna - Autobiografia t 2.txt"}, //RUS {"RU/17354.txt"}, {"RU/18957.txt"}, {"RU/19530.txt"}, {"RU/27519.txt"}, {"RU/46427.txt"}, {"RU/46468.txt"}, {"RU/46606.txt"}, {"RU/46699.txt"}, {"RU/46777.txt"}, {"RU/47729.txt"}, {"RU/49723.txt"}, {"RU/70684.txt"}, {"RU/79813.txt"}, {"RU/9602.txt"}, }; } public static void main(String[] args) throws Exception { final Map<String, List<String>> errors = executeTest(); System.out.println( errors.keySet().stream().mapToDouble(key -> (double) errors.get(key).size()).sum() / (double) engBooksProvider().length * 5.); } public static Map<String, List<String>> executeTest() throws Exception { // input arguments String inputText; final Map<String, List<String>> totalErrors = new HashMap<>(); for (String[] path : engBooksProvider()) { try (InputStream modelResource = SimpleSentenceSplitterCharactersExtractorQualityTest.class .getResourceAsStream(String.format("/texts/%s", path))) { inputText = FileHelper.readAllText(modelResource); } List<String> errors = qualityTest(inputText); if (errors.size() > 0) { totalErrors.put(path[0], errors); } } final Map<String, Integer> errorsCounts = new HashMap<>(); totalErrors.entrySet().forEach(element -> { element.getValue().forEach(error -> { final int errorCount = errorsCounts.getOrDefault(error, 0); errorsCounts.put(error, errorCount + 1); }); }); return totalErrors; } private static List<String> qualityTest(final String inputText) { final Tokenizer tokenizer = new Tokenizer(); final List<String> inputTokens = tokenizer.split(inputText); // expected results final List<Character> expectedResult = Arrays.asList('.', '(', ')', ':', '\"', '#', ';', '‘', '“', ',', '\'', '?', '!'); final List<Character> mandatoryCharacters = Arrays.asList('.', ','); final List<Character> mandatoryGroup1Characters = Collections.singletonList('.'); final List<Character> mandatoryGroup2Characters = Collections.singletonList(','); // creating test instance final ISeparatorExtractor testInstance = ISeparatorExtractor.Type.PROBABILITY.getInstance();
final ISeparatorsGrouper separatorsGrouper = ISeparatorsGrouper.Type.PROBABILITY.getInstance();
3
WANdisco/s3hdfs
src/main/java/com/wandisco/s3hdfs/command/HeadCommand.java
[ "public class S3HdfsPath {\n private final String rootDir;\n private final String userName;\n private final String bucketName;\n private final String objectName;\n private final String partNumber;\n\n private String version;\n\n public S3HdfsPath() throws UnsupportedEncodingException {\n this(null, null, null, null, null, null);\n }\n\n /**\n * Constructs an S3HdfsPath using known information after entering\n * the S3HdfsFilter. This path represents a /bucket/object in S3 and\n * a /root/user/bucket/object/version/file in HDFS.\n *\n * @param rootDir the s3Hdfs root dir (req)\n * @param userName the username behind the current request (req)\n * @param bucketName the s3 bucketname (opt)\n * @param objectName the s3 objectname (opt)\n * @param version the version requested (opt)\n * @param partNumber the partNumber (opt)\n */\n public S3HdfsPath(final String rootDir, final String userName,\n final String bucketName, final String objectName,\n final String version, final String partNumber)\n throws UnsupportedEncodingException {\n this.rootDir = rootDir;\n this.userName = userName;\n this.bucketName = bucketName;\n this.objectName = (objectName == null) ? null :\n URLDecoder.decode(objectName, \"UTF-8\");\n this.version = version;\n this.partNumber = partNumber;\n }\n\n /**\n * Returns the /bucket/object path, or the /bucket/ path,\n * if no object was given.\n * Returns empty String if neither were given.\n *\n * @return the s3 path\n */\n public String getS3Path() {\n String retVal = \"\";\n if (bucketName != null)\n retVal = \"/\" + bucketName + \"/\";\n if (objectName != null && !retVal.isEmpty())\n retVal = retVal + objectName;\n return retVal;\n }\n\n /**\n * Returns the /root/user/bucket/object/version/file path,\n * or the /root/user/bucket/ path if no object was given.\n * <p/>\n * Returns /root/user/ if no bucket, object and version were given.\n *\n * @return the full hdfs .obj path\n */\n public String getFullHdfsObjPath() {\n String retVal;\n if (rootDir.charAt(0) == '/')\n retVal = rootDir + \"/\" + userName + \"/\";\n else\n retVal = \"/\" + rootDir + \"/\" + userName + \"/\";\n\n if (!bucketName.isEmpty()) {\n retVal = retVal + bucketName + \"/\";\n if (!objectName.isEmpty() && !version.isEmpty())\n retVal = retVal + objectName + \"/\" + version + \"/\" + OBJECT_FILE_NAME;\n }\n return retVal;\n }\n\n /**\n * Returns the /root/user/bucket/object/version/meta path,\n * or the /root/user/bucket/ path if no object was given.\n * <p/>\n * Returns /root/user/ if no bucket, object and version were given.\n *\n * @return the full hdfs .meta path\n */\n public String getFullHdfsMetaPath() {\n String retVal;\n if (rootDir.charAt(0) == '/')\n retVal = rootDir + \"/\" + userName + \"/\";\n else\n retVal = \"/\" + rootDir + \"/\" + userName + \"/\";\n\n if (!bucketName.isEmpty()) {\n retVal = retVal + bucketName + \"/\";\n if (!objectName.isEmpty() && !version.isEmpty())\n retVal = retVal + objectName + \"/\" + version + \"/\" + META_FILE_NAME;\n }\n return retVal;\n }\n\n /**\n * Returns the /root/user/bucket/object/version/vers path,\n * or the /root/user/bucket/ path if no object was given.\n * <p/>\n * Returns /root/user/ if no bucket, object and version were given.\n *\n * @return the full hdfs .obj path\n */\n public String getFullHdfsVersPath() {\n String retVal;\n if (rootDir.charAt(0) == '/')\n retVal = rootDir + \"/\" + userName + \"/\";\n else\n retVal = \"/\" + rootDir + \"/\" + userName + \"/\";\n\n if (!bucketName.isEmpty()) {\n retVal = retVal + bucketName + \"/\";\n if (!objectName.isEmpty() && !version.isEmpty())\n retVal = retVal + objectName + \"/\" + version + \"/\" + VERSION_FILE_NAME;\n }\n return retVal;\n }\n\n /**\n * Returns the /root/user/bucket/object/version/file path,\n * or the /root/user/bucket/ path if no object was given.\n * <p/>\n * Returns /root/user/ if no bucket, object and version were given.\n *\n * @return the full hdfs .obj path\n */\n public String getFullHdfsDeleteMarkerPath() {\n String retVal;\n if (rootDir.charAt(0) == '/')\n retVal = rootDir + \"/\" + userName + \"/\";\n else\n retVal = \"/\" + rootDir + \"/\" + userName + \"/\";\n\n if (!bucketName.isEmpty()) {\n retVal = retVal + bucketName + \"/\";\n if (!objectName.isEmpty() && !version.isEmpty())\n retVal = retVal + objectName + \"/\" + version + \"/\" + DELETE_MARKER_FILE_NAME;\n }\n return retVal;\n }\n\n /**\n * Returns the /root/user/bucket path,\n * or the /root/user/ path if no bucket was given.\n *\n * @return the hdfs bucket dir path\n */\n public String getFullHdfsBucketMetaPath() {\n String retVal;\n if (rootDir.charAt(0) == '/')\n retVal = rootDir + \"/\" + userName + \"/\";\n else\n retVal = \"/\" + rootDir + \"/\" + userName + \"/\";\n\n if (!bucketName.isEmpty()) {\n retVal = retVal + bucketName + \"/\" + BUCKET_META_FILE_NAME;\n }\n return retVal;\n }\n\n /**\n * Returns the /root/user/bucket/object/version/upload path,\n * or the /root/user/bucket/ path if no object was given.\n * <p/>\n * Returns /root/user/ if no bucket, object and version were given.\n *\n * @return the hdfs upload dir path\n */\n public String getHdfsRootUploadPath() {\n String retVal;\n if (rootDir.charAt(0) == '/')\n retVal = rootDir + \"/\" + userName + \"/\";\n else\n retVal = \"/\" + rootDir + \"/\" + userName + \"/\";\n\n if (!bucketName.isEmpty()) {\n retVal = retVal + bucketName + \"/\";\n if (!objectName.isEmpty() && !version.isEmpty())\n retVal = retVal + objectName + \"/\" + version + \"/\" + UPLOAD_DIR_NAME + \"/\";\n }\n return retVal;\n }\n\n /**\n * Returns the /root/user/bucket/object/version path,\n * or the /root/user/bucket/ path if no object was given.\n * <p/>\n * Returns /root/user/ if no bucket, object and version were given.\n *\n * @return the hdfs version dir path\n */\n public String getHdfsRootVersionPath() {\n String retVal;\n if (rootDir.charAt(0) == '/')\n retVal = rootDir + \"/\" + userName + \"/\";\n else\n retVal = \"/\" + rootDir + \"/\" + userName + \"/\";\n\n if (!bucketName.isEmpty()) {\n retVal = retVal + bucketName + \"/\";\n if (!objectName.isEmpty() && !version.isEmpty())\n retVal = retVal + objectName + \"/\" + version + \"/\";\n }\n return retVal;\n }\n\n /**\n * Returns the /root/user/bucket/object/version path,\n * or the /root/user/bucket/ path if no object was given.\n * <p/>\n * Returns /root/user/ if no bucket, object and version were given.\n *\n * @return the hdfs version dir path\n */\n public String getHdfsDefaultVersionPath() {\n String retVal;\n if (rootDir.charAt(0) == '/')\n retVal = rootDir + \"/\" + userName + \"/\";\n else\n retVal = \"/\" + rootDir + \"/\" + userName + \"/\";\n\n if (!bucketName.isEmpty()) {\n retVal = retVal + bucketName + \"/\";\n if (!objectName.isEmpty() && !version.isEmpty())\n retVal = retVal + objectName + \"/\" + DEFAULT_VERSION + \"/\";\n }\n return retVal;\n }\n\n /**\n * Returns the /root/user/bucket/object path,\n * or the /root/user/bucket/ path if no object was given.\n * <p/>\n * Returns /root/user/ if no bucket, object and version were given.\n *\n * @return the hdfs object dir path\n */\n public String getHdfsRootObjectPath() {\n String retVal;\n if (rootDir.charAt(0) == '/')\n retVal = rootDir + \"/\" + userName + \"/\";\n else\n retVal = \"/\" + rootDir + \"/\" + userName + \"/\";\n\n if (!bucketName.isEmpty()) {\n retVal = retVal + bucketName + \"/\";\n if (!objectName.isEmpty() && !version.isEmpty())\n retVal = retVal + objectName;\n }\n return retVal;\n }\n\n /**\n * Returns the /root/user/bucket path,\n * or the /root/user/ path if no bucket was given.\n *\n * @return the hdfs bucket dir path\n */\n public String getHdfsRootBucketPath() {\n String retVal;\n if (rootDir.charAt(0) == '/')\n retVal = rootDir + \"/\" + userName + \"/\";\n else\n retVal = \"/\" + rootDir + \"/\" + userName + \"/\";\n\n if (!bucketName.isEmpty()) {\n retVal = retVal + bucketName + \"/\";\n }\n return retVal;\n }\n\n /**\n * Returns the /root/user/ path.\n *\n * @return the hdfs user dir path\n */\n public String getHdfsRootUserPath() {\n String retVal;\n if (rootDir.charAt(0) == '/')\n retVal = rootDir + \"/\" + userName + \"/\";\n else\n retVal = \"/\" + rootDir + \"/\" + userName + \"/\";\n return retVal;\n }\n\n /**\n * Returns the /root/user/bucket/object/version/upload/part path\n *\n * @return the full hdfs .part path\n */\n public String getFullHdfsUploadPartPath() {\n String retVal;\n if (rootDir.charAt(0) == '/')\n retVal = rootDir + \"/\" + userName + \"/\";\n else\n retVal = \"/\" + rootDir + \"/\" + userName + \"/\";\n\n if (!bucketName.isEmpty()) {\n retVal = retVal + bucketName + \"/\";\n if (!objectName.isEmpty() && !version.isEmpty()) {\n retVal = retVal + objectName + \"/\" + version + \"/\" + UPLOAD_DIR_NAME + \"/\" +\n partNumber + PART_FILE_NAME;\n }\n }\n return retVal;\n }\n\n public String getBucketName() {\n return bucketName;\n }\n\n public String getObjectName() {\n return objectName;\n }\n\n public String getUserName() {\n return userName;\n }\n\n public String getVersion() {\n return version;\n }\n\n public void setVersion(String version) {\n this.version = version;\n }\n\n public String getPartNumber() {\n return partNumber;\n }\n\n public String toString() {\n return \"[bucket=\" + getBucketName() + \",object=\" + getObjectName() + \",user=\" +\n getUserName() + \",version=\" + getVersion() + \",part=\" + getPartNumber() + \"]\";\n }\n\n}", "public class MetadataFileRedirect extends Redirect {\n\n public MetadataFileRedirect(HttpServletRequest request) {\n super(request, null, null);\n LOG.debug(\"Created \" + getClass().getSimpleName() + \".\");\n }\n\n /**\n * Sends a PUT command to create an empty file inside of HDFS.\n * It uses the URL from the original request to do so.\n * It will then consume the 307 response and write to the DataNode as well.\n * The data is \"small\" in hopes that this will be relatively quick.\n *\n * @throws IOException\n * @throws ServletException\n */\n public void sendCreate(String nnHostAddress, String userName)\n throws IOException, ServletException {\n // Set up HttpPut\n String[] nnHost = nnHostAddress.split(\":\");\n String metapath = replaceUri(request.getRequestURI(), OBJECT_FILE_NAME,\n META_FILE_NAME);\n\n PutMethod httpPut =\n (PutMethod) getHttpMethod(request.getScheme(), nnHost[0],\n Integer.decode(nnHost[1]), \"CREATE&overwrite=true\", userName,\n metapath, PUT);\n Enumeration headers = request.getHeaderNames();\n Properties metadata = new Properties();\n\n // Set custom metadata headers\n while (headers.hasMoreElements()) {\n String key = (String) headers.nextElement();\n if (key.startsWith(\"x-amz-meta-\")) {\n String value = request.getHeader(key);\n metadata.setProperty(key, value);\n }\n }\n // Include lastModified header\n SimpleDateFormat rc228 = new SimpleDateFormat(\"EEE, dd MMM yyyy HH:mm:ss Z\");\n String modTime = rc228.format(Calendar.getInstance().getTime());\n metadata.setProperty(\"Last-Modified\", modTime);\n\n // Store metadata headers into serialized HashMap in HttpPut entity.\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n metadata.store(baos, null);\n\n httpPut.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray()));\n httpPut.setRequestHeader(S3_HEADER_NAME, S3_HEADER_VALUE);\n\n httpClient.executeMethod(httpPut);\n LOG.debug(\"1st response: \" + httpPut.getStatusLine().toString());\n\n boolean containsRedirect = (httpPut.getResponseHeader(\"Location\") != null);\n\n if (!containsRedirect) {\n httpPut.releaseConnection();\n LOG.error(\"1st response did not contain redirect. \" +\n \"No metadata will be created.\");\n return;\n }\n\n // Handle redirect header transition\n assert httpPut.getStatusCode() == 307;\n Header locationHeader = httpPut.getResponseHeader(\"Location\");\n httpPut.setURI(new URI(locationHeader.getValue(), true));\n\n // Consume response and re-allocate connection for redirect\n httpPut.releaseConnection();\n httpClient.executeMethod(httpPut);\n\n LOG.debug(\"2nd response: \" + httpPut.getStatusLine().toString());\n\n if (httpPut.getStatusCode() != 200) {\n LOG.debug(\"Response not 200: \" + httpPut.getResponseBodyAsString());\n return;\n }\n\n assert httpPut.getStatusCode() == 200;\n }\n\n /**\n * Sends a GET command to read a metadata file inside of HDFS.\n * It uses the URL from the original request to do so.\n * It will then consume the 307 response and read from the DataNode as well.\n *\n * @throws IOException\n * @throws ServletException\n */\n public Properties sendRead(String nnHostAddress, String userName)\n throws IOException, ServletException {\n // Set up HttpGet and get response\n String[] nnHost = nnHostAddress.split(\":\");\n String metapath = replaceUri(request.getRequestURI(), OBJECT_FILE_NAME,\n META_FILE_NAME);\n\n GetMethod httpGet = (GetMethod) getHttpMethod(request.getScheme(),\n nnHost[0], Integer.decode(nnHost[1]), \"OPEN\", userName,\n metapath, GET);\n\n // Try up to 5 times to get the metadata\n httpClient.executeMethod(httpGet);\n LOG.debug(\"1st response: \" + httpGet.getStatusLine().toString());\n\n for (int i = 0; i < 5 && httpGet.getStatusCode() == 403; i++) {\n httpGet.releaseConnection();\n httpClient.executeMethod(httpGet);\n LOG.debug(\"Next response: \" + httpGet.getStatusLine().toString());\n }\n assert httpGet.getStatusCode() == 200;\n\n // Read metadata map\n InputStream is = httpGet.getResponseBodyAsStream();\n Properties metadata = new Properties();\n metadata.load(is);\n\n // Consume response remainder to re-allocate connection and return map\n httpGet.releaseConnection();\n return metadata;\n }\n\n /**\n * Sends a GET command to read a metadata file inside of HDFS.\n * It uses the URL from the modified URI to do so.\n * It will then consume the 307 response and read from the DataNode as well.\n *\n * @throws IOException\n */\n public Properties sendHeadRead(String metadataPath, String nnHostAddress,\n String userName) throws IOException {\n // Set up HttpGet and get response\n String[] nnHost = nnHostAddress.split(\":\");\n GetMethod httpGet = (GetMethod) getHttpMethod(request.getScheme(),\n nnHost[0], Integer.decode(nnHost[1]), \"OPEN\", userName,\n ADD_WEBHDFS(metadataPath), GET);\n\n // Try up to 5 times to get the metadata\n httpClient.executeMethod(httpGet);\n LOG.info(\"1st response: \" + httpGet.toString());\n System.out.println(\"1st response: \" + httpGet.toString());\n\n for (int i = 0; i < 5 && httpGet.getStatusCode() == 403; i++) {\n httpGet.releaseConnection();\n httpClient.executeMethod(httpGet);\n LOG.info(\"Next response: \" + httpGet.toString());\n System.out.println(\"Next response: \" + httpGet.toString());\n }\n assert httpGet.getStatusCode() == 200;\n\n // Read metadata map\n InputStream is = httpGet.getResponseBodyAsStream();\n Properties metadata = new Properties();\n metadata.load(is);\n\n // Consume response remainder to re-allocate connection and return map\n httpGet.releaseConnection();\n return metadata;\n }\n\n}", "public class ObjectInfoRedirect extends Redirect {\n\n public ObjectInfoRedirect(HttpServletRequest request,\n HttpServletResponse response,\n S3HdfsPath path) {\n super(request, response, path);\n LOG.debug(\"Created \" + getClass().getSimpleName() + \".\");\n }\n\n /**\n * Sends a GET command to obtain the stat info on the object.\n * It uses the URL from the original request to do so.\n *\n * @throws IOException\n * @throws ServletException\n */\n public Properties getInfo() throws IOException, ServletException {\n GetMethod httpGet = (GetMethod) getHttpMethod(request.getScheme(),\n request.getServerName(), request.getServerPort(), \"GETFILESTATUS\",\n path.getUserName(), path.getFullHdfsObjPath(), GET);\n\n httpClient.executeMethod(httpGet);\n\n String properties = readInputStream(httpGet.getResponseBodyAsStream());\n Properties info = parseFileInfo(properties);\n\n // consume response\n httpGet.releaseConnection();\n assert httpGet.getStatusCode() == 200;\n return info;\n }\n\n public String getContents(String pathToRead) throws IOException {\n GetMethod httpGet = (GetMethod) getHttpMethod(request.getScheme(),\n request.getServerName(), request.getServerPort(), \"OPEN\",\n path.getUserName(), pathToRead, GET);\n\n httpClient.executeMethod(httpGet);\n\n String content = readInputStream(httpGet.getResponseBodyAsStream());\n\n // consume response\n httpGet.releaseConnection();\n assert httpGet.getStatusCode() == 200;\n return content;\n }\n\n public S3HdfsFileStatus getStatus(String object, String version)\n throws IOException, ServletException {\n GetMethod httpGet = (GetMethod) getHttpMethod(request.getScheme(),\n request.getServerName(), request.getServerPort(), \"GETFILESTATUS\",\n path.getUserName(),\n path.getHdfsRootBucketPath() + object + \"/\" + version + \"/\" + OBJECT_FILE_NAME,\n GET);\n\n httpClient.executeMethod(httpGet);\n\n // If file does not exist, check if delete marker for it exists.\n if (httpGet.getStatusCode() == 404) {\n httpGet.releaseConnection();\n httpGet = (GetMethod) getHttpMethod(request.getScheme(),\n request.getServerName(), request.getServerPort(), \"GETFILESTATUS\",\n path.getUserName(),\n path.getHdfsRootBucketPath() + object + \"/\" + version + \"/\" + DELETE_MARKER_FILE_NAME,\n GET);\n\n httpClient.executeMethod(httpGet);\n }\n\n String jsonStatus = readInputStream(httpGet.getResponseBodyAsStream());\n JsonNode element = new ObjectMapper().readTree(jsonStatus).get(\"FileStatus\");\n\n // consume response\n httpGet.releaseConnection();\n assert httpGet.getStatusCode() == 200;\n return parseHdfsFileStatus(element);\n }\n\n public List<S3HdfsFileStatus> getFilteredListing(String objectName, String prefix)\n throws IOException {\n\n GetMethod httpGet = (GetMethod) getHttpMethod(request.getScheme(),\n request.getServerName(), request.getServerPort(), \"LISTSTATUS\",\n path.getUserName(), path.getHdfsRootBucketPath() + objectName, GET);\n\n httpClient.executeMethod(httpGet);\n\n String listingStr = readInputStream(httpGet.getResponseBodyAsStream());\n List<S3HdfsFileStatus> listing = parseAndFilterListing(listingStr, prefix);\n\n // consume response\n httpGet.releaseConnection();\n assert httpGet.getStatusCode() == 200;\n return listing;\n }\n\n public Map<String, List<S3HdfsFileStatus>> getVersions(List<S3HdfsFileStatus> listing)\n throws IOException, ServletException {\n Map<String, List<S3HdfsFileStatus>> versions =\n new HashMap<String, List<S3HdfsFileStatus>>();\n\n for (S3HdfsFileStatus stats : listing) {\n String objectName = stats.getLocalName();\n List<S3HdfsFileStatus> versionList = getFilteredListing(objectName, null);\n modifyVersionList(objectName, versionList);\n versions.put(stats.getLocalName(), versionList);\n }\n\n return versions;\n }\n\n // Here we replace the version HdfsFileStatus with its length and sizes,\n // but keep the version directory name.\n void modifyVersionList(String objectName,\n List<S3HdfsFileStatus> versionList)\n throws IOException, ServletException {\n for (S3HdfsFileStatus f : versionList) {\n String versionName = f.getLocalName();\n\n S3HdfsFileStatus versionedObject = getStatus(objectName, versionName);\n\n // If this is the DEFAULT_VERSION; get the REAL versionId.\n if (DEFAULT_VERSION.equals(versionName)) {\n GetMethod httpGet = (GetMethod) getHttpMethod(request.getScheme(),\n request.getServerName(), request.getServerPort(), \"OPEN\",\n path.getUserName(),\n path.getHdfsRootBucketPath() + objectName + \"/\" + DEFAULT_VERSION + \"/\" + VERSION_FILE_NAME,\n GET);\n\n httpClient.executeMethod(httpGet);\n versionName = readInputStream(httpGet.getResponseBodyAsStream());\n httpGet.releaseConnection();\n f.setLatest(true);\n } else {\n f.setLatest(false);\n }\n\n String delMarkerPath = path.getHdfsRootBucketPath() + objectName + \"/\" +\n f.getLocalName() + \"/\" + DELETE_MARKER_FILE_NAME;\n boolean delMarker = checkExists(delMarkerPath);\n f.setDelMarker(delMarker);\n f.setVersionId(versionName);\n f.setObjectModTime(versionedObject.getModificationTime());\n f.setObjectSize(versionedObject.getLen());\n }\n }\n\n private List<S3HdfsFileStatus> parseAndFilterListing(String versionStr,\n String prefix)\n throws IOException {\n\n ObjectMapper mapper = new ObjectMapper();\n JsonNode jsonRoot = mapper.readTree(versionStr);\n JsonNode array = jsonRoot.get(\"FileStatuses\").get(\"FileStatus\");\n\n List<S3HdfsFileStatus> versions = new ArrayList<S3HdfsFileStatus>();\n\n for (int i = 0; i < array.size(); i++) {\n JsonNode element = array.get(i);\n\n String path = element.get(\"pathSuffix\").getTextValue();\n if (prefix != null && !path.startsWith(prefix))\n continue;\n\n S3HdfsFileStatus status = parseHdfsFileStatus(element);\n versions.add(status);\n }\n\n return versions;\n }\n\n private S3HdfsFileStatus parseHdfsFileStatus(JsonNode element) {\n return new S3HdfsFileStatus(\n element.get(\"length\").getLongValue(),\n element.get(\"type\").getTextValue().equalsIgnoreCase(\"DIRECTORY\"),\n element.get(\"replication\").getIntValue(),\n element.get(\"blockSize\").getLongValue(),\n element.get(\"modificationTime\").getLongValue(),\n element.get(\"accessTime\").getLongValue(),\n FsPermission.createImmutable((short) element.get(\"permission\").getIntValue()),\n element.get(\"owner\").getTextValue(),\n element.get(\"group\").getTextValue(),\n (element.get(\"symlink\") == null) ? null :\n DFSUtil.string2Bytes(element.get(\"symlink\").getTextValue()),\n DFSUtil.string2Bytes(element.get(\"pathSuffix\").getTextValue()),\n element.get(\"fileId\").getLongValue(),\n element.get(\"childrenNum\").getIntValue()\n );\n }\n\n private Properties parseFileInfo(String fileInfo)\n throws IOException {\n ObjectMapper mapper = new ObjectMapper();\n JsonNode jsonRoot = mapper.readTree(fileInfo);\n JsonNode jsonInfo = jsonRoot.get(\"FileStatus\");\n Properties info = new Properties();\n info.setProperty(\"Content-Length\",\n Long.toString(jsonInfo.get(\"length\").getLongValue()));\n return info;\n }\n\n public boolean checkExists(String pathToCheck) throws IOException {\n GetMethod httpGet = (GetMethod) getHttpMethod(request.getScheme(),\n request.getServerName(), request.getServerPort(), \"GETFILESTATUS\",\n path.getUserName(), pathToCheck, GET);\n\n httpClient.executeMethod(httpGet);\n httpGet.releaseConnection();\n\n return httpGet.getStatusCode() == 200;\n }\n\n}", "public class S3HdfsRequestWrapper extends HttpServletRequestWrapper {\n\n private ServletInputStream inputStream;\n\n /**\n * Constructs a response adaptor wrapping the given response.\n *\n * @throws IllegalArgumentException if the response is null\n */\n public S3HdfsRequestWrapper(HttpServletRequest request) {\n super(request);\n }\n\n @Override\n public ServletInputStream getInputStream() throws IOException {\n if (inputStream != null)\n return inputStream;\n return getRequest().getInputStream();\n }\n\n public void setInputStream(ServletInputStream is) {\n inputStream = is;\n }\n\n @Override\n public String toString() {\n return getRequest().toString();\n }\n}", "public class S3HdfsResponseWrapper extends HttpServletResponseWrapper {\n\n private int status = 200; // default status\n\n /**\n * Constructs a response adaptor wrapping the given response.\n *\n * @throws IllegalArgumentException if the response is null\n */\n public S3HdfsResponseWrapper(HttpServletResponse response) {\n super(response);\n }\n\n @Override\n public void sendError(int sc) throws IOException {\n this.status = sc;\n super.sendError(sc);\n }\n\n @Override\n public void sendError(int sc, String msg) throws IOException {\n this.status = sc;\n super.sendError(sc, msg);\n }\n\n @Override\n public void sendRedirect(String location) throws IOException {\n this.status = 302;\n super.sendRedirect(location);\n }\n\n public int getStatus() {\n return this.status;\n }\n\n @Override\n public void setStatus(int sc) {\n this.status = sc;\n super.setStatus(sc);\n }\n\n @Override\n public String toString() {\n return getResponse().toString();\n }\n}", "public class WebHdfsRequestWrapper extends HttpServletRequestWrapper {\n\n private static Logger LOG = LoggerFactory.getLogger(\n WebHdfsRequestWrapper.class);\n\n private final HttpServletRequest request;\n private final S3HdfsPath s3HdfsPath;\n private final S3HDFS_COMMAND command;\n private ServletInputStream inputStream;\n\n public WebHdfsRequestWrapper(final HttpServletRequest hsr,\n final S3HDFS_COMMAND command,\n final S3HdfsPath s3HdfsPath) {\n super(hsr);\n this.request = hsr;\n this.command = command;\n this.s3HdfsPath = s3HdfsPath;\n }\n\n @Override\n public String getQueryString() {\n String userName = s3HdfsPath.getUserName();\n StringBuilder query = userName == null ? new StringBuilder() :\n new StringBuilder(new UserParam(userName).toString());\n\n //TODO: Move the QueryString logic into modifiedURI in the Commands.\n\n // build GET logic\n if (request.getMethod().equalsIgnoreCase(\"GET\")) {\n if (command.equals(S3HDFS_COMMAND.GET_OBJECT) ||\n command.equals(S3HDFS_COMMAND.GET_VERSIONING)) {\n query.append(\"&op=OPEN\");\n String rangeHeader = request.getHeader(\"Range\");\n if (rangeHeader != null) {\n long[] ranges = parseRange(rangeHeader);\n long startRange = ranges[0];\n long endRange = ranges[1];\n query.append(\"&offset=\").append(startRange).append(\"&length=\").append(endRange);\n }\n } else\n query.append(\"&op=LISTSTATUS\");\n // build PUT logic\n } else if (request.getMethod().equalsIgnoreCase(\"PUT\")) {\n if (command.equals(S3HDFS_COMMAND.PUT_BUCKET))\n query.append(\"&op=MKDIRS&permission=777\");\n else if (command.equals(S3HDFS_COMMAND.PUT_OBJECT) ||\n command.equals(S3HDFS_COMMAND.UPLOAD_PART) ||\n command.equals(S3HDFS_COMMAND.COPY_OBJECT) ||\n command.equals(S3HDFS_COMMAND.CONFIGURE_VERSIONING))\n query.append(\"&op=CREATE&overwrite=true\");\n // build DELETE logic\n } else if (request.getMethod().equalsIgnoreCase(\"DELETE\")) {\n query.append(\"&op=DELETE&recursive=true\");\n // build POST logic\n } else if (request.getMethod().equalsIgnoreCase(\"POST\")) {\n //query.append(\"&op=APPEND\");\n }\n return query.toString();\n }\n\n private long[] parseRange(final String rangeHeader) {\n long[] retVal = new long[2];\n String parsed = rangeHeader.replace(\"bytes=\", \"\").trim();\n String[] longStrs = parsed.split(\"-\");\n // first value from s3 is an offset to start at\n // in HDFS it is also an offset to start at\n retVal[0] = Long.parseLong(longStrs[0]);\n // second value from s3 is the ending byte range\n // in HDFS it is a length to read (end - start)\n long endRange = Long.parseLong(longStrs[1]);\n retVal[1] = endRange - retVal[0];\n return retVal;\n }\n\n @Override\n public ServletInputStream getInputStream() throws IOException {\n if (inputStream != null)\n return inputStream;\n return super.getInputStream();\n }\n\n public void setInputStream(ServletInputStream is) {\n inputStream = is;\n }\n\n @Override\n public String getParameter(final String name) {\n if (name.equals(UserParam.NAME))\n return s3HdfsPath.getUserName();\n return super.getParameter(name);\n }\n}", "public class WebHdfsResponseWrapper extends HttpServletResponseWrapper {\n\n private static Logger LOG = LoggerFactory.getLogger(\n WebHdfsResponseWrapper.class);\n\n protected OutputStream realOutputStream = null;\n protected ServletOutputStream stream = null;\n protected PrintWriter writer = null;\n\n public WebHdfsResponseWrapper(final HttpServletResponse response) {\n super(response);\n }\n\n public ServletOutputStream createOutputStream() throws IOException {\n try {\n realOutputStream = new ByteArrayOutputStream();\n return new ResponseStreamWrapper(realOutputStream);\n } catch (Exception ex) {\n LOG.error(\"Could not create OutputStream class.\", ex);\n }\n return null;\n }\n\n @Override\n public void flushBuffer() throws IOException {\n stream.flush();\n }\n\n @Override\n public ServletOutputStream getOutputStream() throws IOException {\n if (writer != null) {\n throw new IllegalStateException(\"getOutputStream() has already been called!\");\n }\n\n if (stream == null) {\n stream = createOutputStream();\n }\n return stream;\n }\n\n @Override\n public PrintWriter getWriter() throws IOException {\n if (writer != null) {\n return (writer);\n }\n\n if (stream != null) {\n throw new IllegalStateException(\"getOutputStream() has already been called!\");\n }\n\n stream = createOutputStream();\n writer = new PrintWriter(new OutputStreamWriter(stream, \"UTF-8\"));\n return (writer);\n }\n\n @Override\n public void setContentLength(int length) {\n super.setContentLength(length);\n }\n\n /**\n * Gets the underlying content of the output stream.\n *\n * @return content as a String\n */\n public String getContent() {\n return realOutputStream.toString();\n }\n\n /**\n * Clears the output stream so we can record again.\n */\n public void clearOutputStream() {\n stream = null;\n writer = null;\n realOutputStream = null;\n }\n\n @Override\n public String toString() {\n return getResponse().toString();\n }\n\n}", "public static enum S3HDFS_COMMAND {\n HEAD_OBJECT, GET_OBJECT, GET_BUCKET,\n GET_VERSIONING, LIST_PARTS, LIST_VERSIONS, GET_ALL_BUCKETS, PUT_OBJECT,\n COPY_OBJECT, UPLOAD_PART, CONFIGURE_VERSIONING, PUT_BUCKET, DELETE_OBJECT,\n DELETE_VERSION, ABORT_MULTI_PART, DELETE_BUCKET, INITIATE_MULTI_PART,\n COMPLETE_MULTI_PART, UNKNOWN\n}", "public static String ADD_WEBHDFS(final String uri) {\n if (uri.charAt(0) == '/')\n return S3HdfsConstants.WEBHDFS_PREFIX + uri;\n else\n return S3HdfsConstants.WEBHDFS_PREFIX + \"/\" + uri;\n}" ]
import com.wandisco.s3hdfs.path.S3HdfsPath; import com.wandisco.s3hdfs.rewrite.redirect.MetadataFileRedirect; import com.wandisco.s3hdfs.rewrite.redirect.ObjectInfoRedirect; import com.wandisco.s3hdfs.rewrite.wrapper.S3HdfsRequestWrapper; import com.wandisco.s3hdfs.rewrite.wrapper.S3HdfsResponseWrapper; import com.wandisco.s3hdfs.rewrite.wrapper.WebHdfsRequestWrapper; import com.wandisco.s3hdfs.rewrite.wrapper.WebHdfsResponseWrapper; import javax.servlet.ServletException; import java.io.IOException; import java.util.Properties; import static com.wandisco.s3hdfs.conf.S3HdfsConstants.S3HDFS_COMMAND; import static com.wandisco.s3hdfs.rewrite.filter.S3HdfsFilter.ADD_WEBHDFS;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wandisco.s3hdfs.command; public class HeadCommand extends Command { public HeadCommand(final S3HdfsRequestWrapper request, final S3HdfsResponseWrapper response, final String serviceHost, final String proxyPort, final S3HdfsPath s3HdfsPath) { super(request, response, serviceHost, proxyPort, s3HdfsPath); } @Override protected S3HDFS_COMMAND parseCommand() throws IOException { final String objectName = s3HdfsPath.getObjectName(); final String bucketName = s3HdfsPath.getBucketName(); if ((objectName != null && !objectName.isEmpty()) && (bucketName != null && !bucketName.isEmpty())) return S3HDFS_COMMAND.HEAD_OBJECT; else throw new IOException("Unknown command: " + command); } @Override protected String parseURI() throws IOException { // 1. Parse the command. command = parseCommand(); System.out.println("Command parsed as: " + command.toString()); // 2. Parse the modified URI. switch (command) { case HEAD_OBJECT: // A. If we get object head we need the version path // Version path == /root/user/bucket/object/version modifiedURI = s3HdfsPath.getHdfsRootVersionPath(); break; default: throw new IOException("Unknown command: " + command); } // 3. Set the modified URI.
modifiedURI = ADD_WEBHDFS(modifiedURI);
8
jesse-gallagher/frostillic.us-Blog
frostillicus-blog/frostillicus-blog-j2ee/src/main/java/controller/AdminController.java
[ "@RequestScoped\n@Named(\"userInfo\")\npublic class UserInfoBean {\n\tpublic static final String ROLE_ADMIN = \"admin\"; //$NON-NLS-1$\n\n\t@Inject @Named(\"darwinoContext\")\n\tDarwinoContext context;\n\n\t@SneakyThrows\n\tpublic String getImageUrl(final String userName) {\n\t\tString md5 = StringUtil.md5Hex(StringUtil.toString(userName).toLowerCase());\n\t\treturn StringUtil.format(DarwinoHttpConstants.SOCIAL_USERS_PATH + \"/users/{0}/content/photo\", URLEncoder.encode(md5, \"UTF-8\")); //$NON-NLS-1$ //$NON-NLS-2$\n\t}\n\n\tpublic boolean isAdmin() {\n\t\treturn context.getUser().hasRole(ROLE_ADMIN);\n\t}\n\n\tpublic boolean isAnonymous() {\n\t\treturn context.getUser().isAnonymous();\n\t}\n\n\tpublic String getCn() {\n\t\treturn context.getUser().getCn();\n\t}\n\n\tpublic String getDn() {\n\t\treturn context.getUser().getDn();\n\t}\n\n\tpublic String getEmailAddress() throws UserException {\n\t\tObject mail = context.getUser().getAttribute(User.ATTR_EMAIL);\n\t\treturn StringUtil.toString(mail);\n\t}\n}", "@Entity @Data @NoArgsConstructor\npublic class AccessToken {\n\t@Id @Column private String id;\n\t@Column private String userName;\n\t@Column private String name;\n\t@Column private String token;\n\t@Column private boolean isConflict;\n}", "@RepositoryProvider(AppDatabaseDef.STORE_TOKENS)\npublic interface AccessTokenRepository extends DarwinoRepository<AccessToken, String> {\n\tStream<AccessToken> findAll();\n\n\tOptional<AccessToken> findByToken(String token);\n}", "@Entity @Data @NoArgsConstructor\npublic class Link {\n\t@Id @Column private String id;\n\t@Column private String category;\n\t@Column(\"link_url\") @NotEmpty private String url;\n\t@Column(\"link_name\") @NotEmpty private String name;\n\t@Column(\"link_visible\") @Convert(BooleanYNConverter.class) private boolean visible;\n\t@Column private String rel;\n\t@Column private boolean isConflict;\n}", "@RepositoryProvider(AppDatabaseDef.STORE_CONFIG)\npublic interface LinkRepository extends DarwinoRepository<Link, String> {\n\tStream<Link> findAll();\n\n\t@Query(\"select * from Link order by category name\")\n\tList<Link> findAllByCategoryAndName();\n}" ]
import bean.UserInfoBean; import com.darwino.commons.json.JsonException; import com.darwino.jsonstore.Session; import model.AccessToken; import model.AccessTokenRepository; import model.Link; import model.LinkRepository; import javax.annotation.security.RolesAllowed; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.mvc.Controller; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.UUID;
/* * Copyright © 2012-2020 Jesse Gallagher * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package controller; @Controller @Path("admin") @RolesAllowed(UserInfoBean.ROLE_ADMIN) @RequestScoped public class AdminController { @Inject LinkRepository links; @Inject AccessTokenRepository tokens; @Inject Session session; @GET @Produces(MediaType.TEXT_HTML) public String show() { return "admin.jsp"; //$NON-NLS-1$ } // ******************************************************************************* // * Links // ******************************************************************************* @POST @Path("links/{linkId}") public String update( @PathParam("linkId") final String linkId, @FormParam("visible") final String visible, @FormParam("category") final String category, @FormParam("name") final String name, @FormParam("url") final String url, @FormParam("rel") final String rel ) { var link = links.findById(linkId).orElseThrow(() -> new NotFoundException("Unable to find link matching ID " + linkId)); //$NON-NLS-1$ link.setVisible("Y".equals(visible)); //$NON-NLS-1$ link.setCategory(category); link.setName(name); link.setUrl(url); link.setRel(rel); links.save(link); return "redirect:admin"; //$NON-NLS-1$ } @DELETE @Path("links/{linkId}") public String deleteLink(@PathParam("linkId") final String linkId) { links.deleteById(linkId); return "redirect:admin"; //$NON-NLS-1$ } @POST @Path("links/new") public String createLink() {
var link = new Link();
3
DevComPack/setupmaker
src/main/java/com/dcp/sm/gui/pivot/tasks/TaskDirScan.java
[ "public class IOFactory\n{\n //ISO3 language codes\n public static String[] iso3Codes;\n //File type extensions\n public static String[] archiveExt;// = {\"zip\", \"rar\", \"jar\", \"iso\"};\n public static String[] exeExt;// = {\"exe\", \"jar\", \"cmd\", \"sh\", \"bat\"};\n public static String[] setupExt;// = {\"msi\"};\n public static String[] docExt;// = {\"txt\", \"pdf\", \"doc\", \"docx\", \"xml\", \"rtf\", \"odt\", \"xls\", \"xlsx\", \"csv\"};\n public static String[] imgExt;// = {\"bmp\", \"jpg\", \"jpeg\", \"gif\", \"png\", \"ico\"};\n public static String[] webExt;// = {\"html\", \"htm\", \"php\", \"js\", \"asp\", \"aspx\", \"css\"};\n public static String[] soundExt;// = {\"wav\", \"mp3\", \"ogg\", \"wma\"};\n public static String[] vidExt;// = {\"mp4\", \"mpg\", \"mpeg\", \"wmv\", \"avi\", \"mkv\"};\n public static String[] custExt;//User defined custom extensions\n \n /**\n * Returns file type of a file\n * @param f: file\n * @return FILE_TYPE\n */\n public static FILE_TYPE getFileType(File f) {\n if (f.isDirectory()) return FILE_TYPE.Folder;\n \n String NAME = f.getName();\n if (IOFactory.isFileType(NAME, FILE_TYPE.Archive))//Archive\n return FILE_TYPE.Archive;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Executable))//Executable\n return FILE_TYPE.Executable;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Setup))//Setup file\n return FILE_TYPE.Setup;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Document))//Text Document file\n return FILE_TYPE.Document;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Image))//Image file\n return FILE_TYPE.Image;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Web))//Web file\n return FILE_TYPE.Web;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Sound))//Sound file\n return FILE_TYPE.Sound;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Video))//Video file\n return FILE_TYPE.Video;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Custom))//Custom extension\n return FILE_TYPE.Custom;\n else//Simple File\n return FILE_TYPE.File;\n }\n \n /**\n * Tests if a file's extension is of a type\n * (folders and files without extension are automatically valid)\n * @param file_name\n * @param file_type\n * @return boolean: success\n */\n public static boolean isFileType(String file_name, FILE_TYPE file_type) {\n // Accept all (unix) files without extensions\n if (!file_name.contains(\".\"))\n return true;\n \n String[] exts = null;\n switch (file_type) {\n case Archive:\n exts = archiveExt;\n break;\n case Executable:\n exts = exeExt;\n break;\n case Setup:\n exts = setupExt;\n break;\n case Document:\n exts = docExt;\n break;\n case Image:\n exts = imgExt;\n break;\n case Web:\n exts = webExt;\n break;\n case Sound:\n exts = soundExt;\n break;\n case Video:\n exts = vidExt;\n break;\n case Custom:\n exts = custExt;\n break;\n case File:\n return true;\n default:\n break;\n }\n assert exts != null;\n \n for(String S : exts)\n if (file_name.toLowerCase().endsWith(\".\"+S)) {\n return true;\n }\n return false;\n }\n \n \n // Cached icons\n private static final String iconsPath = \"/com/dcp/sm/gui/icons/\";\n public static Image imgFolder;//Folder icon\n public static Image imgFile;//File icon\n public static Image imgZip;//Archive icon\n public static Image imgExe;//Executable icon\n public static Image imgSetup;//Setup icon\n public static Image imgDoc;//Text file icon\n public static Image imgImg;//Image file icon\n public static Image imgWeb;//Web file icon\n public static Image imgSound;//Audio file icon\n public static Image imgVid;//Video file icon\n public static Image imgCust;//Custom filter file icon\n public static Image imgHistory;//History file icon\n public static Image imgClose;//Close file icon\n // Menu icons\n public static Image imgAdd;//Add menu icon\n public static Image imgRight;//Right arrow menu icon\n public static Image imgEdit;//Edit menu icon\n public static Image imgDelete;//Delete menu icon\n public static Image imgImport;//Import menu icon\n public static Image imgCopy;//Copy menu icon\n public static Image imgPaste;//Paste menu icon\n \n //Filters\n public final static Filter<File> imgFilter = new Filter<File>() {\n @Override public boolean include(File file)\n {\n if (file.isDirectory()) return false;\n else if (file.isFile() && IOFactory.isFileType(file.getName(), FILE_TYPE.Image) )\n return false;\n return true;\n }\n };\n public final static Filter<File> docFilter = new Filter<File>() {\n @Override public boolean include(File file)\n {\n if (file.isDirectory()) return false;\n else if (file.isFile() && (IOFactory.isFileType(file.getName(), FILE_TYPE.Document)\n || IOFactory.isFileType(file.getName(), FILE_TYPE.Web)))\n return false;\n return true;\n }\n };\n \n //JSON Files\n public static final String jsonSettings = \"settings.json\";\n //Directories Paths\n public static String resPath;// = \"res\";\n public static String xmlPath;// = resPath+\"/xml\";\n public static String langpackPath;// = resPath+\"/langpacks\";\n public static String batPath;// = resPath+\"/bat\";\n public static String antPath;// = resPath+\"/ant\";\n public static String psPath;// = resPath+\"ps/\";\n public static String libPath;// = \"lib/dcp\";\n public static String targetPath;// = \"target\";\n public static String savePath;// = \"saves\";\n public static String exeTargetDir;// = \"~tmp/\";\n //File Paths\n public static String confFile;// = \"conf.dcp\";\n public static String defDirFile;// = resPath+\"/default-dir.txt\";\n public static String xmlIzpackInstall;// = \"install.xml\";\n public final static String dcpFileExt = \"dcp\";\n //Options\n public static boolean izpackWrite;// = true; \n public static boolean izpackCompile;// = true;\n public static String apikey;// = Admin:Admin\n \n //Jar libraries\n //public static String jarExecutable;// = libPath+\"/dcp-executable.jar\";\n //public static String jarListeners;// = libPath+\"/dcp-listeners.jar\";\n public static String jarResources;// = libPath+\"/dcp-resources.jar\";\n //Ant build files\n public static String xmlIzpackAntBuild;// = antPath+\"/izpack-target.xml\";\n public static String xmlRunAntBuild;// = antPath+\"/run-target.xml\";\n public static String xmlDebugAntBuild;// = antPath+\"/debug-target.xml\";\n //Bat files\n public static String batClean;// = batPath+\"/clean.bat\";\n //izpack spec files\n public static String xmlProcessPanelSpec;// = xmlPath+\"/ProcessPanelSpec.xml\";\n public static String xmlShortcutPanelSpec;// = xmlPath+\"/ShortcutPanelSpec.xml\";\n public static String xmlRegistrySpec;// = xmlPath+\"/RegistrySpec.xml\";\n // chocolatey files\n public static String psChocolateyInstall;// = psPath+\"/ChocolateyInstall.ps1\"\n public static String psChocolateyUninstall;// = psPath+\"/ChocolateyUninstall.ps1\"\n \n public static String saveFile = \"\";//\"save.dcp\";\n public static void setSaveFile(String canonicalPath) {\n if (canonicalPath.length() > 0 && !canonicalPath.endsWith(\".\"+IOFactory.dcpFileExt)) {//add file extension if not given\n canonicalPath = canonicalPath.concat(\".\"+IOFactory.dcpFileExt);\n }\n saveFile = canonicalPath;\n }\n \n /**\n * Load settings from JSON file: settings.json\n * @throws ParseException \n * @throws IOException \n */\n private static boolean loadSettings(String json_file) throws IOException, ParseException {\n JsonSimpleReader json_ext = new JsonSimpleReader(json_file, \"extensions\");\n archiveExt = json_ext.readStringArray(\"archiveExt\");\n exeExt = json_ext.readStringArray(\"exeExt\");\n setupExt = json_ext.readStringArray(\"setupExt\");\n docExt = json_ext.readStringArray(\"docExt\");\n imgExt = json_ext.readStringArray(\"imgExt\");\n webExt = json_ext.readStringArray(\"webExt\");\n soundExt = json_ext.readStringArray(\"soundExt\");\n vidExt = json_ext.readStringArray(\"vidExt\");\n custExt = json_ext.readStringArray(\"custExt\");\n json_ext.close();\n\n JsonSimpleReader json_paths = new JsonSimpleReader(json_file, \"paths\");\n savePath = json_paths.readString(\"savePath\");\n resPath = json_paths.readString(\"resPath\");\n xmlPath = json_paths.readString(\"xmlPath\");\n langpackPath = json_paths.readString(\"langpackPath\");\n batPath = json_paths.readString(\"batPath\");\n antPath = json_paths.readString(\"antPath\");\n psPath = json_paths.readString(\"psPath\");\n libPath = json_paths.readString(\"libPath\");\n targetPath = json_paths.readString(\"targetPath\");\n exeTargetDir = json_paths.readString(\"exeTargetDir\");\n json_paths.close();\n\n JsonSimpleReader json_files = new JsonSimpleReader(json_file, \"files\");\n confFile = json_files.readString(\"confFile\");\n defDirFile = json_files.readString(\"defDirFile\");\n xmlIzpackInstall = json_files.readString(\"xmlIzpackInstall\");\n json_files.close();\n\n JsonSimpleReader json_options = new JsonSimpleReader(json_file, \"options\");\n izpackWrite = (json_options.readString(\"izpackWrite\").equalsIgnoreCase(\"yes\") ||\n json_options.readString(\"izpackWrite\").equalsIgnoreCase(\"true\"));\n izpackCompile = (json_options.readString(\"izpackCompile\").equalsIgnoreCase(\"yes\") ||\n json_options.readString(\"izpackCompile\").equalsIgnoreCase(\"true\"));\n apikey = json_options.readString(\"apikey\");\n json_options.close();\n \n JsonSimpleReader json_codes = new JsonSimpleReader(json_file, \"codes\");\n iso3Codes = json_codes.readStringArray(\"iso3\");\n json_codes.close();\n \n return true;\n }\n \n /**\n * Data load\n */\n public static void init() {\n try {\n \n //Import file extensions from settings.json\n loadSettings(IOFactory.jsonSettings);\n //jarExecutable = libPath+\"/dcp-executable.jar\";\n //jarListeners = libPath+\"/dcp-listeners.jar\";\n jarResources = libPath+\"/dcp-resources.jar\";\n xmlIzpackAntBuild = antPath+\"/izpack-target.xml\";\n xmlRunAntBuild = antPath+\"/run-target.xml\";\n xmlDebugAntBuild = antPath+\"/debug-target.xml\";\n batClean = batPath+\"/clean.bat\";\n xmlProcessPanelSpec = xmlPath+\"/ProcessPanelSpec.xml\";\n xmlShortcutPanelSpec = xmlPath+\"/ShortcutPanelSpec.xml\";\n xmlRegistrySpec = xmlPath+\"/RegistrySpec.xml\";\n psChocolateyInstall = psPath+\"/ChocolateyInstall.ps1\";\n psChocolateyUninstall = psPath+\"/ChocolateyUninstall.ps1\";\n \n //Images Resources\n imgFolder = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"folder.png\"));\n imgFile = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"file.png\"));\n imgZip = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"archive.png\"));\n imgExe = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"executable.png\"));\n imgSetup = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"setup.png\"));\n imgDoc = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"document.png\"));\n imgImg = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"image.png\"));\n imgWeb = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"webfile.png\"));\n imgSound = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"sound.png\"));\n imgVid = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"video.png\"));\n imgCust = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"filter.png\"));\n imgHistory = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"history.png\"));\n imgClose = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"close.png\"));\n imgAdd = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"add.png\"));\n \n imgRight = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"right.png\"));\n imgEdit = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"edit.png\"));\n imgDelete = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"delete.png\"));\n imgImport = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"import.png\"));\n imgCopy = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"copy.png\"));\n imgPaste = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"paste.png\"));\n \n //Make needed directories\n String[] dirs = new String[] {resPath, antPath, batPath, xmlPath, targetPath, savePath};\n for(String dir:dirs) {\n File f = new File(dir);\n if (!f.exists())\n f.mkdir();\n }\n \n } catch (TaskExecutionException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n } catch (ParseException e) {\n e.printStackTrace();\n }\n }\n \n}", "public class ScanFrame extends FillPane implements Bindable\n{\n // Singleton reference\n private static ScanFrame singleton;\n public static ScanFrame getSingleton() { assert (singleton != null); return singleton; }\n public ScanFacade facade;\n // Configuration\n private AppConfig appConfig = Master.facade.appConfig;\n private SetupConfig setupConfig = Master.facade.setupConfig;\n // Master class\n private Master master;\n public void setMaster(Master master) { this.master = master; }\n // Edit Flag\n private boolean modified = false;// True if tab changed data\n public void setModified(boolean VALUE) { assert master != null; modified = VALUE; master.setUndo(true); }\n public boolean isModified() { return modified; }\n \n public List<Pack> getPacks() {// Read-only Packs data (selected)\n if (treeView.getCheckmarksEnabled())// If select mode and not loaded\n return facade.getCheckedPacks(treeView.getCheckedPaths());\n return facade.getPacks();\n }\n public List<Group> getGroups() {\n return facade.getGroups();\n }\n \n // Browse Area\n @BXML private FileBrowserSheet fileBrowserSheet;// File Browser\n @BXML private TextInput inPath;// Path Text Input\n public String getScanDir() { return inPath.getText(); }// Return scanned directory path\n @BXML private PushButton btRefresh;// Refresh button\n @BXML private PushButton btBrowse;// Browse button\n // Recent Directories options\n @BXML private SplitPane hSplitPane;\n @BXML private TablePane recent_dirs;\n @BXML private TablePane recent_projects;\n // Scan Mode options\n @BXML private RadioButton btRadSimple;// Simple Scan Mode Radio Button\n @BXML private Checkbox btSelect;// Activate/Desactivate Node Check State Select mode\n @BXML private PushButton btSelectAll;// Select All button\n @BXML private PushButton btSelectNone;// Select None button\n @BXML private RadioButton btRadRecursiv;// Recursive Scan Mode Radio Button (default)\n @BXML private BoxPane depthPane;// Depth Label+Spinner Box Pane\n @BXML private Spinner depthSpinner;// Spinner depth value\n @BXML private PushButton btCollapse;// Collapse button\n @BXML private PushButton btExpand;// Expand button\n // Filter options\n @BXML private Checkbox cbZip;// Archives\n @BXML private Checkbox cbSetup;// Setups\n @BXML private Checkbox cbExe;// Executables\n @BXML private Checkbox cbDir;// Directories\n @BXML private Checkbox cbImg;// Images\n @BXML private Checkbox cbVid;// Videos\n @BXML private Checkbox cbSound;// Sounds\n @BXML private Checkbox cbDoc;// Documents\n @BXML private Checkbox cbCustTxt;// Custom set filter\n @BXML private Checkbox cbCustExpr;// Custom Expression filter button\n @BXML private TextInput inCustExpr;// Custom REGEXP filter input\n // Advanced options\n @BXML private Checkbox cbFolderScan;// Treat folders as groups in Set tab\n @BXML private Checkbox cbFolderTarget;// Treat folders as install paths for Packs in Set tab\n // Displays\n @BXML private static TreeView treeView;// Tree View for scanned directory\n // Filter\n private FilenameFilter filter;\n // Actions\n private Action ADirScan;// Scan the given directory\n // Menu Handlers\n private MenuHandler MHTreeView;\n //========================\n \n public ScanFrame() {// Constructor\n assert (singleton == null);\n singleton = this;\n \n // folder tree view context menu\n MHTreeView = new MenuHandler.Adapter() {\n @Override public boolean configureContextMenu(Component component, Menu menu, int x, int y)\n {\n final TreeNode node = (TreeNode) treeView.getSelectedNode();\n \n if (node != null) {\n Menu.Section menuSection = new Menu.Section();\n menu.getSections().add(menuSection);\n \n Menu.Item itemOpen = new Menu.Item(new ButtonData(IOFactory.imgFolder, \"scan\"));\n \n final File newDir = new File(inPath.getText(), node.getText());\n if (newDir.exists() && newDir.isDirectory()) {\n itemOpen.getButtonPressListeners().add(new ButtonPressListener() {// scan selected folder\n @Override public void buttonPressed(Button bt) {\n Out.print(LOG_LEVEL.DEBUG, \"Scan folder set to child folder: \" + node.getText());\n inPath.setText(newDir.getAbsolutePath());\n ADirScan.perform(bt);\n }\n });\n }\n else itemOpen.setEnabled(false);\n \n menuSection.add(itemOpen);\n }\n return false;\n }\n };\n \n filter = new FilenameFilter() {// Checkbox packs filters\n @Override public boolean accept(File dir, String name)\n {\n try {\n if (inCustExpr.getText().length() > 0 && name.matches(inCustExpr.getText()))\n return !cbCustExpr.isSelected();\n if (IOFactory.isFileType(name, FILE_TYPE.Archive))\n return !cbZip.isSelected();\n if (IOFactory.isFileType(name, FILE_TYPE.Setup))\n return !cbSetup.isSelected();\n if (IOFactory.isFileType(name, FILE_TYPE.Executable))\n return !cbExe.isSelected();\n if (IOFactory.isFileType(name, FILE_TYPE.Image))\n return !cbImg.isSelected();\n if (IOFactory.isFileType(name, FILE_TYPE.Video))\n return !cbVid.isSelected();\n if (IOFactory.isFileType(name, FILE_TYPE.Sound))\n return !cbSound.isSelected();\n if (IOFactory.isFileType(name, FILE_TYPE.Document))\n return !cbDoc.isSelected();\n if (IOFactory.isFileType(name, FILE_TYPE.Custom))\n return !cbCustTxt.isSelected();\n return true;\n }\n catch (PatternSyntaxException e) {\n cbCustExpr.setSelected(false);\n return true;\n }\n }\n };\n \n ADirScan = new Action() {// Directory Scan from Filters/mode Action\n @Override public void perform(Component source) {\n if (btSelect.isSelected()) btSelect.press(); // * bugfix: scan on enabled selection doesn't update packs list\n \n TaskDirScan scan = new TaskDirScan(singleton, inPath.getText(), facade.getTreeData(), filter,\n (String) depthSpinner.getSelectedItem(), !cbDir.isSelected());\n \n int res = scan.execute();\n if (res == 0) {\n Out.print(LOG_LEVEL.DEBUG, \"Scanned directory: \" + inPath.getText());\n // Save directory to app config recent dirs\n appConfig.addRecentDir(new File(inPath.getText()));// add scanned dir to recent dirs\n recentFieldFill(recent_dirs, appConfig.getRecentDirs());// refresh recent dirs list display\n if (depthSpinner.getSelectedIndex() < 5)\n treeView.expandAll();\n else treeView.collapseAll();\n inPath.requestFocus();\n setModified(true);// Modified Flag (*)\n }\n else if (res == 2) {// Error: Path doesn't exist\n Out.print(LOG_LEVEL.DEBUG, \"Path error: \" + inPath.getText());\n Alert.alert(\"This path doesn't exist! Please correct it.\", ScanFrame.this.getWindow());\n }\n \n } };\n }\n\n //========================\n @Override\n public void initialize(Map<String, Object> namespace, URL location, Resources resources)\n {\n facade = new ScanFacade();\n recentFieldFill(recent_dirs, appConfig.getRecentDirs());\n recentFieldFill(recent_projects, appConfig.getRecentProjects());\n hSplitPane.setSplitRatio(appConfig.getScanHorSplitPaneRatio());\n \n // Custom filters fill from settings.json file to UI\n if (IOFactory.custExt.length > 0) {\n final int maxExts = 3;// number of extensions to show in UI\n String customFilters = \"(\";\n for (int i = 0; i < maxExts && i < IOFactory.custExt.length; i++)\n customFilters += IOFactory.custExt[i] + \" \";\n customFilters = \"Custom \" + customFilters.trim().replaceAll(\" \", \", \")\n + (IOFactory.custExt.length > maxExts ? \"..)\" : \")\");\n Out.print(LOG_LEVEL.DEBUG, \"Loaded Filter: \"+customFilters);\n cbCustTxt.setButtonData(new ButtonData(customFilters));\n }\n \n // Select button transitions\n final AppearTransition selectExpTrans = new AppearTransition(btSelect, 150, 20);\n final FadeTransition selectCollTrans = new FadeTransition(btSelect, 100, 20);\n // Depth transitions\n final AppearTransition depthAppTrans = new AppearTransition(depthPane, 150, 20);\n final FadeTransition depthFadeTrans = new FadeTransition(depthPane, 100, 20);\n \n // Validators\n inPath.setValidator(new PathValidator(inPath, false));\n \n // Data Binding\n treeView.setMenuHandler(MHTreeView);\n treeView.setTreeData(facade.getTreeData());// Bind Tree view to data\n treeView.getTreeViewNodeStateListeners().add(new TreeViewNodeStateListener() {\n @Override public void nodeCheckStateChanged(TreeView tv, Path arg1, NodeCheckState arg2)\n {\n setModified(true);\n }\n });\n \n // Action Binding\n btRefresh.setAction(ADirScan);\n btRefresh.setButtonDataKey(\"ENTER\");\n btBrowse.setAction(new BrowseAction(fileBrowserSheet));\n \n // Set default directory selection in File Browser (packs/)\n try {// Set working directory as root directory for file browser\n fileBrowserSheet.setRootDirectory(new File(\".\").getCanonicalFile());\n } catch (IOException e) {\n e.printStackTrace();\n }\n fileBrowserSheet.setMode(FileBrowserSheet.Mode.SAVE_TO);// FileBrowser Mode to Directory selection\n \n // Directory select in File Browser Event\n fileBrowserSheet.getFileBrowserSheetListeners().add(new FileBrowserSheetListener.Adapter() {\n @Override\n public void selectedFilesChanged(FileBrowserSheet fileBrowserSheet, Sequence<File> previousSelectedFiles)\n {\n // If path changed\n if (!ScanFrame.this.inPath.getText().equals(fileBrowserSheet.getSelectedFile().getAbsolutePath())) {\n boolean error = false;\n if (!ScanFrame.this.inPath.getValidator().isValid(inPath.getText()) && ScanFrame.this.inPath.getText().length() > 0) {\n error = true;\n }\n ScanFrame.this.inPath.setText(fileBrowserSheet.getSelectedFile().getAbsolutePath());\n ADirScan.perform(fileBrowserSheet);// Scan Action\n if (error == true) {\n Out.print(LOG_LEVEL.INFO, \"Updated folder path for packs to: \"+ScanFrame.this.inPath.getText());\n //setModified(false);\n }\n }\n }\n });\n \n // update workspace scan horizontal splitpane ratio\n hSplitPane.getSplitPaneListeners().add(new SplitPaneListener.Adapter() {\n @Override public void splitRatioChanged(SplitPane sp, float ratio)\n {\n appConfig.setScanHorSplitPaneRatio(sp.getSplitRatio());\n }\n });\n \n // Update setup source path from inPath\n inPath.getTextInputContentListeners().add(new TextInputContentListener.Adapter() {\n @Override public void textChanged(TextInput TI)\n {\n if (TI.isValid())// path exists\n setupConfig.setSrcPath(TI.getText());\n }\n });\n // Set root directory from written path to file browser\n inPath.getComponentStateListeners().add(new ComponentStateListener.Adapter() {\n @Override public void focusedChanged(Component component, Component obverseComponent)\n {\n if (!component.isFocused()) {\n File root = new File(inPath.getText());\n if (root.exists() && root.isDirectory())\n fileBrowserSheet.setRootDirectory(root);\n }\n }\n });\n \n //Simple scan activate radio button listener\n btRadSimple.getButtonPressListeners().add(new ButtonPressListener() {\n @Override public void buttonPressed(Button bt)\n {\n if (facade.getScanMode() == SCAN_MODE.RECURSIVE_SCAN) {\n setScanMode(SCAN_MODE.SIMPLE_SCAN);\n btSelect.setVisible(true);\n btSelect.setSelected(false);\n selectExpTrans.start();//Select button expand transition\n depthFadeTrans.start(new TransitionListener() {//Depth Fade transition\n @Override public void transitionCompleted(Transition tr)\n {\n depthPane.setVisible(false);\n btCollapse.setEnabled(false);\n btExpand.setEnabled(false);\n cbFolderScan.setEnabled(false);\n cbFolderTarget.setEnabled(false);\n }\n });\n ADirScan.perform(bt);\n }\n }\n });\n //Recursive scan activate radio button listener\n btRadRecursiv.getButtonPressListeners().add(new ButtonPressListener() {\n @Override public void buttonPressed(Button bt)\n {\n if (facade.getScanMode() == SCAN_MODE.SIMPLE_SCAN) {\n setScanMode(SCAN_MODE.RECURSIVE_SCAN);\n btCollapse.setEnabled(true);\n btExpand.setEnabled(true);\n selectCollTrans.start(new TransitionListener() {//Select button collapse transition\n @Override public void transitionCompleted(Transition arg0)\n {\n btSelect.setVisible(false);\n btSelectAll.setEnabled(false);\n btSelectNone.setEnabled(false);\n cbFolderScan.setEnabled(true);\n cbFolderTarget.setEnabled(true);\n // enable Group folder options by default\n cbFolderScan.setSelected(true);\n setFolderScan(SCAN_FOLDER.GROUP_FOLDER);\n cbFolderTarget.setSelected(true);\n setFolderTarget(true);\n }\n });\n depthPane.setVisible(true);\n depthAppTrans.start();//Depth appear transition\n ADirScan.perform(bt);\n }\n }\n });\n \n btExpand.getButtonPressListeners().add(new ButtonPressListener() {\n @Override public void buttonPressed(Button bt)\n {\n treeView.expandAll();\n }\n });\n btCollapse.getButtonPressListeners().add(new ButtonPressListener() {\n @Override public void buttonPressed(Button bt)\n {\n treeView.collapseAll();\n }\n });\n \n //Activate Checkmarks for tree view button listener\n btSelect.getButtonStateListeners().add(new ButtonStateListener() {\n @Override public void stateChanged(Button bt, State st)\n {\n if (bt.isSelected()) {//Enable Selection\n treeView.setCheckmarksEnabled(true);\n btSelectAll.setEnabled(true);\n btSelectNone.setEnabled(true);\n selectAll();\n }\n else {//Disable Selection\n treeView.setCheckmarksEnabled(false);\n btSelectAll.setEnabled(false);\n btSelectNone.setEnabled(false);\n setModified(true);// (*)\n }\n }\n });\n //Select All button\n btSelectAll.getButtonPressListeners().add(new ButtonPressListener() {\n @Override public void buttonPressed(Button bt) { selectAll(); }\n });\n //Select None button\n btSelectNone.getButtonPressListeners().add(new ButtonPressListener() {\n @Override public void buttonPressed(Button bt) { selectNone(); }\n });\n \n //Spinner depth value change listener (do scan)\n depthSpinner.getSpinnerSelectionListeners().add(new SpinnerSelectionListener.Adapter() {\n @Override public void selectedIndexChanged(Spinner spinner, int previousSelectedIndex)\n {\n ADirScan.perform(spinner);//Directory scan\n }\n });\n \n //Checkbox Filters Event Listeners\n cbZip.getButtonPressListeners().add(new ButtonPressListener() {//Archive\n @Override public void buttonPressed(Button button) {\n ADirScan.perform(button);//Action launch\n Out.print(LOG_LEVEL.DEBUG,\"Applied filter: Archive\");\n }\n });\n cbSetup.getButtonPressListeners().add(new ButtonPressListener() {//Setup\n @Override public void buttonPressed(Button button) {\n ADirScan.perform(button);//Action launch\n Out.print(LOG_LEVEL.DEBUG,\"Applied filter: Setup\");\n }\n });\n cbExe.getButtonPressListeners().add(new ButtonPressListener() {//Executable\n @Override public void buttonPressed(Button button) {\n ADirScan.perform(button);//Action launch\n Out.print(LOG_LEVEL.DEBUG,\"Applied filter: Executable\");\n }\n });\n cbDir.getButtonPressListeners().add(new ButtonPressListener() {//Directory\n @Override public void buttonPressed(Button button) {\n ADirScan.perform(button);//Action launch\n Out.print(LOG_LEVEL.DEBUG,\"Applied filter: Directory\");\n }\n });\n cbImg.getButtonPressListeners().add(new ButtonPressListener() {//Images\n @Override public void buttonPressed(Button button) {\n ADirScan.perform(button);//Action launch\n Out.print(LOG_LEVEL.DEBUG,\"Applied filter: Image\");\n }\n });\n cbVid.getButtonPressListeners().add(new ButtonPressListener() {//Videos\n @Override public void buttonPressed(Button button) {\n ADirScan.perform(button);//Action launch\n Out.print(LOG_LEVEL.DEBUG,\"Applied filter: Video\");\n }\n });\n cbSound.getButtonPressListeners().add(new ButtonPressListener() {//Sounds\n @Override public void buttonPressed(Button button) {\n ADirScan.perform(button);//Action launch\n Out.print(LOG_LEVEL.DEBUG,\"Applied filter: Sound\");\n }\n });\n cbDoc.getButtonPressListeners().add(new ButtonPressListener() {//Documents\n @Override public void buttonPressed(Button button) {\n ADirScan.perform(button);//Action launch\n Out.print(LOG_LEVEL.DEBUG,\"Applied filter: Document\");\n }\n });\n cbCustTxt.getButtonPressListeners().add(new ButtonPressListener() {// Custom filter SETTINGS\n @Override public void buttonPressed(Button button) {\n ADirScan.perform(button);//Action launch\n Out.print(LOG_LEVEL.DEBUG,\"Applied custom filter\");\n }\n });\n cbCustExpr.getButtonPressListeners().add(new ButtonPressListener() {//Custom filter REGEXP\n @Override public void buttonPressed(Button button) {\n ADirScan.perform(button);//Action launch\n Out.print(LOG_LEVEL.DEBUG,\"Applied regular expression filter\");\n }\n });\n inCustExpr.getTextInputContentListeners().add(new TextInputContentListener.Adapter() {\n @Override public void textChanged(TextInput textInput)\n {\n if (cbCustExpr.isSelected())\n ADirScan.perform(textInput);//Action launch\n }\n });\n \n cbFolderScan.getButtonPressListeners().add(new ButtonPressListener() {\n @Override public void buttonPressed(Button bt)\n {\n if (bt.isSelected())\n setFolderScan(SCAN_FOLDER.GROUP_FOLDER);\n else setFolderScan(SCAN_FOLDER.PACK_FOLDER);\n }\n });\n cbFolderTarget.getButtonPressListeners().add(new ButtonPressListener() {\n @Override public void buttonPressed(Button bt)\n {\n if (bt.isSelected())\n setFolderTarget(true);\n else setFolderTarget(false);\n }\n });\n \n }\n \n //========================\n \n /**\n * Checkmarks Selection function for packs tree view (simple scan/select mode)\n */\n private void selectAll() {\n if (treeView.getCheckmarksEnabled())\n for(int i=0; i<facade.getTreeData().getLength(); i++)//Select all\n treeView.setNodeChecked(new Path(i), true);\n }\n private void selectNone() {\n if (treeView.getCheckmarksEnabled())\n for(int i=0; i<facade.getTreeData().getLength(); i++)//Select all\n treeView.setNodeChecked(new Path(i), false);\n }\n \n /**\n * Changes the Mode of Scan [SIMPLE|RECURSIVE]\n * @param new_mode\n */\n private void setScanMode(SCAN_MODE new_mode)\n {\n assert (new_mode == SCAN_MODE.RECURSIVE_SCAN || new_mode == SCAN_MODE.SIMPLE_SCAN);\n SCAN_MODE mode = facade.getScanMode();\n if (mode != new_mode) {\n //Directory Filter Checkbox value change\n if (new_mode == SCAN_MODE.RECURSIVE_SCAN) {// Recursive Scan\n treeView.setCheckmarksEnabled(false);// Check state disable\n }\n\n if (mode == SCAN_MODE.DEFAULT)\n Out.print(LOG_LEVEL.DEBUG, \"Scan Mode set to \" + new_mode);\n else\n Out.print(LOG_LEVEL.DEBUG, \"Scan Mode changed from \" + mode + \" to \" + new_mode);\n \n facade.setScanMode(new_mode);\n setModified(true);\n }\n }\n \n /**\n * Changes the folder scan mode [PACK|GROUP]\n * @param new_mode\n */\n private void setFolderScan(SCAN_FOLDER new_mode)\n {\n SCAN_FOLDER mode = facade.getFolderScan();\n if (mode != new_mode) {\n if (mode == SCAN_FOLDER.DEFAULT)\n Out.print(LOG_LEVEL.DEBUG, \"Folder scan mode set to: \" + new_mode);\n else\n Out.print(LOG_LEVEL.DEBUG, \"Folder scan mode changed from \" + mode + \" to \" + new_mode);\n \n facade.setFolderScan(new_mode);\n setModified(true);\n }\n }\n /**\n * Changes the folder target mode [true|false]\n * @param enable\n */\n private void setFolderTarget(boolean enable)\n {\n if (facade.getFolderTarget() != enable) {\n if (enable == true)\n Out.print(LOG_LEVEL.DEBUG, \"Folder target mode set\");\n else\n Out.print(LOG_LEVEL.DEBUG, \"Folder target mode unset\");\n \n facade.setFolderTarget(enable);\n setModified(true);\n }\n }\n \n /**\n * Fill recent paths field with list of Files\n * @param field: gui component to fill\n * @param files: list of paths to put\n */\n public void recentFieldFill(final TablePane field, final List<File> files) {\n if (files != null)\n try\n {\n if (field.getRows().getLength() > 0)// Data clear\n field.getRows().remove(0, field.getRows().getLength());\n \n //Analyze for wrong paths to remove\n int n = files.getLength();\n for(int i = 0; i < n; i++) {\n if (!files.get(i).exists()) {\n files.remove(files.get(i));\n i--; n--;\n }\n }\n \n for(final File file:files)\n {\n //Remove button\n ButtonData remBtData = new ButtonData(IOFactory.imgClose, \"\");\n final Button btRemove = new PushButton(remBtData);\n btRemove.setStyles(\"{toolbar:'true', backgroundColor:'WHITE', borderColor:'WHITE'}\");\n btRemove.setTooltipText(\"Remove\");\n btRemove.setVisible(false);\n\n final BoxPane removeBoxPane = new BoxPane();//BoxPane\n removeBoxPane.setOrientation(Orientation.HORIZONTAL);\n removeBoxPane.setStyles(\"{verticalAlignment:'center', horizontalAlignment:'right'}\");\n removeBoxPane.add(btRemove);\n \n //Directory Link button\n ButtonData btData = new ButtonData(IOFactory.imgHistory,\n file.getParentFile().getName() + \"/\" + file.getName());\n final LinkButton btLink = new LinkButton(btData);//LinkButton\n btLink.setStyles(\"{color:'#0198E1'}\");\n btLink.setTooltipText(file.getAbsolutePath());\n\n final BoxPane linkBoxPane = new BoxPane();//BoxPane\n linkBoxPane.setOrientation(Orientation.HORIZONTAL);\n linkBoxPane.setStyles(\"{verticalAlignment:'center', horizontalAlignment:'left'}\");\n linkBoxPane.add(btLink);\n \n //Row\n final FillPane fillPane = new FillPane();//FillPane\n fillPane.setOrientation(Orientation.HORIZONTAL);\n fillPane.add(linkBoxPane);\n \n final Row row = new Row();//TablePane.Row\n row.setHeight(\"16\");\n row.add(fillPane);\n row.add(removeBoxPane);\n \n field.getRows().add(row);\n \n //Remove button display/hide event\n removeBoxPane.getComponentMouseListeners().add(new ComponentMouseListener.Adapter() {\n @Override public void mouseOver(Component component)\n {\n btRemove.setVisible(true);\n }\n @Override public void mouseOut(Component component)\n {\n btRemove.setVisible(false);\n }\n });\n \n //Remove button press event\n btRemove.getButtonPressListeners().add(new ButtonPressListener() {\n @Override public void buttonPressed(Button bt)\n {\n field.getRows().remove(row);\n Out.print(LOG_LEVEL.INFO, file.getName()+\" entry removed\");\n if (field.equals(recent_dirs))\n appConfig.removeRecentDir(file);\n else if (field.equals(recent_projects))\n appConfig.removeRecentProject(file);\n }\n });\n \n //Recent directory link press event\n btLink.getButtonPressListeners().add(new ButtonPressListener() {\n @Override public void buttonPressed(Button bt)\n {\n if (field.equals(recent_dirs)) { // Scan folder\n inPath.setText(file.getAbsolutePath());\n fileBrowserSheet.setRootDirectory(file.getParentFile());\n fileBrowserSheet.setSelectedFile(file);\n ADirScan.perform(bt);\n }\n else if (field.equals(recent_projects)) { // Load project\n master.loadProject(file.getAbsolutePath());\n }\n }\n });\n }\n \n field.repaint();\n }\n catch (SerializationException e) {\n e.printStackTrace();\n }\n }\n \n /**\n * Init options from default/loaded setup configuration\n * @param appConfig: application configuration\n * @param setupConfig: default or loaded setup configuration data\n */\n public void init(AppConfig appConfig, SetupConfig setupConfig) {\n inPath.setText(setupConfig.getSrcPath());\n facade.clear();\n \n this.appConfig = appConfig;\n this.setupConfig = setupConfig;\n \n SCAN_FOLDER scanFolder = setupConfig.getScanFolder();\n if (scanFolder != facade.getFolderScan()) {\n cbFolderScan.setSelected(scanFolder == SCAN_FOLDER.GROUP_FOLDER ? true : false);\n setFolderScan(scanFolder);\n }\n if (setupConfig.getScanTarget() != facade.getFolderTarget()) {\n cbFolderTarget.setSelected(setupConfig.getScanTarget());\n setFolderTarget(setupConfig.getScanTarget());\n }\n \n SCAN_MODE scanMode = setupConfig.getScanMode();\n if (scanMode != facade.getScanMode()) {\n // display update\n if (scanMode == SCAN_MODE.RECURSIVE_SCAN) {\n btRadRecursiv.setSelected(true);\n btCollapse.setEnabled(true);\n btExpand.setEnabled(true);\n btSelect.setVisible(false);\n btSelectAll.setEnabled(false);\n btSelectNone.setEnabled(false);\n depthPane.setVisible(true);\n cbFolderScan.setEnabled(true);\n cbFolderTarget.setEnabled(true);\n }\n else {\n btRadSimple.setSelected(true);\n btSelect.setVisible(true);\n btSelect.setSelected(false);\n depthPane.setVisible(false);\n btCollapse.setEnabled(false);\n btExpand.setEnabled(false);\n cbFolderScan.setEnabled(false);\n cbFolderTarget.setEnabled(false);\n }\n setScanMode(scanMode);// scans folder too\n }\n \n ADirScan.perform(null);\n setModified(false);// disable update on next step\n }\n \n}", "public class CastFactory\n{\n //Constants\n private final static String PATH_DELIMITER = \"/\";\n \n \n /**\n * File to Pack cast\n * @param FILE\n * @return Pack\n */\n public static Pack fileToPack(File FILE) {\n String NAME = FILE.getName();//File name\n Image IMG = null;//Icon\n IMG = nameToImage(NAME, FILE.isDirectory());\n Pack P = new Pack(NAME, IMG);//Pack (NAME + IMG)\n P.setFileType(IOFactory.getFileType(FILE));\n P.setSize(FILE.length());//Size\n \n try {//File Path\n P.setPath(FILE.getCanonicalPath());//PATH\n \n } catch (IOException e) {\n e.printStackTrace();\n }\n \n return P;\n }\n \n /**\n * Pivot Image from Pack name\n * @param NAME\n * @param folder\n * @return Image\n */\n public static Image nameToImage(String NAME, boolean folder)\n {\n Image IMG = null;//Icon\n if (folder) {//Folder\n IMG = IOFactory.imgFolder;\n }\n else {//File icon\n if (IOFactory.isFileType(NAME, FILE_TYPE.Archive))\n IMG = IOFactory.imgZip;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Executable))\n IMG = IOFactory.imgExe;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Setup))\n IMG = IOFactory.imgSetup;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Document))\n IMG = IOFactory.imgDoc;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Image))\n IMG = IOFactory.imgImg;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Web))\n IMG = IOFactory.imgWeb;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Sound))\n IMG = IOFactory.imgSound;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Video))\n IMG = IOFactory.imgVid;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Custom))\n IMG = IOFactory.imgCust;\n else\n IMG = IOFactory.imgFile;//Simple File\n }\n return IMG;\n }\n\n /**\n * String array path to single string delimited by '/'\n * @param PATH\n * @return String Path\n */\n public static String pathToString(String[] PATH) {\n String tmpPath = \"\";\n for(String s:PATH)//Strings concat\n tmpPath = tmpPath + s + PATH_DELIMITER;\n return tmpPath;\n }\n \n /**\n * Tree view Node to String array path from Tree view root\n * @param NODE\n * @return path array of parent groups\n */\n public static String[] nodeToPath(TreeNode NODE) {\n java.util.List<String> backList = new java.util.ArrayList<String>();\n //Return back in hierarchy\n TreeNode Ntmp = NODE;\n do {\n backList.add(Ntmp.getText());\n Ntmp = Ntmp.getParent();\n } while(Ntmp != null);\n //Copy the hierarchy from top to bottom\n String[] PATH = new String[backList.size()];\n int i = 0;\n ListIterator<String> it = backList.listIterator(backList.size());\n while(it.hasPrevious()) {\n PATH[i++] = it.previous();\n }\n \n return PATH;\n }\n \n /**\n * Add Group's children to tree branch recursively\n * @param group\n * @return group's new branch instance\n */\n public static TreeBranch groupToSingleBranch(Group group) {\n TreeBranch TB = new TreeBranch(IOFactory.imgFolder, group.getName());\n TB.setUserData(group);//Save model data\n return TB;\n }\n private static void recursivAdd(Group group, TreeBranch TARGET_TB) {\n for(Group G:group.getChildren()) {\n TreeBranch TB = groupToSingleBranch(G);\n TARGET_TB.add(TB);\n recursivAdd(G, TB);//-@\n }\n }\n /**\n * Group model to new TreeBranch tree view component\n * @param group\n * @return group's new branch instance with childs\n */\n public static TreeBranch groupToBranch(Group group) {\n TreeBranch TB = groupToSingleBranch(group);\n recursivAdd(group, TB);//Add its childs\n return TB;\n }\n \n /**\n * Pack model to Tree view node\n * @param P\n * @return pack's new node instance\n */\n public static TreeNode packToNode(Pack P) {\n //TreeNode node = new TreeNode(P.getIcon(), P.getInstallName());\n TreeNode node = new TreeNode(P.getIcon(), P.getName());\n node.setUserData(P);//Save model data\n return node;\n }\n \n \n /**\n * Validate path\n * @param target_file\n * @param default_name\n * @param extension\n * @return validated path\n */\n public static String pathValidate(String target_file, String default_name, String extension) {\n //Target file output validating\n if (target_file.equals(\"\"))//If no path entered\n target_file = new File(\"\").getAbsolutePath() + \"/\"+default_name + \".\"+extension;//in working directory\n \n else {//Path entered\n \n //if relative path entered\n if ( (OSValidator.isWindows() && !target_file.substring(1).startsWith(\":\")) ||//Windows starts with '?:'\n (OSValidator.isUnix() && !target_file.startsWith(\"/\")) )//Unix starts with '/'\n target_file = new File(\"\").getAbsolutePath() + \"/\" + target_file;\n //if no extension .jar given in path, add it to last name\n if (!(target_file.endsWith(\".\"+extension.toLowerCase()) ||\n target_file.endsWith(\".\"+extension.toUpperCase()))) {\n \n if (target_file.endsWith(\"/\") || target_file.endsWith(\"\\\\\"))//if ends with directory\n target_file = target_file + default_name + \".\"+extension;\n else//If ends with file name\n target_file = target_file + \".\"+extension;\n \n }\n //If parent path doesn't exist\n if (!new File(new File(target_file).getParent()).exists()) {\n new File(new File(target_file).getParent()).mkdir();//Making the directory\n if (!new File(new File(target_file).getParent()).exists())//If error in creating dir\n target_file = new File(\"\").getAbsolutePath() + \"/\" + default_name;//Working dir\n }\n }\n \n return target_file;\n }\n \n /**\n * Update model data of old Pack\n * @param P: Pack to update\n * @param DCP_VERSION: old DCP version of pack\n */\n public static void packModelUpdate(Pack P, String DCP_VERSION) {\n switch (DCP_VERSION) {// no break for first cases to update properties on cascade\n case \"1.0\":\n P.setInstallVersion(Pack.getVersionFromName(P.getName()));\n case \"1.1\":\n P.setArch(0);\n \n Out.print(LOG_LEVEL.DEBUG, \"Pack data model updated from \"+ DCP_VERSION +\".x to current DCP version\");\n break;\n }\n }\n \n /**\n * Update setup data of old SetupConfigs\n * @param setupConfig: SetupConfig to update\n * @param DCP_VERSION: old DCP version of pack\n */\n public static void setupModelUpdate(SetupConfig setupConfig, String DCP_VERSION) {\n switch (DCP_VERSION) {// no break for first cases to update properties on cascade\n case \"1.0\":\n case \"1.1\":\n setupConfig.setScanMode(SCAN_MODE.SIMPLE_SCAN);\n setupConfig.setScanFolder(SCAN_FOLDER.PACK_FOLDER);\n \n Out.print(LOG_LEVEL.DEBUG, \"Setup data model updated from \"+ DCP_VERSION +\".x to current DCP version\");\n break;\n }\n }\n \n}", "public static enum SCAN_MODE {\n DEFAULT,\n SIMPLE_SCAN,//Default\n RECURSIVE_SCAN\n}", "public class Group implements Comparable<Group>, Serializable\n{\n /**\n * Class written into save file\n */\n private static final long serialVersionUID = 7019635543387148548L;\n \n //Groups\n private String installGroups = \"\";//Install Groups *\n //Attributes\n private String name;//Group name\n private Group parent = null;//Parent group, if any\n private String description = \"\";//Group's description\n //Childs\n private List<Group> children = new ArrayList<Group>();//Childs, if is parent\n public void addChild(Group G) { children.add(G); }//Add child to Group\n public void removeChild(Group G) { children.remove(G); }//Delete Child Cascade\n public List<Group> getChildren() { return children; }//Returns the childs\n \n //Constructors\n public Group() {\n }\n public Group(String name) {\n this.name = name;\n }\n public Group(String name, Group parent) {\n this.name = name;\n setParent(parent);\n }\n public Group(Group group) {\n this.name = group.getName();\n if (group.getParent() != null)\n \tsetParent(group.getParent());\n setDescription(group.getDescription());\n setInstallGroups(group.getInstallGroups());\n }\n \n /**\n * Cast group model from Non-Maven data (<v1.2.1)\n * @param group\n */\n public Group(dcp.logic.model.Group group) {\n assert group != null;\n this.name = group.name;\n if (group.parent != null)\n \tsetParent(new Group(group.parent));\n setDescription(group.description);\n setInstallGroups(group.installGroups);\n\t}\n\t//Getters & Setters\n public String getInstallGroups() { return installGroups; }\n public void setInstallGroups(String installGroups) { this.installGroups = installGroups; }\n \n public String getName() { return name; }\n public void setName(String name) { this.name = name; }\n \n public Group getParent() { return parent; }\n public void setParent(Group PARENT) { this.parent = PARENT; }\n public boolean hasParent(Group PARENT) {\n return GroupFactory.hasParent(this, PARENT);\n }\n \n public String getDescription() { return description; }\n public void setDescription(String description) { this.description = description; }\n \n public String getPath() {\n return CastFactory.pathToString(GroupFactory.getPath(this));\n }\n \n //Comparison function\n @Override\n public boolean equals(Object obj)//Groups compare\n {\n if (obj==null) return false;\n if (obj instanceof Group) {\n Group G = (Group) obj;\n if (G.getParent() != null)\n return this.name.equalsIgnoreCase(G.getName()) && this.getPath().equalsIgnoreCase(G.getPath());\n else//Group has no parent\n return this.name.equalsIgnoreCase(G.getName()) && this.parent == null;\n }\n else if (obj instanceof TreeBranch) {\n TreeBranch branch = (TreeBranch) obj;\n return this.name.equalsIgnoreCase(branch.getText()) &&\n ( (this.getParent() != null && branch.getParent() != null && this.getParent().equals(branch.getParent())) ||\n (this.getParent() == null && branch.getParent() == null) );\n }\n else return false;\n }\n \n @Override\n public String toString()\n {\n return this.getPath();\n }\n @Override\n public int compareTo(Group o)\n {\n if (this.equals(o))\n return 0;//Equal\n else {\n int string_compare = (this.getName().compareTo(o.getName()));//Name comparison\n if (string_compare != 0)\n return string_compare;\n else\n return -1;\n }\n }\n \n}", "public class Pack implements Serializable\n{\n /**\n * Write Pack data to save file\n */\n private static final long serialVersionUID = -8775694196832301518L;\n \n //Relations\n private Group group = null;//Pack member of this group\n private String installGroups = \"\";//Install Groups *\n private Group dependsOnGroup = null;//Group dependency\n private Pack dependsOnPack = null;//Pack dependency\n //Attributes\n private String name = \"\";//File Name\n private FILE_TYPE fileType = FILE_TYPE.File;//File type\n private double size = 0;//File Size in bytes\n private String path = \"\";//File Absolute Path\n private INSTALL_TYPE installType = INSTALL_TYPE.COPY;//Install Type\n private PLATFORM installOs = PLATFORM.ALL;//Install OS\n private int arch = 0;// Platform Architecture (32/64 bits|0 = all)\n private String installPath = \"\";//Install Path, after the $INSTALL_PATH defined\n private String shortcutPath = \"\";//Relative path for shortcut\n //Info\n private int priority = 0;//Pack install priority\n private String installName = \"\";//Pack Install Name\n private String installVersion = \"1.0.0\";//Pack Install Version\n private String description = \"\";//Pack description\n //Booleans\n private boolean silent_install = false;//If Setup install is passive\n private boolean required = false;//Is required\n private boolean selected = true;//Is selected\n private boolean hidden = false;//Is hidden\n private boolean override = true;//If pack will override existing pack\n private boolean shortcut = false;//If pack will have a shortcut created for it\n //Icon\n private String icon = \"\";//Icon file path\n private transient Image imgIcon = null;//Icon Image\n \n //Functions\n public String getBaseName() {//Name without extension\n if (name.contains(\".\"))\n return name.substring(0,name.lastIndexOf(\".\"));\n return name;\n }\n // extract version number from file name<\n public static String getVersionFromName(String name) {\n try {\n if (Pattern.compile(\".*[0-9]+([._\\\\-a-zA-Z][0-9]+)+.*\").matcher(name).find()) {\n String[] borders = name.split(\"[0-9]+([._\\\\-a-zA-Z][0-9]+)+[a-zA-Z]?\");\n if (borders.length > 0)\n return name.substring(borders[0].length(), name.length() - (borders.length > 1?borders[1].length():0));\n else\n return name;\n }\n return \"1.0.0\";\n }\n catch(IllegalStateException e) {\n System.out.println(e);\n return \"1.0.0\";\n }\n }\n \n //Constructors\n public Pack(String NAME, Image ICON) {\n this.name = NAME;\n this.description = name;\n this.installName = name;\n this.installVersion = getVersionFromName(name);\n setIcon(ICON);\n }\n public Pack(Pack pack) {//Copy another Pack data\n name = pack.name;\n priority = pack.priority;\n fileType = pack.fileType;\n installName = pack.installName;\n installVersion = pack.installVersion; // 1.1\n size = pack.size;\n path = pack.path;\n group = pack.group;\n installType = pack.installType;\n if (pack.installOs != null) installOs = pack.installOs;\n arch = pack.arch; // 1.2\n installPath = pack.installPath;\n shortcutPath = pack.shortcutPath;\n installGroups = pack.installGroups;\n description = pack.description;\n if (pack.dependsOnGroup!=null) dependsOnGroup = pack.dependsOnGroup;\n if (pack.dependsOnPack!=null) dependsOnPack = pack.dependsOnPack;\n required = pack.required;\n selected = pack.selected;\n hidden = pack.hidden;\n override = pack.override;\n shortcut = pack.shortcut;\n silent_install = pack.silent_install;\n icon = pack.icon;\n imgIcon = pack.imgIcon;\n }\n \n /**\n * Cast pack model from Non-Maven data (<v1.2.1)\n * @param obj\n */\n public Pack(dcp.logic.model.Pack pack) {\n name = pack.name;\n priority = pack.priority;\n fileType = pack.fileType.cast();\n installName = pack.installName;\n installVersion = pack.installVersion; // 1.1\n size = pack.size;\n path = pack.path;\n if (pack.group != null) group = new Group(pack.group);\n installType = pack.installType.cast();\n if (pack.installOs != null) installOs = pack.installOs.cast();\n arch = pack.arch; // 1.2\n installPath = pack.installPath;\n shortcutPath = pack.shortcutPath;\n installGroups = pack.installGroups;\n description = pack.description;\n if (pack.dependsOnGroup != null) dependsOnGroup = GroupFactory.get(new Group(pack.dependsOnGroup).getPath());\n if (pack.dependsOnPack != null) dependsOnPack = new Pack(pack.dependsOnPack);\n required = pack.required;\n selected = pack.selected;\n hidden = pack.hidden;\n override = pack.override;\n shortcut = pack.shortcut;\n silent_install = pack.silent_install;\n icon = pack.icon;\n setIcon(imgIcon);\n\t}\n \n \n\t//Overrides\n @Override public boolean equals(Object obj)//Packs compare\n {\n if (obj==null) return false;\n if (obj instanceof Pack) {//With a Pack model\n Pack P = (Pack) obj;\n return this.name.toLowerCase().equals(P.getName().toLowerCase())//Name\n && this.path.toLowerCase().equals(P.getPath().toLowerCase());//Path\n }\n else if (obj instanceof TreeNode) {//With a TreeView Node\n TreeNode node = (TreeNode) obj;\n return this.name.toLowerCase().equals(node.getText().toLowerCase())//Name\n && this.group.equals(node.getParent());//Group\n }\n else return super.equals(obj);\n }\n @Override\n public String toString()\n {\n return this.name;\n }\n \n /**\n * Update pack name and path from new file\n * @param new_file\n */\n public void updatePack(File new_file) {\n name = new_file.getName();\n path = new_file.getAbsolutePath();\n }\n \n //Relation functions\n public Group getGroup() { return group; }\n public String getGroupName() {\n if (group != null)\n return group.getName();\n return \"\";\n }\n public String getGroupPath() {\n if (group != null)\n return group.getPath();\n return \"\";\n }\n public void setGroup(Group group) { this.group = group; }\n \n public String getInstallGroups() { return installGroups; }\n public void setInstallGroups(String installGroups) { this.installGroups = installGroups; }\n \n public Group getGroupDependency() { return dependsOnGroup; }\n public void setGroupDependency(Group group) { this.dependsOnGroup = group; this.dependsOnPack = null; }\n public Pack getPackDependency() { return dependsOnPack; }\n public void setPackDependency(Pack pack) { this.dependsOnPack = pack; this.dependsOnGroup = null; }\n \n \n //Getters & Setters\n public String getName() { return name; }\n \n public double getSize() { return size; }\n public void setSize(double size) { this.size = size; }\n\n public String getIconPath() { return icon; }\n public Image getIcon() { return imgIcon; }\n public void setIcon(String ICON)\n {\n this.icon = ICON;\n try {\n setIcon( Image.load(getClass().getResource(icon)) );\n } catch (TaskExecutionException e) {\n e.printStackTrace();\n }\n }\n public void setIcon(Image ICON) { imgIcon = ICON; }\n \n public String getPath() { return path; }\n public void setPath(String path) { this.path = path; }\n \n public String getInstallPath() { return installPath; }\n public void setInstallPath(String installPath) { this.installPath = installPath; }\n \n public String getShortcutPath() { return shortcutPath; }\n public void setShortcutPath(String shortcutPath) {\n if (shortcutPath.length() > 0 && !(shortcutPath.substring(0, 1).equals(\"/\") || shortcutPath.substring(0, 1).equals(\"\\\\\")))\n shortcutPath = \"/\" + shortcutPath;\n this.shortcutPath = shortcutPath;\n }\n \n \n //Info functions\n public String getInstallName() { return installName; }\n public void setInstallName(String installName) { this.installName = installName; }\n\n public String getInstallVersion() { return installVersion; }\n public void setInstallVersion(String installVersion) { this.installVersion = installVersion; }\n \n public String getDescription() { return description; }\n public void setDescription(String description) { this.description = description; }\n \n public INSTALL_TYPE getInstallType() { return installType; }\n public void setInstallType(INSTALL_TYPE IT) { installType = IT; }\n\n public PLATFORM getInstallOs() { return installOs; }\n public void setInstallOs(PLATFORM OS) { installOs = OS; }\n \n public int getArch() { return arch; }\n public void setArch(int arch) {\n assert arch == 0 || arch == 32 || arch == 64;\n this.arch = arch;\n }\n \n public int getPriority() { return priority+1; }\n public void setPriority(int priority) { this.priority = priority; }\n \n \n //Boolean functions\n public FILE_TYPE getFileType() { return fileType; }\n public void setFileType(FILE_TYPE fileType) { this.fileType = fileType; }\n public boolean isSilentInstall() { return this.silent_install; }\n public void setSilentInstall(boolean silent_install) { this.silent_install = silent_install; }\n \n public boolean isRequired() { return required; }\n public void setRequired(boolean required) {\n this.required = required;\n if (required == true && this.getPackDependency() != null) {\n this.getPackDependency().setRequired(true);\n }\n }\n public boolean isSelected() { return selected; }\n public void setSelected(boolean selected) {\n this.selected = selected;\n if (selected == true && this.getPackDependency() != null) {\n this.getPackDependency().setSelected(true);\n }\n }\n public boolean isHidden() { return hidden; }\n public void setHidden(boolean hidden) { this.hidden = hidden; }\n public boolean isOverride() { return override; }\n public void setOverride(boolean override) { this.override = override; }\n public boolean isShortcut() { return shortcut; }\n public void setShortcut(boolean shortcut) { this.shortcut = shortcut; }\n \n}" ]
import java.io.File; import java.io.FilenameFilter; import org.apache.pivot.collections.List; import org.apache.pivot.util.concurrent.Task; import org.apache.pivot.wtk.content.TreeBranch; import org.apache.pivot.wtk.content.TreeNode; import com.dcp.sm.config.io.IOFactory; import com.dcp.sm.gui.pivot.frames.ScanFrame; import com.dcp.sm.logic.factory.CastFactory; import com.dcp.sm.logic.factory.TypeFactory.SCAN_MODE; import com.dcp.sm.logic.model.Group; import com.dcp.sm.logic.model.Pack;
package com.dcp.sm.gui.pivot.tasks; public class TaskDirScan extends Task<Integer> { //Constants private final static int INFINITE_DEPTH = 20;//Maximum recursive scan depth if depth is '-' //Attributes private ScanFrame scanFrame; private String path; private List<TreeNode> treeData; private String depthValue; //Data private List<Group> groups; private List<Pack> packs; //Filter private boolean folderFilter; private FilenameFilter filter; public TaskDirScan(ScanFrame source, String path, List<TreeNode> treeData, FilenameFilter filter, String depthValue, boolean folderFilter) { this.scanFrame = source; // point to data models lists this.groups = scanFrame.facade.getGroups(); this.packs = scanFrame.facade.getPacks(); this.path = path; this.treeData = treeData; this.filter= filter; this.depthValue = depthValue; this.folderFilter = folderFilter; } /** * Recursive Scan Function + Groups create * Scan DIR to treeBranch, directories to PARENT */ private void recursivScan(File directory, TreeBranch treeBranch, Group PARENT, int DEPTH) { for(File f:directory.listFiles(filter)) { if (f.isDirectory()) {//Directory if (DEPTH>0) { Group G = new Group(f.getName(),PARENT); groups.add(G);//Group model add TreeBranch T = new TreeBranch(IOFactory.imgFolder, f.getName()); recursivScan(f, T, G, DEPTH-1);//@- treeBranch.add(T);//Tree Branch node add } else if (folderFilter) {//Get folders as packs Pack P = CastFactory.fileToPack(f); P.setPriority(packs.getLength());//Priority initialize P.setGroup(PARENT); packs.add(P); treeBranch.add(new TreeNode(P.getIcon(), P.getName()));//Tree node add } } else {//File Pack P = CastFactory.fileToPack(f); P.setPriority(packs.getLength());//Priority initialize P.setGroup(PARENT);//Setting Parent packs.add(P); treeBranch.add(new TreeNode(P.getIcon(), P.getName()));//Tree node add } } } /** * Simple Scan Functions * @param directory to scan * @param folder folder filter is selected */ private void simpleScan(File directory) { for(File f : directory.listFiles(filter)) { if (f.isDirectory()) {//Directory if (folderFilter) {//Directory filter cb selected (not active) Pack P = CastFactory.fileToPack(f); P.setPriority(packs.getLength());//Priority initialize packs.add(P); treeData.add(new TreeNode(P.getIcon(), P.getName())); } } else if (f.isFile()) {//File Pack P = CastFactory.fileToPack(f); P.setPriority(packs.getLength());//Priority initialize packs.add(P); treeData.add(new TreeNode(P.getIcon(), P.getName())); } } } @Override public Integer execute() { scanFrame.facade.clear();// Clear data if (!path.equals("")) {//If a path is entered File dir = new File(path); if (dir.exists()) { scanFrame.setModified(true);//Flag Modified TreeBranch treeBranch = new TreeBranch(dir.getName());
SCAN_MODE scanMode = ScanFrame.getSingleton().facade.getScanMode();
3
kaliturin/BlackList
app/src/main/java/com/kaliturin/blacklist/fragments/SettingsFragment.java
[ "public class MainActivity extends AppCompatActivity\n implements NavigationView.OnNavigationItemSelectedListener {\n\n public static final String ACTION_JOURNAL = \"com.kaliturin.blacklist.ACTION_JOURNAL\";\n public static final String ACTION_SMS_CONVERSATIONS = \"com.kaliturin.blacklist.ACTION_SMS_CONVERSATIONS\";\n public static final String ACTION_SETTINGS = \"com.kaliturin.blacklist.ACTION_SETTINGS\";\n public static final String ACTION_SMS_SEND_TO = \"android.intent.action.SENDTO\";\n\n private static final String CURRENT_ITEM_ID = \"CURRENT_ITEM_ID\";\n private FragmentSwitcher fragmentSwitcher = new FragmentSwitcher();\n private NavigationView navigationView;\n private DrawerLayout drawer;\n private int selectedMenuItemId = 0;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n Settings.applyCurrentTheme(this);\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n // permissions\n Permissions.checkAndRequest(this);\n\n // init settings defaults\n Settings.initDefaults(this);\n\n // toolbar\n Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);\n setSupportActionBar(toolbar);\n\n // show custom toolbar shadow on pre LOLLIPOP devices\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {\n View view = findViewById(R.id.toolbar_shadow);\n if (view != null) {\n view.setVisibility(View.VISIBLE);\n }\n }\n\n // drawer\n drawer = (DrawerLayout) findViewById(R.id.drawer_layout);\n ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,\n R.string.Open_navigation_drawer, R.string.Close_navigation_drawer);\n drawer.addDrawerListener(toggle);\n toggle.syncState();\n\n // navigation menu\n navigationView = (NavigationView) findViewById(R.id.nav_view);\n navigationView.setNavigationItemSelectedListener(this);\n\n // if there was a screen rotation\n int itemId;\n if (savedInstanceState != null) {\n // get saved current navigation menu item\n itemId = savedInstanceState.getInt(CURRENT_ITEM_ID);\n } else {\n // choose the fragment by activity's action\n String action = getIntent().getAction();\n action = (action == null ? \"\" : action);\n switch (action) {\n case ACTION_SMS_SEND_TO:\n // show SMS sending activity\n showSendSMSActivity();\n // switch to SMS chat fragment\n itemId = R.id.nav_sms;\n break;\n case ACTION_SMS_CONVERSATIONS:\n // switch to SMS chat fragment\n itemId = R.id.nav_sms;\n break;\n case ACTION_SETTINGS:\n // switch to settings fragment\n itemId = R.id.nav_settings;\n break;\n case ACTION_JOURNAL:\n // switch to journal fragment\n itemId = R.id.nav_journal;\n break;\n default:\n if (Settings.getBooleanValue(this, Settings.GO_TO_JOURNAL_AT_START)) {\n // switch to journal fragment\n itemId = R.id.nav_journal;\n } else {\n // switch to SMS chat fragment\n itemId = R.id.nav_sms;\n }\n break;\n }\n // switch to chosen fragment\n fragmentSwitcher.switchFragment(itemId);\n }\n\n // select navigation menu item\n selectNavigationMenuItem(itemId);\n }\n\n @Override\n public void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n outState.putInt(CURRENT_ITEM_ID, selectedMenuItemId);\n }\n\n @Override\n public void onBackPressed() {\n if (drawer.isDrawerOpen(GravityCompat.START)) {\n drawer.closeDrawer(GravityCompat.START);\n } else {\n if (!fragmentSwitcher.onBackPressed()) {\n if (!Settings.getBooleanValue(this, Settings.DONT_EXIT_ON_BACK_PRESSED)) {\n super.onBackPressed();\n }\n }\n }\n }\n\n @Override\n public boolean onNavigationItemSelected(@NonNull MenuItem item) {\n int itemId = item.getItemId();\n\n // exit item was clicked\n if (itemId == R.id.nav_exit) {\n finish();\n return true;\n }\n\n // switch to the new fragment\n fragmentSwitcher.switchFragment(itemId);\n drawer.closeDrawer(GravityCompat.START);\n\n // Normally we don't need to select navigation items manually. But in API 10\n // (and maybe some another) there is bug of menu item selection/deselection.\n // To resolve this problem we deselect the old selected item and select the\n // new one manually. And it's why we return false in the current method.\n // This way of deselection of the item was found as the most appropriate.\n // Because of some side effects of all others tried.\n selectNavigationMenuItem(itemId);\n\n return false;\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n // check for result code from the child activity (it could be a dialog-activity)\n if (requestCode == 0 && resultCode == RESULT_OK) {\n fragmentSwitcher.updateFragment();\n }\n }\n\n @Override\n public void onRequestPermissionsResult(int requestCode,\n @NonNull String permissions[],\n @NonNull int[] grantResults) {\n // process permissions results\n Permissions.onRequestPermissionsResult(requestCode, permissions, grantResults);\n // check granted permissions and notify about not granted\n Permissions.notifyIfNotGranted(this);\n }\n\n @Override\n public boolean onKeyUp(int keyCode, KeyEvent event) {\n if (keyCode == KeyEvent.KEYCODE_MENU) {\n DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);\n if (drawer.isDrawerOpen(GravityCompat.START)) {\n drawer.closeDrawer(GravityCompat.START);\n } else {\n drawer.openDrawer(GravityCompat.START);\n }\n return true;\n }\n return super.onKeyUp(keyCode, event);\n }\n\n//----------------------------------------------------------------------------\n\n private void selectNavigationMenuItem(int itemId) {\n navigationView.getMenu().clear();\n navigationView.inflateMenu(R.menu.activity_main_drawer);\n navigationView.getMenu().findItem(itemId).setChecked(true);\n // save selected item\n selectedMenuItemId = itemId;\n }\n\n // Switcher of activity's fragments\n private class FragmentSwitcher implements FragmentArguments {\n private final String CURRENT_FRAGMENT = \"CURRENT_FRAGMENT\";\n private ContactsFragment blackListFragment = new ContactsFragment();\n private ContactsFragment whiteListFragment = new ContactsFragment();\n private JournalFragment journalFragment = new JournalFragment();\n private SettingsFragment settingsFragment = new SettingsFragment();\n private InformationFragment informationFragment = new InformationFragment();\n private SMSConversationsListFragment smsFragment = new SMSConversationsListFragment();\n\n boolean onBackPressed() {\n return journalFragment.dismissSnackBar() ||\n blackListFragment.dismissSnackBar() ||\n whiteListFragment.dismissSnackBar();\n }\n\n // Switches fragment by navigation menu item\n void switchFragment(@IdRes int itemId) {\n Intent intent = getIntent();\n // passing intent's extra to the fragment\n Bundle extras = intent.getExtras();\n Bundle arguments = (extras != null ? new Bundle(extras) : new Bundle());\n switch (itemId) {\n case R.id.nav_journal:\n arguments.putString(TITLE, getString(R.string.Journal));\n switchFragment(journalFragment, arguments);\n break;\n case R.id.nav_black_list:\n arguments.putString(TITLE, getString(R.string.Black_list));\n arguments.putInt(CONTACT_TYPE, Contact.TYPE_BLACK_LIST);\n switchFragment(blackListFragment, arguments);\n break;\n case R.id.nav_white_list:\n arguments.putString(TITLE, getString(R.string.White_list));\n arguments.putInt(CONTACT_TYPE, Contact.TYPE_WHITE_LIST);\n switchFragment(whiteListFragment, arguments);\n break;\n case R.id.nav_sms:\n arguments.putString(TITLE, getString(R.string.Messaging));\n switchFragment(smsFragment, arguments);\n break;\n case R.id.nav_settings:\n arguments.putString(TITLE, getString(R.string.Settings));\n switchFragment(settingsFragment, arguments);\n break;\n default:\n arguments.putString(TITLE, getString(R.string.Information));\n switchFragment(informationFragment, arguments);\n break;\n }\n\n // remove used extras\n intent.removeExtra(LIST_POSITION);\n }\n\n // Switches to passed fragment\n private void switchFragment(Fragment fragment, Bundle arguments) {\n // replace the current showed fragment\n Fragment current = getSupportFragmentManager().findFragmentByTag(CURRENT_FRAGMENT);\n if (current != fragment) {\n fragment.setArguments(arguments);\n getSupportFragmentManager().beginTransaction().\n replace(R.id.frame_layout, fragment, CURRENT_FRAGMENT).commit();\n }\n }\n\n // Updates the current fragment\n private void updateFragment() {\n Fragment fragment = getSupportFragmentManager().findFragmentByTag(CURRENT_FRAGMENT);\n if (fragment != null) {\n FragmentTransaction ft = getSupportFragmentManager().beginTransaction();\n ft.detach(fragment).attach(fragment).commit();\n }\n }\n }\n\n // Shows the activity of SMS sending\n private void showSendSMSActivity() {\n Uri uri = getIntent().getData();\n if (uri == null) {\n return;\n }\n\n // get phone number where to send the SMS\n String ssp = uri.getSchemeSpecificPart();\n String number = ContactsAccessHelper.normalizePhoneNumber(ssp);\n if (number.isEmpty()) {\n return;\n }\n\n // find person by phone number in contacts\n String person = null;\n ContactsAccessHelper db = ContactsAccessHelper.getInstance(this);\n Contact contact = db.getContact(this, number);\n if (contact != null) {\n person = contact.name;\n }\n\n // get SMS thread id by phone number\n int threadId = db.getSMSThreadIdByNumber(this, number);\n if (threadId >= 0) {\n // get the count of unread sms of the thread\n int unreadCount = db.getSMSMessagesUnreadCountByThreadId(this, threadId);\n\n // open thread's SMS conversation activity\n Bundle arguments = new Bundle();\n arguments.putInt(FragmentArguments.THREAD_ID, threadId);\n arguments.putInt(FragmentArguments.UNREAD_COUNT, unreadCount);\n arguments.putString(FragmentArguments.CONTACT_NUMBER, number);\n String title = (person != null ? person : number);\n CustomFragmentActivity.show(this, title, SMSConversationFragment.class, arguments);\n }\n\n // open SMS sending activity\n Bundle arguments = new Bundle();\n arguments.putString(FragmentArguments.CONTACT_NAME, person);\n arguments.putString(FragmentArguments.CONTACT_NUMBER, number);\n String title = getString(R.string.New_message);\n CustomFragmentActivity.show(this, title, SMSSendFragment.class, arguments);\n }\n}", "public class SettingsArrayAdapter extends ArrayAdapter<SettingsArrayAdapter.Model> {\n private SparseArray<ViewHolder> rowsArray = new SparseArray<>();\n\n public SettingsArrayAdapter(Context context) {\n super(context, 0);\n }\n\n @Override\n @NonNull\n public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {\n // get created row by position\n View rowView;\n ViewHolder viewHolder = rowsArray.get(position);\n if (viewHolder != null) {\n rowView = viewHolder.rowView;\n } else {\n // get model by position\n Model model = getItem(position);\n // get row layout\n int layoutId = R.layout.row_settings;\n if (model != null) {\n if (model.type == Model.TITLE) {\n layoutId = R.layout.row_title;\n }\n }\n // create row\n LayoutInflater inflater = LayoutInflater.from(getContext());\n rowView = inflater.inflate(layoutId, parent, false);\n if (model != null) {\n viewHolder = new ViewHolder(rowView, model, position);\n rowsArray.put(position, viewHolder);\n }\n }\n\n return rowView;\n }\n\n // Returns true if row is checked\n public boolean isRowChecked(View view) {\n ViewHolder viewHolder = (ViewHolder) view.getTag();\n return (viewHolder != null && viewHolder.isChecked());\n }\n\n // Sets row checked\n public void setRowChecked(View view, boolean checked) {\n ViewHolder viewHolder = (ViewHolder) view.getTag();\n if (viewHolder != null) {\n viewHolder.setChecked(checked);\n }\n }\n\n // Sets row checked by property name\n public void setRowChecked(String property, boolean checked) {\n for (int i = 0; i < rowsArray.size(); i++) {\n ViewHolder viewHolder = rowsArray.valueAt(i);\n if (viewHolder.model.property != null &&\n viewHolder.model.property.equals(property)) {\n viewHolder.setChecked(checked);\n break;\n }\n }\n }\n\n // Returns property name from row's model\n @Nullable\n public String getRowProperty(View view) {\n ViewHolder viewHolder = (ViewHolder) view.getTag();\n return (viewHolder != null ? viewHolder.model.property : null);\n }\n\n private void addModel(int type, String title, String comment, String property, boolean isChecked,\n View.OnClickListener listener) {\n Model model = new Model(type, title, comment, property, isChecked, listener);\n add(model);\n }\n\n private void addModel(int type, String title, String comment, String property,\n View.OnClickListener listener) {\n boolean isChecked = (property != null && Settings.getBooleanValue(getContext(), property));\n addModel(type, title, comment, property, isChecked, listener);\n }\n\n public void addTitle(@StringRes int titleId) {\n addModel(Model.TITLE, getString(titleId), null, null, null);\n }\n\n public void addCheckbox(@StringRes int titleId, @StringRes int commentId, boolean isChecked,\n View.OnClickListener listener) {\n addModel(Model.CHECKBOX, getString(titleId), getString(commentId), null, isChecked, listener);\n }\n\n public void addCheckbox(@StringRes int titleId, @StringRes int commentId, String property,\n View.OnClickListener listener) {\n addModel(Model.CHECKBOX, getString(titleId), getString(commentId), property, listener);\n }\n\n public void addCheckbox(@StringRes int titleId, @StringRes int commentId, String property) {\n addCheckbox(titleId, commentId, property, null);\n }\n\n public void addButton(@StringRes int titleId, @StringRes int commentId, View.OnClickListener listener) {\n addButton(getString(titleId), getString(commentId), listener);\n }\n\n public void addButton(String title, String comment, View.OnClickListener listener) {\n addModel(Model.BUTTON, title, comment, null, false, listener);\n }\n\n @Nullable\n private String getString(@StringRes int stringRes) {\n return (stringRes != 0 ? getContext().getString(stringRes) : null);\n }\n\n // Row item data\n class Model {\n private static final int TITLE = 1;\n private static final int CHECKBOX = 2;\n private static final int BUTTON = 3;\n\n final int type;\n final String title;\n final String comment;\n final String property;\n final View.OnClickListener listener;\n private boolean checked;\n\n Model(int type, String title, String comment, String property,\n boolean checked, View.OnClickListener listener) {\n this.type = type;\n this.title = title;\n this.comment = comment;\n this.property = property;\n this.checked = checked;\n this.listener = listener;\n }\n\n boolean isChecked() {\n return checked;\n }\n\n boolean setChecked(boolean checked) {\n if (this.checked != checked) {\n if (property != null &&\n !Settings.setBooleanValue(getContext(), property, checked)) {\n return false;\n }\n this.checked = checked;\n }\n return true;\n }\n }\n\n // Row view holder\n private class ViewHolder {\n final Model model;\n final View rowView;\n final CheckBox checkBox;\n\n final View.OnClickListener listener = new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n applyChecked();\n if (model.listener != null) {\n model.listener.onClick(rowView);\n }\n }\n };\n\n ViewHolder(View rowView, Model model, int position) {\n Context context = getContext();\n this.rowView = rowView;\n this.model = model;\n\n rowView.setTag(this);\n\n // title\n TextView titleView = (TextView) rowView.findViewById(R.id.text_title);\n if (titleView != null) {\n titleView.setText(model.title);\n }\n\n // comment\n if (model.comment != null) {\n TextView commentView = (TextView) rowView.findViewById(R.id.text_comment);\n if (commentView != null) {\n commentView.setText(model.comment);\n commentView.setVisibility(View.VISIBLE);\n }\n }\n\n // checkbox\n if (model.type == Model.CHECKBOX) {\n checkBox = (CheckBox) rowView.findViewById(R.id.cb);\n if (checkBox != null) {\n Utils.scaleViewOnTablet(context, checkBox, R.dimen.iconScale);\n checkBox.setVisibility(View.VISIBLE);\n checkBox.setChecked(model.isChecked());\n checkBox.setOnClickListener(listener);\n }\n } else {\n checkBox = null;\n }\n\n // button\n if (model.type == Model.BUTTON) {\n rowView.setOnClickListener(listener);\n // set row's background drawable\n int drawableRes = Utils.getResourceId(context, R.attr.selector_control);\n Utils.setDrawable(context, rowView, drawableRes);\n // set row's image\n ImageView imageView = (ImageView) rowView.findViewById(R.id.image);\n if (imageView != null) {\n Utils.scaleViewOnTablet(context, imageView, R.dimen.iconScale);\n imageView.setVisibility(View.VISIBLE);\n }\n }\n\n // title\n if (model.type == Model.TITLE) {\n if (position == 0) {\n View borderView = rowView.findViewById(R.id.top_border);\n if (borderView != null) {\n borderView.setVisibility(View.GONE);\n }\n }\n }\n }\n\n void setChecked(boolean checked) {\n if (checkBox != null) {\n if (model.setChecked(checked)) {\n checkBox.setChecked(checked);\n }\n }\n }\n\n boolean isChecked() {\n return model.isChecked();\n }\n\n void applyChecked() {\n if (checkBox != null) {\n if (!model.setChecked(checkBox.isChecked())) {\n checkBox.setChecked(model.isChecked());\n }\n }\n }\n }\n}", "public class DatabaseAccessHelper extends SQLiteOpenHelper {\n private static final String TAG = DatabaseAccessHelper.class.getName();\n public static final String DATABASE_NAME = \"blacklist.db\";\n private static final int DATABASE_VERSION = 1;\n private static volatile DatabaseAccessHelper sInstance = null;\n\n @Nullable\n public static DatabaseAccessHelper getInstance(Context context) {\n if (sInstance == null) {\n synchronized (DatabaseAccessHelper.class) {\n if (sInstance == null) {\n if (Permissions.isGranted(context, Permissions.WRITE_EXTERNAL_STORAGE)) {\n sInstance = new DatabaseAccessHelper(context.getApplicationContext());\n }\n }\n }\n }\n return sInstance;\n }\n\n public static void invalidateCache() {\n if (sInstance != null) {\n synchronized (DatabaseAccessHelper.class) {\n if (sInstance != null) {\n sInstance.close();\n sInstance = null;\n }\n }\n }\n }\n\n private DatabaseAccessHelper(Context context) {\n super(context, DATABASE_NAME, null, DATABASE_VERSION);\n // helper won't create the database file until we first open it\n SQLiteDatabase db = getWritableDatabase();\n // onConfigure isn't calling in android 2.3\n db.execSQL(\"PRAGMA foreign_keys=ON\");\n }\n\n @Override\n public void onCreate(SQLiteDatabase db) {\n db.execSQL(JournalTable.Statement.CREATE);\n db.execSQL(ContactTable.Statement.CREATE);\n db.execSQL(ContactNumberTable.Statement.CREATE);\n db.execSQL(SettingsTable.Statement.CREATE);\n }\n\n @Override\n public void onUpgrade(SQLiteDatabase db, int i, int i1) {\n if (i != i1) {\n db.execSQL(\"DROP TABLE IF EXISTS \" + SettingsTable.NAME);\n db.execSQL(\"DROP TABLE IF EXISTS \" + ContactNumberTable.NAME);\n db.execSQL(\"DROP TABLE IF EXISTS \" + ContactTable.NAME);\n db.execSQL(\"DROP TABLE IF EXISTS \" + JournalTable.NAME);\n onCreate(db);\n }\n }\n\n @Override\n public void onConfigure(SQLiteDatabase db) {\n super.onConfigure(db);\n db.execSQL(\"PRAGMA foreign_keys=ON\");\n }\n\n//----------------------------------------------------------------\n\n // Checks whether file is SQLite file\n public static boolean isSQLiteFile(String fileName) {\n File file = new File(fileName);\n if (!file.exists() || !file.canRead()) {\n return false;\n }\n\n FileReader reader = null;\n try {\n reader = new FileReader(file);\n char[] buffer = new char[16];\n if (reader.read(buffer, 0, 16) > 0) {\n String str = String.valueOf(buffer);\n return str.equals(\"SQLite format 3\\u0000\");\n }\n } catch (Exception e) {\n Log.w(TAG, e);\n } finally {\n Utils.close(reader);\n }\n return false;\n }\n\n // Closes cursor if it is empty and returns false\n private boolean validate(Cursor cursor) {\n if (cursor == null || cursor.isClosed()) return false;\n if (cursor.getCount() == 0) {\n cursor.close();\n return false;\n }\n return true;\n }\n\n // Common statements\n private static class Common {\n /**\n * Creates 'IN part' of 'WHERE' clause.\n * If \"all\" is true - includes all items, except of specified in list.\n * Else includes all items specified in list.\n */\n @Nullable\n static String getInClause(String column, boolean all, List<String> items) {\n if (all) {\n if (items.isEmpty()) {\n // include all items\n return null;\n } else {\n // include all items except of specified\n String args = joinStrings(items, \", \");\n return column + \" NOT IN ( \" + args + \" ) \";\n }\n }\n // include all specified items\n String args = joinStrings(items, \", \");\n return column + \" IN ( \" + args + \" ) \";\n }\n\n /**\n * Creates 'LIKE part' of 'WHERE' clause\n */\n\n @Nullable\n static String getLikeClause(String column, String filter) {\n return (filter == null ? null :\n column + \" LIKE '%\" + filter + \"%' \");\n }\n\n /**\n * Concatenates passed clauses with 'AND' operator\n */\n static String concatClauses(String[] clauses) {\n StringBuilder sb = new StringBuilder();\n for (String clause : clauses) {\n if (TextUtils.isEmpty(clause)) continue;\n if (sb.length() > 0) sb.append(\" AND \");\n sb.append(clause);\n }\n return sb.toString();\n }\n\n static String joinStrings(List<String> list, String separator) {\n StringBuilder sb = new StringBuilder();\n boolean first = true;\n for (String item : list) {\n if (first)\n first = false;\n else\n sb.append(separator);\n\n sb.append(item);\n }\n return sb.toString();\n }\n }\n\n // Journal table scheme\n private static class JournalTable {\n static final String NAME = \"journal\";\n\n static class Column {\n static final String ID = \"_id\";\n static final String TIME = \"time\";\n static final String CALLER = \"caller\";\n static final String NUMBER = \"number\";\n static final String TEXT = \"text\";\n }\n\n static class Statement {\n static final String CREATE =\n \"CREATE TABLE \" + JournalTable.NAME +\n \"(\" +\n Column.ID + \" INTEGER PRIMARY KEY NOT NULL, \" +\n Column.TIME + \" INTEGER NOT NULL, \" +\n Column.CALLER + \" TEXT NOT NULL, \" +\n Column.NUMBER + \" TEXT, \" +\n Column.TEXT + \" TEXT \" +\n \")\";\n\n static final String SELECT_FIRST_PART =\n \"SELECT \" +\n Column.ID + \", \" +\n Column.TIME +\n \" FROM \" + JournalTable.NAME +\n \" ORDER BY \" + Column.TIME +\n \" DESC\";\n\n static final String SELECT_LAST_PART_BY_ID =\n \"SELECT \" +\n Column.CALLER + \", \" +\n Column.NUMBER + \", \" +\n Column.TEXT +\n \" FROM \" + JournalTable.NAME +\n \" WHERE _id = ? \";\n\n static final String SELECT_FIRST_PART_BY_FILTER =\n \"SELECT * \" +\n \" FROM \" + JournalTable.NAME +\n \" WHERE \" + Column.CALLER + \" LIKE ? \" +\n \" OR \" + Column.TEXT + \" LIKE ? \" +\n \" ORDER BY \" + Column.TIME +\n \" DESC\";\n }\n }\n\n // Journal table record\n public static class JournalRecord {\n public final long id;\n public final long time;\n public final String caller;\n public final String number;\n public final String text;\n\n JournalRecord(long id, long time, @NonNull String caller,\n String number, String text) {\n this.id = id;\n this.time = time;\n this.caller = caller;\n this.number = number;\n this.text = text;\n }\n }\n\n // Journal record cursor wrapper\n public class JournalRecordCursorWrapper extends CursorWrapper {\n private final int ID;\n private final int TIME;\n\n JournalRecordCursorWrapper(Cursor cursor) {\n super(cursor);\n cursor.moveToFirst();\n ID = cursor.getColumnIndex(JournalTable.Column.ID);\n TIME = cursor.getColumnIndex(JournalTable.Column.TIME);\n }\n\n public JournalRecord getJournalRecord() {\n long id = getLong(ID);\n long time = getLong(TIME);\n String[] parts = getJournalRecordPartsById(id);\n return new JournalRecord(id, time, parts[0], parts[1], parts[2]);\n }\n\n public long getTime(int position) {\n long time = 0;\n if (0 <= position && position < getCount()) {\n int curPosition = getPosition();\n if (moveToPosition(position)) {\n time = getLong(TIME);\n moveToPosition(curPosition);\n }\n }\n return time;\n }\n }\n\n // Selects journal record's parts by id\n private String[] getJournalRecordPartsById(long id) {\n SQLiteDatabase db = getReadableDatabase();\n Cursor cursor = db.rawQuery(JournalTable.Statement.SELECT_LAST_PART_BY_ID,\n new String[]{String.valueOf(id)});\n\n String[] parts;\n if (validate(cursor)) {\n cursor.moveToFirst();\n final int CALLER = cursor.getColumnIndex(JournalTable.Column.CALLER);\n final int NUMBER = cursor.getColumnIndex(JournalTable.Column.NUMBER);\n final int TEXT = cursor.getColumnIndex(JournalTable.Column.TEXT);\n parts = new String[]{\n cursor.getString(CALLER),\n cursor.getString(NUMBER),\n cursor.getString(TEXT)};\n cursor.close();\n } else {\n parts = new String[]{\"?\", \"?\", \"?\"};\n }\n\n return parts;\n }\n\n // Selects all journal records\n @Nullable\n private JournalRecordCursorWrapper getJournalRecords() {\n SQLiteDatabase db = getReadableDatabase();\n Cursor cursor = db.rawQuery(JournalTable.Statement.SELECT_FIRST_PART, null);\n\n return (validate(cursor) ? new JournalRecordCursorWrapper(cursor) : null);\n }\n\n // Selects journal records filtered with passed filter\n @Nullable\n public JournalRecordCursorWrapper getJournalRecords(@Nullable String filter) {\n if (filter == null) {\n return getJournalRecords();\n }\n SQLiteDatabase db = getReadableDatabase();\n Cursor cursor = db.rawQuery(JournalTable.Statement.SELECT_FIRST_PART_BY_FILTER,\n new String[]{\"%\" + filter + \"%\", \"%\" + filter + \"%\"});\n\n return (validate(cursor) ? new JournalRecordCursorWrapper(cursor) : null);\n }\n\n // Deletes all records specified in container and fit to filter\n public int deleteJournalRecords(IdentifiersContainer contactIds, @Nullable String filter) {\n if (contactIds.isEmpty()) return 0;\n\n boolean all = contactIds.isAll();\n List<String> ids = contactIds.getIdentifiers(new LinkedList<String>());\n\n // build 'WHERE' clause\n String clause = Common.concatClauses(new String[]{\n Common.getLikeClause(JournalTable.Column.CALLER, filter),\n Common.getInClause(JournalTable.Column.ID, all, ids)\n });\n\n // delete records\n SQLiteDatabase db = getWritableDatabase();\n return db.delete(JournalTable.NAME, clause, null);\n }\n\n // Deletes record by specified id\n public boolean deleteJournalRecord(long id) {\n SQLiteDatabase db = getWritableDatabase();\n return (db.delete(JournalTable.NAME, JournalTable.Column.ID + \" = \" + id, null) > 0);\n }\n\n // Writes journal record\n public long addJournalRecord(long time, @NonNull String caller,\n String number, String text) {\n if (number != null && number.equals(caller)) {\n number = null;\n }\n SQLiteDatabase db = getWritableDatabase();\n ContentValues values = new ContentValues();\n values.put(JournalTable.Column.TIME, time);\n values.put(JournalTable.Column.CALLER, caller);\n values.put(JournalTable.Column.NUMBER, number);\n values.put(JournalTable.Column.TEXT, text);\n return db.insert(JournalTable.NAME, null, values);\n }\n\n//----------------------------------------------------------------\n\n // Contact number table scheme\n private static class ContactNumberTable {\n static final String NAME = \"number\";\n\n static class Column {\n static final String ID = \"_id\";\n static final String NUMBER = \"number\";\n static final String TYPE = \"type\";\n static final String CONTACT_ID = \"contact_id\";\n }\n\n static class Statement {\n static final String CREATE =\n \"CREATE TABLE \" + ContactNumberTable.NAME +\n \"(\" +\n Column.ID + \" INTEGER PRIMARY KEY NOT NULL, \" +\n Column.NUMBER + \" TEXT NOT NULL, \" +\n Column.TYPE + \" INTEGER NOT NULL, \" +\n Column.CONTACT_ID + \" INTEGER NOT NULL, \" +\n \"FOREIGN KEY(\" + Column.CONTACT_ID + \") REFERENCES \" +\n ContactTable.NAME + \"(\" + ContactTable.Column.ID + \")\" +\n \" ON DELETE CASCADE \" +\n \")\";\n\n static final String SELECT_BY_CONTACT_ID =\n \"SELECT * \" +\n \" FROM \" + ContactNumberTable.NAME +\n \" WHERE \" + Column.CONTACT_ID + \" = ? \" +\n \" ORDER BY \" + Column.NUMBER +\n \" ASC\";\n\n static final String SELECT_BY_TYPE_AND_NUMBER =\n \"SELECT * \" +\n \" FROM \" + ContactNumberTable.NAME +\n \" WHERE \" + Column.TYPE + \" = ? \" +\n \" AND \" + Column.NUMBER + \" = ? \";\n\n static final String SELECT_BY_NUMBER =\n \"SELECT * \" +\n \" FROM \" + ContactNumberTable.NAME +\n \" WHERE (\" +\n Column.TYPE + \" = \" + ContactNumber.TYPE_EQUALS + \" AND \" +\n \" ? = \" + Column.NUMBER + \") OR (\" +\n Column.TYPE + \" = \" + ContactNumber.TYPE_STARTS + \" AND \" +\n \" ? LIKE \" + Column.NUMBER + \"||'%') OR (\" +\n Column.TYPE + \" = \" + ContactNumber.TYPE_ENDS + \" AND \" +\n \" ? LIKE '%'||\" + Column.NUMBER + \") OR (\" +\n Column.TYPE + \" = \" + ContactNumber.TYPE_CONTAINS + \" AND \" +\n \" ? LIKE '%'||\" + Column.NUMBER + \"||'%')\";\n }\n }\n\n // ContactsNumber table item\n public static class ContactNumber {\n public static final int TYPE_EQUALS = 0;\n public static final int TYPE_CONTAINS = 1;\n public static final int TYPE_STARTS = 2;\n public static final int TYPE_ENDS = 3;\n\n public final long id;\n public final String number;\n public final int type;\n public final long contactId;\n\n public ContactNumber(long id, @NonNull String number, long contactId) {\n this(id, number, TYPE_EQUALS, contactId);\n }\n\n public ContactNumber(long id, @NonNull String number, int type, long contactId) {\n this.id = id;\n this.number = number;\n this.type = type;\n this.contactId = contactId;\n }\n }\n\n // ContactsNumber item cursor wrapper\n private class ContactNumberCursorWrapper extends CursorWrapper {\n private final int ID;\n private final int NUMBER;\n private final int TYPE;\n private final int CONTACT_ID;\n\n ContactNumberCursorWrapper(Cursor cursor) {\n super(cursor);\n cursor.moveToFirst();\n ID = cursor.getColumnIndex(ContactNumberTable.Column.ID);\n NUMBER = cursor.getColumnIndex(ContactNumberTable.Column.NUMBER);\n TYPE = cursor.getColumnIndex(ContactNumberTable.Column.TYPE);\n CONTACT_ID = cursor.getColumnIndex(ContactNumberTable.Column.CONTACT_ID);\n }\n\n ContactNumber getNumber() {\n long id = getLong(ID);\n String number = getString(NUMBER);\n int type = getInt(TYPE);\n long contactId = getLong(CONTACT_ID);\n return new ContactNumber(id, number, type, contactId);\n }\n }\n\n // Deletes contact number by id\n private int deleteContactNumber(long id) {\n SQLiteDatabase db = getWritableDatabase();\n return db.delete(ContactNumberTable.NAME,\n ContactNumberTable.Column.ID + \" = \" + id,\n null);\n }\n\n // Selects contact numbers by contact id\n @Nullable\n private ContactNumberCursorWrapper getContactNumbersByContactId(long contactId) {\n SQLiteDatabase db = getReadableDatabase();\n Cursor cursor = db.rawQuery(\n ContactNumberTable.Statement.SELECT_BY_CONTACT_ID,\n new String[]{String.valueOf(contactId)});\n\n return (validate(cursor) ? new ContactNumberCursorWrapper(cursor) : null);\n }\n\n // Searches contact numbers by number value\n @Nullable\n private ContactNumberCursorWrapper getContactNumbersByNumber(String number) {\n SQLiteDatabase db = getReadableDatabase();\n Cursor cursor = db.rawQuery(\n ContactNumberTable.Statement.SELECT_BY_NUMBER,\n new String[]{number, number, number, number});\n\n return (validate(cursor) ? new ContactNumberCursorWrapper(cursor) : null);\n }\n\n // Searches contact numbers by type and value\n @Nullable\n private ContactNumberCursorWrapper getContactNumbersByTypeAndNumber(int numberType, String number) {\n SQLiteDatabase db = getReadableDatabase();\n Cursor cursor = db.rawQuery(\n ContactNumberTable.Statement.SELECT_BY_TYPE_AND_NUMBER,\n new String[]{String.valueOf(numberType), number});\n\n return (validate(cursor) ? new ContactNumberCursorWrapper(cursor) : null);\n }\n\n // Searches contact numbers by number value\n private List<ContactNumber> getContactNumbers(String number) {\n List<ContactNumber> list = new LinkedList<>();\n ContactNumberCursorWrapper cursor = getContactNumbersByNumber(number);\n if (cursor != null) {\n do {\n list.add(cursor.getNumber());\n } while (cursor.moveToNext());\n cursor.close();\n }\n\n return list;\n }\n\n // Searches contact numbers by numbers types and values\n // This method is mainly needed for retrieving actual ContactNumber.id and/or ContactNumber.contactId\n private List<ContactNumber> getContactNumbers(List<ContactNumber> numbers) {\n List<ContactNumber> list = new LinkedList<>();\n for (ContactNumber number : numbers) {\n ContactNumberCursorWrapper cursor =\n getContactNumbersByTypeAndNumber(number.type, number.number);\n if (cursor != null) {\n do {\n list.add(cursor.getNumber());\n } while (cursor.moveToNext());\n cursor.close();\n }\n }\n\n return list;\n }\n//----------------------------------------------------------------\n\n // Table of contacts (black/white lists)\n private static class ContactTable {\n static final String NAME = \"contact\";\n\n static class Column {\n static final String ID = \"_id\";\n static final String NAME = \"name\";\n static final String TYPE = \"type\"; // black/white type\n }\n\n static class Statement {\n static final String CREATE =\n \"CREATE TABLE \" + ContactTable.NAME +\n \"(\" +\n Column.ID + \" INTEGER PRIMARY KEY NOT NULL, \" +\n Column.NAME + \" TEXT NOT NULL, \" +\n Column.TYPE + \" INTEGER NOT NULL DEFAULT 0 \" +\n \")\";\n\n static final String SELECT_BY_TYPE =\n \"SELECT * \" +\n \" FROM \" + ContactTable.NAME +\n \" WHERE \" + Column.TYPE + \" = ? \" +\n \" ORDER BY \" + Column.NAME +\n \" ASC\";\n\n static final String SELECT_BY_NAME =\n \"SELECT * \" +\n \" FROM \" + ContactTable.NAME +\n \" WHERE \" + Column.NAME + \" = ? \";\n\n static final String SELECT_BY_TYPE_AND_NAME =\n \"SELECT * \" +\n \" FROM \" + ContactTable.NAME +\n \" WHERE \" + Column.TYPE + \" = ? \" +\n \" AND \" + Column.NAME + \" = ? \";\n\n static final String SELECT_BY_ID =\n \"SELECT * \" +\n \" FROM \" + ContactTable.NAME +\n \" WHERE \" + Column.ID + \" = ? \";\n\n static final String SELECT_BY_FILTER =\n \"SELECT * \" +\n \" FROM \" + ContactTable.NAME +\n \" WHERE \" + Column.TYPE + \" = ? \" +\n \" AND \" + Column.NAME + \" LIKE ? \" +\n \" ORDER BY \" + Column.NAME +\n \" ASC\";\n }\n }\n\n // The contact\n public static class Contact {\n public static final int TYPE_BLACK_LIST = 1;\n public static final int TYPE_WHITE_LIST = 2;\n\n public final long id;\n public final String name;\n public final int type;\n public final List<ContactNumber> numbers;\n\n Contact(long id, @NonNull String name, int type, @NonNull List<ContactNumber> numbers) {\n this.id = id;\n this.name = name;\n this.type = type;\n this.numbers = numbers;\n }\n }\n\n // Source of the contact\n public interface ContactSource {\n Contact getContact();\n }\n\n // Contact cursor wrapper\n public class ContactCursorWrapper extends CursorWrapper implements ContactSource {\n private final int ID;\n private final int NAME;\n private final int TYPE;\n\n ContactCursorWrapper(Cursor cursor) {\n super(cursor);\n cursor.moveToFirst();\n ID = cursor.getColumnIndex(ContactTable.Column.ID);\n NAME = getColumnIndex(ContactTable.Column.NAME);\n TYPE = getColumnIndex(ContactTable.Column.TYPE);\n }\n\n @Override\n public Contact getContact() {\n return getContact(true);\n }\n\n Contact getContact(boolean withNumbers) {\n long id = getLong(ID);\n String name = getString(NAME);\n int type = getInt(TYPE);\n\n List<ContactNumber> numbers = new LinkedList<>();\n if (withNumbers) {\n ContactNumberCursorWrapper cursor = getContactNumbersByContactId(id);\n if (cursor != null) {\n do {\n numbers.add(cursor.getNumber());\n } while (cursor.moveToNext());\n cursor.close();\n }\n }\n\n return new Contact(id, name, type, numbers);\n }\n }\n\n // Searches all contacts by type\n @Nullable\n private ContactCursorWrapper getContacts(int contactType) {\n SQLiteDatabase db = getReadableDatabase();\n Cursor cursor = db.rawQuery(\n ContactTable.Statement.SELECT_BY_TYPE,\n new String[]{String.valueOf(contactType)});\n\n return (validate(cursor) ? new ContactCursorWrapper(cursor) : null);\n }\n\n // Searches all contacts by type filtering by passed filter\n @Nullable\n public ContactCursorWrapper getContacts(int contactType, @Nullable String filter) {\n if (filter == null) {\n return getContacts(contactType);\n }\n SQLiteDatabase db = getReadableDatabase();\n Cursor cursor = db.rawQuery(\n ContactTable.Statement.SELECT_BY_FILTER,\n new String[]{String.valueOf(contactType), \"%\" + filter + \"%\"});\n\n return (validate(cursor) ? new ContactCursorWrapper(cursor) : null);\n }\n\n // Searches contact by name\n @Nullable\n public ContactCursorWrapper getContact(String contactName) {\n SQLiteDatabase db = getReadableDatabase();\n Cursor cursor = db.rawQuery(\n ContactTable.Statement.SELECT_BY_NAME,\n new String[]{contactName});\n\n return (validate(cursor) ? new ContactCursorWrapper(cursor) : null);\n }\n\n // Searches contact by type and name\n @Nullable\n private ContactCursorWrapper getContact(int contactType, String contactName) {\n SQLiteDatabase db = getReadableDatabase();\n Cursor cursor = db.rawQuery(\n ContactTable.Statement.SELECT_BY_TYPE_AND_NAME,\n new String[]{String.valueOf(contactType), contactName});\n\n return (validate(cursor) ? new ContactCursorWrapper(cursor) : null);\n }\n\n // Searches contact by id\n @Nullable\n public ContactCursorWrapper getContact(long contactId) {\n SQLiteDatabase db = getReadableDatabase();\n Cursor cursor = db.rawQuery(\n ContactTable.Statement.SELECT_BY_ID,\n new String[]{String.valueOf(contactId)});\n\n return (validate(cursor) ? new ContactCursorWrapper(cursor) : null);\n }\n\n // Adds a new contact and returns contact id or -1 on error\n private long addContact(int contactType, @NonNull String contactName) {\n SQLiteDatabase db = getWritableDatabase();\n ContentValues values = new ContentValues();\n values.put(ContactTable.Column.NAME, contactName);\n values.put(ContactTable.Column.TYPE, contactType);\n return db.insert(ContactTable.NAME, null, values);\n }\n\n // Adds a contact with numbers and returns contact id or -1 on error.\n // If adding numbers already belong to some contacts - removes them at first.\n public long addContact(int contactType, @NonNull String contactName, @NonNull List<ContactNumber> numbers) {\n if (numbers.size() == 0) return -1;\n\n long contactId = -1;\n SQLiteDatabase db = getWritableDatabase();\n db.beginTransaction();\n try {\n // delete existing numbers from contacts\n deleteContactNumbers(numbers);\n\n // try to find existing contact with the same name and type\n ContactCursorWrapper cursor = getContact(contactType, contactName);\n if (cursor != null) {\n Contact contact = cursor.getContact(false);\n contactId = contact.id;\n cursor.close();\n }\n\n // contact was not found\n if (contactId < 0) {\n // add a new one\n contactId = addContact(contactType, contactName);\n }\n\n // add numbers to the contact\n if (contactId >= 0) {\n for (ContactNumber number : numbers) {\n ContentValues values = new ContentValues();\n values.put(ContactNumberTable.Column.NUMBER, number.number);\n values.put(ContactNumberTable.Column.TYPE, number.type);\n values.put(ContactNumberTable.Column.CONTACT_ID, contactId);\n if (db.insert(ContactNumberTable.NAME, null, values) < 0) {\n return -1;\n }\n }\n db.setTransactionSuccessful();\n }\n } finally {\n db.endTransaction();\n }\n\n return contactId;\n }\n\n // Deletes contact numbers if they exist.\n // After that deletes parent contacts if they are empty.\n private void deleteContactNumbers(List<ContactNumber> numbers) {\n // get full initialized contact numbers by type and value\n List<ContactNumber> contactNumbers = getContactNumbers(numbers);\n\n // delete found numbers and collect ids of parent contacts\n Set<Long> contactIds = new TreeSet<>();\n for (ContactNumber number : contactNumbers) {\n if (deleteContactNumber(number.id) > 0) {\n contactIds.add(number.contactId);\n }\n }\n\n // check contacts consistency\n for (Long contactId : contactIds) {\n // if contact does not have any number\n ContactNumberCursorWrapper cursor = getContactNumbersByContactId(contactId);\n if (cursor == null) {\n // delete it\n deleteContact(contactId);\n } else {\n cursor.close();\n }\n }\n }\n\n // Adds contact with single number\n public long addContact(int contactType, @NonNull String contactName, @NonNull ContactNumber contactNumber) {\n List<ContactNumber> numbers = new LinkedList<>();\n numbers.add(contactNumber);\n return addContact(contactType, contactName, numbers);\n }\n\n // Adds contact with single number with default type\n public long addContact(int contactType, @NonNull String contactName, @Nullable String number) {\n if (number == null) {\n number = contactName;\n }\n List<ContactNumber> numbers = new LinkedList<>();\n numbers.add(new ContactNumber(0, number, 0));\n return addContact(contactType, contactName, numbers);\n }\n\n // Deletes all contacts which are specified in container with specified type\n public int deleteContacts(int contactType, IdentifiersContainer contactIds, @Nullable String filter) {\n if (contactIds.isEmpty()) return 0;\n\n boolean all = contactIds.isAll();\n List<String> ids = contactIds.getIdentifiers(new LinkedList<String>());\n\n // build 'WHERE' clause\n String clause = Common.concatClauses(new String[]{\n ContactTable.Column.TYPE + \" = \" + contactType,\n Common.getLikeClause(ContactTable.Column.NAME, filter),\n Common.getInClause(ContactTable.Column.ID, all, ids)\n });\n\n // delete contacts\n SQLiteDatabase db = getWritableDatabase();\n return db.delete(ContactTable.NAME, clause, null);\n }\n\n // Deletes contact by id\n public int deleteContact(long contactId) {\n SQLiteDatabase db = getWritableDatabase();\n return db.delete(ContactTable.NAME,\n ContactTable.Column.ID + \" = \" + contactId,\n null);\n }\n\n // Searches contacts by contact numbers (retrieving them by ContactNumber.contactId)\n private List<Contact> getContacts(List<ContactNumber> numbers, boolean withNumbers) {\n List<Contact> contacts = new LinkedList<>();\n for (ContactNumber contactNumber : numbers) {\n ContactCursorWrapper cursor = getContact(contactNumber.contactId);\n if (cursor != null) {\n contacts.add(cursor.getContact(withNumbers));\n cursor.close();\n }\n }\n return contacts;\n }\n\n // Searches contacts by contact number\n public List<Contact> getContacts(String number, boolean withNumbers) {\n List<ContactNumber> numbers = getContactNumbers(number);\n return getContacts(numbers, withNumbers);\n }\n\n // Searches contact by name and number\n @Nullable\n public Contact getContact(String contactName, String number) {\n List<Contact> contacts = getContacts(number, false);\n for (Contact contact : contacts) {\n if (contact.name.equals(contactName)) {\n return contact;\n }\n }\n return null;\n }\n\n // Moves the contact to the opposite type list\n public long moveContact(Contact contact) {\n int type = reverseContactType(contact.type);\n return addContact(type, contact.name, contact.numbers);\n }\n\n // Reverses passed contact type\n private int reverseContactType(int type) {\n return (type == Contact.TYPE_BLACK_LIST ?\n Contact.TYPE_WHITE_LIST :\n Contact.TYPE_BLACK_LIST);\n }\n\n//----------------------------------------------------------------\n\n // Table of settings\n private static class SettingsTable {\n static final String NAME = \"settings\";\n\n static class Column {\n static final String ID = \"_id\";\n static final String NAME = \"name\";\n static final String VALUE = \"value\";\n }\n\n static class Statement {\n static final String CREATE =\n \"CREATE TABLE \" + SettingsTable.NAME +\n \"(\" +\n Column.ID + \" INTEGER PRIMARY KEY NOT NULL, \" +\n Column.NAME + \" TEXT NOT NULL, \" +\n Column.VALUE + \" TEXT \" +\n \")\";\n\n static final String SELECT_BY_NAME =\n \"SELECT * \" +\n \" FROM \" + SettingsTable.NAME +\n \" WHERE \" + Column.NAME + \" = ? \";\n }\n }\n\n // Settings item\n private class SettingsItem {\n final long id;\n final String name;\n final String value;\n\n SettingsItem(long id, String name, String value) {\n this.id = id;\n this.name = name;\n this.value = value;\n }\n }\n\n // SettingsItem cursor wrapper\n private class SettingsItemCursorWrapper extends CursorWrapper {\n private final int ID;\n private final int NAME;\n private final int VALUE;\n\n SettingsItemCursorWrapper(Cursor cursor) {\n super(cursor);\n cursor.moveToFirst();\n ID = cursor.getColumnIndex(SettingsTable.Column.ID);\n NAME = cursor.getColumnIndex(SettingsTable.Column.NAME);\n VALUE = cursor.getColumnIndex(SettingsTable.Column.VALUE);\n }\n\n SettingsItem getSettings() {\n long id = getLong(ID);\n String name = getString(NAME);\n String value = getString(VALUE);\n return new SettingsItem(id, name, value);\n }\n }\n\n // Selects settings by name\n @Nullable\n private SettingsItemCursorWrapper getSettings(@NonNull String name) {\n SQLiteDatabase db = getReadableDatabase();\n Cursor cursor = db.rawQuery(\n SettingsTable.Statement.SELECT_BY_NAME,\n new String[]{name});\n\n return (validate(cursor) ? new SettingsItemCursorWrapper(cursor) : null);\n }\n\n // Selects value of settings by name\n @Nullable\n public String getSettingsValue(@NonNull String name) {\n SettingsItemCursorWrapper cursor = getSettings(name);\n if (cursor != null) {\n SettingsItem item = cursor.getSettings();\n cursor.close();\n return item.value;\n }\n return null;\n }\n\n // Sets value of settings with specified name\n public boolean setSettingsValue(@NonNull String name, @NonNull String value) {\n SQLiteDatabase db = getWritableDatabase();\n ContentValues values = new ContentValues();\n values.put(SettingsTable.Column.VALUE, value);\n // try to update value\n int n = db.update(SettingsTable.NAME,\n values,\n SettingsTable.Column.NAME + \" = ? \",\n new String[]{name});\n if (n == 0) {\n // try to add name/value\n values.put(SettingsTable.Column.NAME, name);\n return db.insert(SettingsTable.NAME, null, values) >= 0;\n }\n\n return true;\n }\n}", "public class DefaultSMSAppHelper {\n\n public static boolean isAvailable() {\n return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;\n }\n\n public static void updateState(Context context) {\n boolean ready = isDefault(context);\n enableSMSReceiving(context, ready);\n }\n\n public static void enableSMSReceiving(Context context, boolean enable) {\n int state = (enable ?\n PackageManager.COMPONENT_ENABLED_STATE_ENABLED :\n PackageManager.COMPONENT_ENABLED_STATE_DISABLED);\n PackageManager packageManager = context.getPackageManager();\n ComponentName componentName = new ComponentName(context, SMSBroadcastReceiver.class);\n packageManager.setComponentEnabledSetting(\n componentName,\n state,\n PackageManager.DONT_KILL_APP);\n }\n\n @TargetApi(19)\n public static boolean isDefault(Context context) {\n if (!isAvailable()) return true;\n String myPackage = context.getPackageName();\n String smsPackage = Telephony.Sms.getDefaultSmsPackage(context);\n return (smsPackage != null && smsPackage.equals(myPackage));\n }\n\n @TargetApi(19)\n public static void askForDefaultAppChange(Fragment fragment, int requestCode) {\n if (!isAvailable()) return;\n Context context = fragment.getContext().getApplicationContext();\n String packageName;\n // current app package is already set as default\n if (isDefault(context)) {\n // get previously saved app package as default\n packageName = Settings.getStringValue(context, Settings.DEFAULT_SMS_APP_NATIVE_PACKAGE);\n } else {\n // get blacklist app package as default\n packageName = context.getPackageName();\n // save current default sms app package to the settings\n String nativePackage = Telephony.Sms.getDefaultSmsPackage(context);\n if (nativePackage != null) {\n Settings.setStringValue(context, Settings.DEFAULT_SMS_APP_NATIVE_PACKAGE, nativePackage);\n }\n }\n // start sms app change dialog\n askForDefaultAppChange(fragment, packageName, requestCode);\n }\n\n @TargetApi(19)\n private static void askForDefaultAppChange(Fragment fragment, @Nullable String packageName, int requestCode) {\n if (!isAvailable()) return;\n Intent intent;\n if (packageName == null) {\n String action;\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {\n action = android.provider.Settings.ACTION_MANAGE_DEFAULT_APPS_SETTINGS;\n } else {\n action = android.provider.Settings.ACTION_WIRELESS_SETTINGS;\n }\n intent = new Intent(action);\n } else {\n intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);\n intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, packageName);\n }\n fragment.startActivityForResult(intent, requestCode);\n }\n}", "public class DialogBuilder {\n private Context context;\n private View view;\n private Dialog dialog;\n private LinearLayout listLayout;\n private ButtonsBar buttonsBar;\n\n public DialogBuilder(@NonNull Context context) {\n this.context = context;\n this.listLayout = (LinearLayout) getView().findViewById(R.id.items_list);\n }\n\n /**\n * Sets the title of the dialog\n **/\n public DialogBuilder setTitle(@StringRes int titleId) {\n String title = context.getString(titleId);\n return setTitle(title);\n }\n\n /**\n * Sets the title of the dialog\n **/\n public DialogBuilder setTitle(String title) {\n TextView titleView = (TextView) getView().findViewById(R.id.dialog_title);\n titleView.setText(title);\n titleView.setVisibility(View.VISIBLE);\n View lineView = getView().findViewById(R.id.title_line);\n lineView.setVisibility(View.VISIBLE);\n return this;\n }\n\n /**\n * Sets the title of the dialog\n **/\n public DialogBuilder setTitle(String title, int maxLines) {\n TextView titleView = (TextView) getView().findViewById(R.id.dialog_title);\n titleView.setText(title);\n titleView.setMaxLines(maxLines);\n titleView.setEllipsize(TextUtils.TruncateAt.END);\n if (maxLines == 1) {\n titleView.setSingleLine(true);\n }\n titleView.setVisibility(View.VISIBLE);\n View lineView = getView().findViewById(R.id.title_line);\n lineView.setVisibility(View.VISIBLE);\n return this;\n }\n\n /**\n * Adds the new item to the list with title only\n **/\n public DialogBuilder addItem(@StringRes int titleId) {\n return addItem(-1, titleId, null, null);\n }\n\n /**\n * Adds the new item to the list with title and click listener\n **/\n public DialogBuilder addItem(@StringRes int titleId, View.OnClickListener listener) {\n return addItem(-1, titleId, null, listener);\n }\n\n /**\n * Adds the new item to the list with id, title, and click listener\n **/\n public DialogBuilder addItem(int id, @StringRes int titleId, View.OnClickListener listener) {\n return addItem(id, titleId, null, listener);\n }\n\n /**\n * Adds the new item to the list with id, title, tag, and click listener\n **/\n public DialogBuilder addItem(int id, @StringRes int titleId, Object tag, View.OnClickListener listener) {\n String title = context.getString(titleId);\n return addItem(id, title, tag, listener);\n }\n\n /**\n * Adds the new item to the list with title and click listener\n **/\n public DialogBuilder addItem(String title, final View.OnClickListener listener) {\n return addItem(-1, title, null, listener);\n }\n\n /**\n * Adds the new item to the list with id, title and click listener\n **/\n public DialogBuilder addItem(int id, String title, final View.OnClickListener listener) {\n return addItem(id, title, null, listener);\n }\n\n /**\n * Adds the new item to the list with id, title, tag and click listener\n **/\n public DialogBuilder addItem(int id, String title, Object tag, final View.OnClickListener listener) {\n // inflate row using default layout\n LayoutInflater inflater = LayoutInflater.from(context);\n View itemView = inflater.inflate(R.layout.row_item_dialog, null);\n itemView.setId(id);\n itemView.setTag(tag);\n\n // if there are some rows above\n if (listLayout.getChildCount() > 0) {\n // show top border\n View borderView = itemView.findViewById(R.id.item_top_border);\n if (borderView != null) {\n borderView.setVisibility(View.VISIBLE);\n }\n }\n\n if (listener != null) {\n ImageView imageView = (ImageView) itemView.findViewById(R.id.item_image);\n Utils.scaleViewOnTablet(context, imageView, R.dimen.iconScale);\n imageView.setVisibility(View.VISIBLE);\n }\n\n // wrap on click listener\n itemView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n getDialog().dismiss();\n if (listener != null) {\n listener.onClick(v);\n }\n }\n });\n\n TextView titleView = (TextView) itemView.findViewById(R.id.item_title);\n titleView.setText(title);\n\n return addItem(itemView);\n }\n\n /**\n * Adds the new item to the list\n **/\n public DialogBuilder addItem(View itemView) {\n listLayout.addView(itemView);\n return this;\n }\n\n /**\n * Adds the new edit to the list with id, text and hint\n **/\n public DialogBuilder addEdit(int id, String text, String hint) {\n // inflate row using default layout\n LayoutInflater inflater = LayoutInflater.from(context);\n View itemView = inflater.inflate(R.layout.row_edit_dialog, null);\n // if there are some rows above\n if (listLayout.getChildCount() > 0) {\n // show top border\n View borderView = itemView.findViewById(R.id.item_top_border);\n if (borderView != null) {\n borderView.setVisibility(View.VISIBLE);\n }\n }\n // setup edit\n EditText editText = (EditText) itemView.findViewById(R.id.edit_text);\n editText.setText(text);\n editText.setSelection(editText.getText().length());\n editText.setHint(hint);\n editText.setId(id);\n\n return addItem(itemView);\n }\n\n /**\n * Adds bottom-left button to the dialog\n **/\n public DialogBuilder addButtonLeft(String title,\n DialogInterface.OnClickListener listener) {\n return addButton(R.id.button_left, title, listener);\n }\n\n /**\n * Adds bottom-right button to the dialog\n **/\n public DialogBuilder addButtonRight(String title,\n DialogInterface.OnClickListener listener) {\n return addButton(R.id.button_right, title, listener);\n }\n\n /**\n * Adds bottom-center button to the dialog\n **/\n public DialogBuilder addButtonCenter(String title,\n DialogInterface.OnClickListener listener) {\n return addButton(R.id.button_center, title, listener);\n }\n\n private DialogBuilder addButton(@IdRes int buttonId, String title,\n final DialogInterface.OnClickListener listener) {\n View view = getView();\n if (buttonsBar == null) {\n buttonsBar = new ButtonsBar(view, R.id.three_buttons_bar);\n buttonsBar.show();\n }\n\n buttonsBar.setButton(buttonId, title, new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (listener != null) {\n listener.onClick(getDialog(), 0);\n }\n getDialog().dismiss();\n }\n });\n\n return this;\n }\n\n // Returns the dialog's view\n private View getView() {\n if (view == null) {\n LayoutInflater inflater = LayoutInflater.from(context);\n view = inflater.inflate(R.layout.dialog_layout, null);\n }\n\n return view;\n }\n\n // Returns the dialog\n private Dialog getDialog() {\n if (dialog == null) {\n dialog = new AlertDialog.Builder(context).setView(getView()).create();\n }\n return dialog;\n }\n\n // Shows the dialog\n public Dialog show() {\n Dialog dialog = getDialog();\n dialog.show();\n return dialog;\n }\n\n public DialogBuilder setOnCancelListener(DialogInterface.OnCancelListener listener) {\n getDialog().setOnCancelListener(listener);\n return this;\n }\n}", "public class Permissions {\n private static final String TAG = Permissions.class.getName();\n private static final int REQUEST_CODE = (Permissions.class.hashCode() & 0xffff);\n private static final Map<String, Boolean> permissionsResults = new ConcurrentHashMap<>();\n\n // Permissions names\n public static final String WRITE_EXTERNAL_STORAGE = \"android.permission.WRITE_EXTERNAL_STORAGE\";\n public static final String RECEIVE_SMS = \"android.permission.RECEIVE_SMS\";\n public static final String WRITE_SMS = \"android.permission.WRITE_SMS\";\n public static final String READ_SMS = \"android.permission.READ_SMS\";\n public static final String SEND_SMS = \"android.permission.SEND_SMS\";\n public static final String CALL_PHONE = \"android.permission.CALL_PHONE\";\n public static final String READ_PHONE_STATE = \"android.permission.READ_PHONE_STATE\";\n public static final String READ_CONTACTS = \"android.permission.READ_CONTACTS\";\n public static final String WRITE_CONTACTS = \"android.permission.WRITE_CONTACTS\";\n public static final String READ_CALL_LOG = \"android.permission.READ_CALL_LOG\";\n public static final String WRITE_CALL_LOG = \"android.permission.WRITE_CALL_LOG\";\n public static final String VIBRATE = \"android.permission.VIBRATE\";\n public static final String ANSWER_PHONE_CALLS = \"android.permission.ANSWER_PHONE_CALLS\";\n\n private static ArrayList<String> PERMISSIONS = new ArrayList<>(Arrays.asList(\n WRITE_EXTERNAL_STORAGE,\n RECEIVE_SMS,\n WRITE_SMS,\n READ_SMS,\n SEND_SMS,\n CALL_PHONE,\n READ_PHONE_STATE,\n READ_CONTACTS,\n WRITE_CONTACTS,\n READ_CALL_LOG,\n WRITE_CALL_LOG,\n VIBRATE\n ));\n\n static {\n if (Build.VERSION.SDK_INT >= Constants.PIE_API_VERSION) {\n Log.d(TAG, \"Requesting extra permissions for PIE and higher.\");\n PERMISSIONS.add(ANSWER_PHONE_CALLS);\n }\n }\n\n /**\n * Checks for permission\n **/\n public static boolean isGranted(@NonNull Context context, @NonNull String permission) {\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {\n return true;\n }\n Boolean result = permissionsResults.get(permission);\n if (result == null) {\n int permissionCheck = ContextCompat.checkSelfPermission(context, permission);\n result = (permissionCheck == PackageManager.PERMISSION_GRANTED);\n permissionsResults.put(permission, result);\n }\n return result;\n }\n\n /**\n * Checks for permissions and notifies the user if they aren't granted\n **/\n public static void notifyIfNotGranted(@NonNull Context context) {\n StringBuilder sb = new StringBuilder();\n int count = 0;\n for (String permission : PERMISSIONS) {\n if (!isGranted(context, permission)) {\n if (count > 0) {\n sb.append(\"\\n\");\n }\n String info = getPermissionInfo(context, permission);\n sb.append(info);\n sb.append(\";\");\n count++;\n }\n }\n\n if (count > 0) {\n int duration;\n String message = context.getString(R.string.app_name) + \" \";\n if (count == 1) {\n duration = Toast.LENGTH_SHORT;\n message += context.getString(R.string.needs_permission) + \":\\n\" + sb.toString();\n } else {\n duration = Toast.LENGTH_LONG;\n message += context.getString(R.string.needs_permissions) + \":\\n\" + sb.toString();\n }\n Utils.showToast(context, message, duration);\n }\n }\n\n /**\n * Checks for permission and notifies if it isn't granted\n **/\n public static boolean notifyIfNotGranted(@NonNull Context context, @NonNull String permission) {\n if (!isGranted(context, permission)) {\n notify(context, permission);\n return true;\n }\n return false;\n }\n\n /**\n * Returns information string about permission\n **/\n @Nullable\n private static String getPermissionInfo(@NonNull Context context, @NonNull String permission) {\n context = context.getApplicationContext();\n PackageManager pm = context.getPackageManager();\n PermissionInfo info = null;\n try {\n info = pm.getPermissionInfo(permission, PackageManager.GET_META_DATA);\n } catch (PackageManager.NameNotFoundException ex) {\n Log.w(TAG, ex);\n }\n\n if (info != null) {\n CharSequence label = info.loadLabel(pm);\n if (label == null) {\n label = info.nonLocalizedLabel;\n }\n return label.toString();\n }\n\n return null;\n }\n\n /**\n * Notifies the user if permission isn't granted\n **/\n private static void notify(@NonNull Context context, @NonNull String permission) {\n String info = getPermissionInfo(context, permission);\n if (info != null) {\n String message = context.getString(R.string.app_name) + \" \" +\n context.getString(R.string.needs_permission) + \":\\n\" + info + \";\";\n Utils.showToast(context, message, Toast.LENGTH_SHORT);\n }\n }\n\n /**\n * Checks for permissions and shows a dialog for permission granting\n **/\n public static void checkAndRequest(@NonNull Activity context) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n List<String> permissions = new LinkedList<>();\n for (String permission : PERMISSIONS) {\n if (!isGranted(context, permission)) {\n permissions.add(permission);\n }\n }\n if (permissions.size() > 0) {\n String[] array = permissions.toArray(new String[permissions.size()]);\n ActivityCompat.requestPermissions(context, array, REQUEST_CODE);\n }\n }\n }\n\n /**\n * Resets permissions results cache\n **/\n public static void invalidateCache() {\n permissionsResults.clear();\n }\n\n /**\n * Saves the results of permission granting request\n **/\n public static void onRequestPermissionsResult(int requestCode,\n @NonNull String permissions[],\n @NonNull int[] grantResults) {\n if (requestCode == REQUEST_CODE &&\n permissions.length == grantResults.length) {\n for (int i = 0; i < permissions.length; i++) {\n boolean result = (grantResults[i] == PackageManager.PERMISSION_GRANTED);\n permissionsResults.put(permissions[i], result);\n }\n }\n }\n}", "public class Settings {\n public static final String BLOCK_CALLS_FROM_BLACK_LIST = \"BLOCK_CALLS_FROM_BLACK_LIST\";\n public static final String BLOCK_ALL_CALLS = \"BLOCK_ALL_CALLS\";\n public static final String BLOCK_CALLS_NOT_FROM_CONTACTS = \"BLOCK_CALLS_NOT_FROM_CONTACTS\";\n public static final String BLOCK_CALLS_NOT_FROM_SMS_CONTENT = \"BLOCK_CALLS_NOT_FROM_SMS_CONTENT\";\n public static final String BLOCK_PRIVATE_CALLS = \"BLOCK_PRIVATE_CALLS\";\n public static final String BLOCKED_CALL_STATUS_NOTIFICATION = \"BLOCKED_CALL_STATUS_NOTIFICATION\";\n public static final String WRITE_CALLS_JOURNAL = \"WRITE_CALLS_JOURNAL\";\n public static final String BLOCK_SMS_FROM_BLACK_LIST = \"BLOCK_SMS_FROM_BLACK_LIST\";\n public static final String BLOCK_ALL_SMS = \"BLOCK_ALL_SMS\";\n public static final String BLOCK_SMS_NOT_FROM_CONTACTS = \"BLOCK_SMS_NOT_FROM_CONTACTS\";\n public static final String BLOCK_SMS_NOT_FROM_SMS_CONTENT = \"BLOCK_SMS_NOT_FROM_SMS_CONTENT\";\n public static final String BLOCK_PRIVATE_SMS = \"BLOCK_PRIVATE_SMS\";\n public static final String BLOCKED_SMS_STATUS_NOTIFICATION = \"BLOCKED_SMS_STATUS_NOTIFICATION\";\n public static final String WRITE_SMS_JOURNAL = \"WRITE_SMS_JOURNAL\";\n public static final String BLOCKED_SMS_SOUND_NOTIFICATION = \"BLOCKED_SMS_SOUND_NOTIFICATION\";\n public static final String RECEIVED_SMS_SOUND_NOTIFICATION = \"RECEIVED_SMS_SOUND_NOTIFICATION\";\n public static final String BLOCKED_SMS_VIBRATION_NOTIFICATION = \"BLOCKED_SMS_VIBRATION_NOTIFICATION\";\n public static final String RECEIVED_SMS_VIBRATION_NOTIFICATION = \"RECEIVED_SMS_VIBRATION_NOTIFICATION\";\n public static final String BLOCKED_SMS_RINGTONE = \"BLOCKED_SMS_RINGTONE\";\n public static final String RECEIVED_SMS_RINGTONE = \"RECEIVED_SMS_RINGTONE\";\n public static final String BLOCKED_CALL_SOUND_NOTIFICATION = \"BLOCKED_CALL_SOUND_NOTIFICATION\";\n public static final String BLOCKED_CALL_VIBRATION_NOTIFICATION = \"BLOCKED_CALL_VIBRATION_NOTIFICATION\";\n public static final String BLOCKED_CALL_RINGTONE = \"BLOCKED_CALL_RINGTONE\";\n public static final String DELIVERY_SMS_NOTIFICATION = \"DELIVERY_SMS_NOTIFICATION\";\n public static final String FOLD_SMS_TEXT_IN_JOURNAL = \"FOLD_SMS_TEXT_IN_JOURNAL\";\n public static final String UI_THEME_DARK = \"UI_THEME_DARK\";\n public static final String GO_TO_JOURNAL_AT_START = \"GO_TO_JOURNAL_AT_START\";\n public static final String DEFAULT_SMS_APP_NATIVE_PACKAGE = \"DEFAULT_SMS_APP_NATIVE_PACKAGE\";\n public static final String DONT_EXIT_ON_BACK_PRESSED = \"DONT_EXIT_ON_BACK_PRESSED\";\n public static final String REMOVE_FROM_CALL_LOG = \"REMOVE_FROM_CALL_LOG\";\n public static final String SIM_SUBSCRIPTION_ID = \"SIM_SUBSCRIPTION\";\n\n private static final String TRUE = \"TRUE\";\n private static final String FALSE = \"FALSE\";\n\n private static Map<String, String> settingsMap = new ConcurrentHashMap<>();\n\n public static void invalidateCache() {\n settingsMap.clear();\n }\n\n public static boolean setStringValue(Context context, @NonNull String name, @NonNull String value) {\n DatabaseAccessHelper db = DatabaseAccessHelper.getInstance(context);\n if (db != null && db.setSettingsValue(name, value)) {\n settingsMap.put(name, value);\n return true;\n }\n return false;\n }\n\n @Nullable\n public static String getStringValue(Context context, @NonNull String name) {\n String value = settingsMap.get(name);\n if (value == null) {\n DatabaseAccessHelper db = DatabaseAccessHelper.getInstance(context);\n if (db != null) {\n value = db.getSettingsValue(name);\n if (value != null) {\n settingsMap.put(name, value);\n }\n }\n }\n return value;\n }\n\n public static boolean setBooleanValue(Context context, @NonNull String name, boolean value) {\n String v = (value ? TRUE : FALSE);\n return setStringValue(context, name, v);\n }\n\n public static boolean getBooleanValue(Context context, @NonNull String name) {\n String value = getStringValue(context, name);\n return (value != null && value.equals(TRUE));\n }\n\n public static boolean setIntegerValue(Context context, @NonNull String name, int value) {\n String v = String.valueOf(value);\n return setStringValue(context, name, v);\n }\n\n @Nullable\n public static Integer getIntegerValue(Context context, @NonNull String name) {\n String value = getStringValue(context, name);\n try {\n return (value != null ? Integer.valueOf(value) : null);\n } catch (NumberFormatException ignored) {\n }\n return null;\n }\n\n public static void initDefaults(Context context) {\n Map<String, String> map = new HashMap<>();\n map.put(BLOCK_CALLS_FROM_BLACK_LIST, TRUE);\n map.put(BLOCK_ALL_CALLS, FALSE);\n map.put(BLOCK_CALLS_NOT_FROM_CONTACTS, FALSE);\n map.put(BLOCK_CALLS_NOT_FROM_SMS_CONTENT, FALSE);\n map.put(BLOCK_PRIVATE_CALLS, FALSE);\n map.put(WRITE_CALLS_JOURNAL, TRUE);\n map.put(BLOCKED_CALL_STATUS_NOTIFICATION, TRUE);\n map.put(BLOCKED_CALL_SOUND_NOTIFICATION, FALSE);\n map.put(BLOCKED_CALL_VIBRATION_NOTIFICATION, FALSE);\n map.put(BLOCK_SMS_FROM_BLACK_LIST, TRUE);\n map.put(BLOCK_ALL_SMS, FALSE);\n map.put(BLOCK_SMS_NOT_FROM_CONTACTS, FALSE);\n map.put(BLOCK_SMS_NOT_FROM_SMS_CONTENT, FALSE);\n map.put(BLOCK_PRIVATE_SMS, FALSE);\n map.put(BLOCKED_SMS_STATUS_NOTIFICATION, TRUE);\n map.put(WRITE_SMS_JOURNAL, TRUE);\n map.put(BLOCKED_SMS_SOUND_NOTIFICATION, FALSE);\n map.put(RECEIVED_SMS_SOUND_NOTIFICATION, TRUE);\n map.put(BLOCKED_SMS_SOUND_NOTIFICATION, FALSE);\n map.put(RECEIVED_SMS_VIBRATION_NOTIFICATION, TRUE);\n map.put(BLOCKED_SMS_VIBRATION_NOTIFICATION, FALSE);\n map.put(DELIVERY_SMS_NOTIFICATION, TRUE);\n map.put(FOLD_SMS_TEXT_IN_JOURNAL, TRUE);\n map.put(UI_THEME_DARK, FALSE);\n map.put(GO_TO_JOURNAL_AT_START, FALSE);\n map.put(DONT_EXIT_ON_BACK_PRESSED, FALSE);\n map.put(REMOVE_FROM_CALL_LOG, FALSE);\n map.put(SIM_SUBSCRIPTION_ID, \"-1\");\n\n if (!Permissions.isGranted(context, Permissions.WRITE_EXTERNAL_STORAGE)) {\n settingsMap = new ConcurrentHashMap<>(map);\n } else {\n for (Map.Entry<String, String> entry : map.entrySet()) {\n String name = entry.getKey();\n if (getStringValue(context, name) == null) {\n String value = entry.getValue();\n setStringValue(context, name, value);\n }\n }\n }\n }\n\n // Applies the current UI theme depending on settings\n public static void applyCurrentTheme(Activity activity) {\n if (getBooleanValue(activity, Settings.UI_THEME_DARK)) {\n activity.setTheme(R.style.AppTheme_Dark);\n } else {\n activity.setTheme(R.style.AppTheme_Light);\n }\n }\n}", "public class SubscriptionHelper {\n\n public static boolean isAvailable() {\n return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1);\n }\n\n @Nullable\n public static List<SubscriptionInfo> getSubscriptions(Context context) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {\n SubscriptionManager sm = SubscriptionManager.from(context);\n return sm.getActiveSubscriptionInfoList();\n }\n\n return null;\n }\n\n /**\n * @return id of the current subscription (id of SIM)\n */\n @Nullable\n public static Integer getCurrentSubscriptionId(Context context) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {\n SubscriptionInfo info = getCurrentSubscription(context);\n if (info != null) return info.getSubscriptionId();\n }\n\n return null;\n }\n\n @Nullable\n public static String getCurrentSubscriptionName(Context context) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {\n SubscriptionInfo info = getCurrentSubscription(context);\n if (info != null) return info.getDisplayName().toString();\n }\n\n return null;\n }\n\n @Nullable\n public static SubscriptionInfo getCurrentSubscription(Context context) {\n Integer subscriptionId = Settings.getIntegerValue(context, Settings.SIM_SUBSCRIPTION_ID);\n if (subscriptionId != null && subscriptionId >= 0) {\n return getSubscriptionById(context, subscriptionId);\n }\n\n return null;\n }\n\n @Nullable\n public static SubscriptionInfo getSubscriptionById(Context context, int subscriptionId) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {\n List<SubscriptionInfo> list = getSubscriptions(context);\n if (list != null) {\n for (SubscriptionInfo info : list) {\n if (info.getSubscriptionId() == subscriptionId) {\n return info;\n }\n }\n }\n }\n\n return null;\n }\n\n @Nullable\n public static String getName(SubscriptionInfo info) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1 && info != null) {\n return info.getDisplayName().toString();\n }\n return null;\n }\n\n @Nullable\n public static Integer getId(SubscriptionInfo info) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1 && info != null) {\n return info.getSubscriptionId();\n }\n return null;\n }\n}", "public class Utils {\n private static final String TAG = Utils.class.getName();\n\n /**\n * Tints menu icon\n **/\n public static void setMenuIconTint(Context context, MenuItem item, @AttrRes int colorAttrRes) {\n Drawable drawable = DrawableCompat.wrap(item.getIcon());\n drawable.mutate();\n setDrawableTint(context, drawable, colorAttrRes);\n }\n\n /**\n * Sets the tint color of the drawable\n **/\n public static void setDrawableTint(Context context, Drawable drawable, @AttrRes int colorAttrRes) {\n int colorRes = getResourceId(context, colorAttrRes);\n int color = ContextCompat.getColor(context, colorRes);\n DrawableCompat.setTint(drawable, color);\n }\n\n /**\n * Sets the background color of the drawable\n **/\n public static void setDrawableColor(Context context, Drawable drawable, @AttrRes int colorAttrRes) {\n int colorRes = getResourceId(context, colorAttrRes);\n int color = ContextCompat.getColor(context, colorRes);\n if (drawable instanceof ShapeDrawable) {\n ((ShapeDrawable) drawable).getPaint().setColor(color);\n } else if (drawable instanceof GradientDrawable) {\n ((GradientDrawable) drawable).setColor(color);\n } else if (drawable instanceof ColorDrawable) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {\n ((ColorDrawable) drawable).setColor(color);\n }\n } else if (drawable instanceof RotateDrawable) {\n setDrawableColor(context, ((RotateDrawable) drawable).getDrawable(), colorAttrRes);\n }\n }\n\n /**\n * Sets drawable for the view\n **/\n @SuppressWarnings(\"deprecation\")\n public static void setDrawable(Context context, View view, @DrawableRes int drawableRes) {\n Drawable drawable = ContextCompat.getDrawable(context, drawableRes);\n if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {\n view.setBackgroundDrawable(drawable);\n } else {\n view.setBackground(drawable);\n }\n }\n\n /**\n * Resolves attribute of passed theme returning referenced resource id\n **/\n public static int getResourceId(@AttrRes int attrRes, Resources.Theme theme) {\n TypedValue typedValue = new TypedValue();\n theme.resolveAttribute(attrRes, typedValue, true);\n return typedValue.resourceId;\n }\n\n /**\n * Resolves current theme's attribute returning referenced resource id\n **/\n public static int getResourceId(Context context, @AttrRes int attrRes) {\n return getResourceId(attrRes, context.getTheme());\n }\n\n /**\n * Resolves attribute of passed theme returning referenced resource id\n **/\n public static int getResourceId(Context context, @AttrRes int attrRes, @StyleRes int styleRes) {\n Resources.Theme theme = context.getResources().newTheme();\n theme.applyStyle(styleRes, true);\n return getResourceId(attrRes, theme);\n }\n\n//----------------------------------------------------------------------------\n\n /**\n * Copies passed text to clipboard\n **/\n @SuppressWarnings(\"deprecation\")\n public static boolean copyTextToClipboard(Context context, String text) {\n try {\n if (Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {\n android.text.ClipboardManager clipboard =\n (android.text.ClipboardManager) context\n .getSystemService(Context.CLIPBOARD_SERVICE);\n clipboard.setText(text);\n } else {\n android.content.ClipboardManager clipboard =\n (android.content.ClipboardManager)\n context.getSystemService(Context.CLIPBOARD_SERVICE);\n android.content.ClipData clip =\n android.content.ClipData.newPlainText(\"\", text);\n clipboard.setPrimaryClip(clip);\n }\n return true;\n } catch (Exception e) {\n Log.w(TAG, e);\n return false;\n }\n }\n\n /**\n * Copies file from source to destination\n **/\n public static boolean copyFile(File src, File dst) {\n InputStream in = null;\n OutputStream out = null;\n try {\n in = new FileInputStream(src);\n out = new FileOutputStream(dst);\n byte[] buffer = new byte[1024];\n int length;\n while ((length = in.read(buffer)) > 0) {\n out.write(buffer, 0, length);\n }\n } catch (IOException e) {\n Log.w(TAG, e);\n return false;\n } finally {\n close(in);\n close(out);\n }\n\n return true;\n }\n\n public static void close(Closeable closeable) {\n try {\n if (closeable != null) {\n closeable.close();\n }\n } catch (IOException e) {\n Log.w(TAG, e);\n }\n }\n\n /**\n * Makes file path if it doesn't exist\n **/\n public static boolean makeFilePath(File file) {\n String parent = file.getParent();\n if (parent != null) {\n File dir = new File(parent);\n try {\n if (!dir.exists() && !dir.mkdirs()) {\n throw new SecurityException(\"File.mkdirs() returns false\");\n }\n } catch (SecurityException e) {\n Log.w(TAG, e);\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Makes and shows threadsafe toast\n */\n public static void showToast(final Context context, final String message, final int duration) {\n Handler handler = new Handler(Looper.getMainLooper());\n handler.post(new Runnable() {\n @Override\n public void run() {\n Toast.makeText(context.getApplicationContext(), message, duration).show();\n }\n });\n }\n\n /**\n * Scales passed view with passed dimension on Tablets only\n */\n public static void scaleViewOnTablet(Context context, View view, @DimenRes int dimenRes) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {\n boolean isTablet = context.getResources().getBoolean(R.bool.isTablet);\n if (isTablet) {\n TypedValue outValue = new TypedValue();\n context.getResources().getValue(dimenRes, outValue, true);\n float scale = outValue.getFloat();\n view.setScaleX(scale);\n view.setScaleY(scale);\n }\n }\n }\n\n /**\n * Returns year-less date format\n */\n @SuppressWarnings(\"SimpleDateFormat\")\n public static DateFormat getYearLessDateFormat(DateFormat dateFormat) {\n if (dateFormat instanceof SimpleDateFormat) {\n // creating year less date format\n String fullPattern = ((SimpleDateFormat)dateFormat).toPattern();\n // checking 'de' we omit problems with Spain locale\n String regex = fullPattern.contains(\"de\") ? \"[^Mm]*[Yy]+[^Mm]*\" : \"[^DdMm]*[Yy]+[^DdMm]*\";\n String yearLessPattern = fullPattern.replaceAll(regex, \"\");\n return new SimpleDateFormat(yearLessPattern);\n }\n return dateFormat;\n }\n}" ]
import android.app.Activity; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.support.annotation.IdRes; import android.support.annotation.Nullable; import android.support.annotation.StringRes; import android.support.v4.app.Fragment; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.telephony.SubscriptionInfo; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.kaliturin.blacklist.R; import com.kaliturin.blacklist.activities.MainActivity; import com.kaliturin.blacklist.adapters.SettingsArrayAdapter; import com.kaliturin.blacklist.utils.DatabaseAccessHelper; import com.kaliturin.blacklist.utils.DefaultSMSAppHelper; import com.kaliturin.blacklist.utils.DialogBuilder; import com.kaliturin.blacklist.utils.Permissions; import com.kaliturin.blacklist.utils.Settings; import com.kaliturin.blacklist.utils.SubscriptionHelper; import com.kaliturin.blacklist.utils.Utils; import java.io.File; import java.util.List;
case BLOCKED_SMS: uriString = Settings.getStringValue(getContext(), Settings.BLOCKED_SMS_RINGTONE); break; case RECEIVED_SMS: uriString = Settings.getStringValue(getContext(), Settings.RECEIVED_SMS_RINGTONE); break; } return (uriString != null ? Uri.parse(uriString) : null); } // On row click listener for opening ringtone picker private class RingtonePickerOnClickListener implements View.OnClickListener { int requestCode; RingtonePickerOnClickListener(int requestCode) { this.requestCode = requestCode; } @Override public void onClick(View view) { if (isAdded()) { if (adapter.isRowChecked(view)) { // open ringtone picker dialog Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER); intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION); intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, getString(R.string.Ringtone_picker)); intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, getRingtoneUri(requestCode)); startActivityForResult(intent, requestCode); } } else { adapter.setRowChecked(view, false); } } } // On row click listener for updating dependent rows private class DependentRowOnClickListener implements View.OnClickListener { @Override public void onClick(View view) { String property = adapter.getRowProperty(view); if (property == null) { return; } boolean checked = adapter.isRowChecked(view); if (!checked) { // if row was unchecked - reset dependent rows switch (property) { case Settings.BLOCKED_SMS_STATUS_NOTIFICATION: adapter.setRowChecked(Settings.BLOCKED_SMS_SOUND_NOTIFICATION, false); adapter.setRowChecked(Settings.BLOCKED_SMS_VIBRATION_NOTIFICATION, false); break; case Settings.BLOCKED_CALL_STATUS_NOTIFICATION: adapter.setRowChecked(Settings.BLOCKED_CALL_SOUND_NOTIFICATION, false); adapter.setRowChecked(Settings.BLOCKED_CALL_VIBRATION_NOTIFICATION, false); break; } } else { switch (property) { case Settings.BLOCKED_SMS_SOUND_NOTIFICATION: case Settings.BLOCKED_SMS_VIBRATION_NOTIFICATION: adapter.setRowChecked(Settings.BLOCKED_SMS_STATUS_NOTIFICATION, true); break; case Settings.BLOCKED_CALL_SOUND_NOTIFICATION: case Settings.BLOCKED_CALL_VIBRATION_NOTIFICATION: adapter.setRowChecked(Settings.BLOCKED_CALL_STATUS_NOTIFICATION, true); break; } } } } // Shows the dialog of database file path definition private void showFilePathDialog(@StringRes int titleId, final TextView.OnEditorActionListener listener) { if (!isAdded()) return; String filePath = Environment.getExternalStorageDirectory().getPath() + "/Download/" + DatabaseAccessHelper.DATABASE_NAME; @IdRes final int editId = 1; // create dialog DialogBuilder dialog = new DialogBuilder(getContext()); dialog.setTitle(titleId); dialog.addEdit(editId, filePath, getString(R.string.File_path)); dialog.addButtonLeft(getString(R.string.CANCEL), null); dialog.addButtonRight(getString(R.string.OK), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Window window = ((Dialog) dialog).getWindow(); if (window != null) { TextView textView = (TextView) window.findViewById(editId); if (textView != null) { listener.onEditorAction(textView, 0, null); } } } }); dialog.show(); } // Exports data file to the passed path private boolean exportDataFile(String dstFilePath) { if (!Permissions.isGranted(getContext(), Permissions.WRITE_EXTERNAL_STORAGE)) { return false; } // get source file DatabaseAccessHelper db = DatabaseAccessHelper.getInstance(getContext()); if (db == null) { return false; } File srcFile = new File(db.getReadableDatabase().getPath()); // check destination file File dstFile = new File(dstFilePath); if (dstFile.getParent() == null) { toast(R.string.Error_invalid_file_path); return false; } // create destination file path
if (!Utils.makeFilePath(dstFile)) {
8
dperezcabrera/jpoker
src/main/java/org/poker/main/MainController.java
[ "public class RandomStrategy implements IStrategy {\n\n private static final Random RAND = new Random();\n private final String name;\n private double aggressivity = 0.5 + RAND.nextDouble() / 2;\n private BetCommand lastBet = null;\n\n public RandomStrategy(String name) {\n this.name = \"Random-\" + name;\n }\n\n @Override\n public String getName() {\n return name;\n }\n\n private long getMaxBet(GameInfo<PlayerInfo> state) {\n if (aggressivity > 1.d) {\n return Long.MAX_VALUE;\n }\n long players = state.getPlayers().stream().filter(p -> p.isActive() || p.getState() == TexasHoldEmUtil.PlayerState.ALL_IN).count();\n double probability = 1.0D / players;\n long pot = state.getPlayers().stream().mapToLong(p -> p.getBet()).sum();\n return Math.round((probability * pot / (1 - probability)) * aggressivity);\n }\n\n @Override\n public BetCommand getCommand(GameInfo<PlayerInfo> state) {\n PlayerInfo ownInfo = state.getPlayer(state.getPlayerTurn());\n calcAggressivity(state, ownInfo);\n long otherPlayerMaxBet = state.getPlayers().stream().max((p0, p1) -> Long.compare(p0.getBet(), p1.getBet())).get().getBet();\n\n long minBet = Math.max(otherPlayerMaxBet - ownInfo.getBet(), state.getSettings().getBigBlind());\n long maxBet = getMaxBet(state);\n long chips = ownInfo.getChips();\n BetCommand result;\n maxBet = Math.min(maxBet, state.getPlayers().stream().mapToLong(p -> p.getBet()).sum());\n if (minBet > maxBet) {\n result = new BetCommand(BetCommandType.FOLD);\n } else if (maxBet >= chips) {\n result = new BetCommand(BetCommandType.ALL_IN);\n } else if (maxBet > minBet && (lastBet == null || lastBet.getType() != BetCommandType.RAISE)) {\n result = new BetCommand(BetCommandType.RAISE, maxBet);\n } else if (minBet == 0 || otherPlayerMaxBet == state.getSettings().getBigBlind()) {\n result = new BetCommand(BetCommandType.CHECK);\n } else {\n result = new BetCommand(BetCommandType.CALL);\n }\n lastBet = result;\n return result;\n }\n\n @Override\n public String toString() {\n return String.join(\"{RandomStrategy-\", name, \"}\");\n }\n\n @Override\n public void check(List<Card> communityCards) {\n lastBet = null;\n }\n\n private void calcAggressivity(GameInfo<PlayerInfo> state, PlayerInfo player) {\n long allChips = state.getPlayers().stream().filter(p -> p.isActive() || p.getState() == TexasHoldEmUtil.PlayerState.ALL_IN).mapToLong(p -> p.getChips()).sum();\n long players = state.getPlayers().stream().filter(p -> p.isActive() || p.getState() == TexasHoldEmUtil.PlayerState.ALL_IN && p.getChips() > 0).count();\n long myChips = player.getChips();\n\n double proportion = (allChips - myChips) / players;\n aggressivity = (myChips / (proportion + myChips)) / 2 + 0.70d;\n if (myChips > (allChips - myChips)) {\n aggressivity = 1.1;\n }\n }\n}", "public interface IGameController {\n\n public void setSettings(Settings settings);\n\n public boolean addStrategy(IStrategy strategy);\n\n public void start() throws GameException;\n\n public void waitFinish();\n\n public void stop();\n\n public Map<String, Double> getScores();\n}", "@FunctionalInterface\npublic interface IStrategy {\n\n public String getName();\n\n public default BetCommand getCommand(GameInfo<PlayerInfo> state) {\n return null;\n }\n\n public default void initHand(GameInfo<PlayerInfo> state) {\n }\n \n public default void endHand(GameInfo<PlayerInfo> state) {\n }\n \n public default void endGame(Map<String, Double> scores) {\n }\n\n public default void check(List<Card> communityCards) {\n }\n\n public default void onPlayerCommand(String player, BetCommand betCommand) {\n }\n}", "@NotThreadSafe\npublic class Settings implements Serializable{\n private static final long serialVersionUID = 1L;\n\n private int maxPlayers;\n private long time;\n private int maxErrors;\n private int maxRounds;\n private long playerChip;\n private long smallBlind;\n private int rounds4IncrementBlind;\n\n public Settings() {\n // Default constructor.\n }\n\n public Settings(Settings s) {\n this.maxPlayers = s.maxPlayers;\n this.time = s.time;\n this.maxErrors = s.maxErrors;\n this.playerChip = s.playerChip;\n this.smallBlind = s.smallBlind;\n this.maxRounds = s.maxRounds;\n this.rounds4IncrementBlind = s.rounds4IncrementBlind;\n }\n\n public int getMaxErrors() {\n return maxErrors;\n }\n\n public void setMaxErrors(int maxErrors) {\n this.maxErrors = maxErrors;\n }\n\n public int getMaxPlayers() {\n return maxPlayers;\n }\n\n public void setMaxPlayers(int maxPlayers) {\n this.maxPlayers = maxPlayers;\n }\n\n public long getTime() {\n return time;\n }\n\n public void setTime(long time) {\n this.time = time;\n }\n\n public long getPlayerChip() {\n return playerChip;\n }\n\n public void setPlayerChip(long playerChip) {\n this.playerChip = playerChip;\n }\n\n public long getSmallBlind() {\n return smallBlind;\n }\n\n public long getBigBlind() {\n return smallBlind * 2;\n }\n\n public void setSmallBlind(long smallBlind) {\n this.smallBlind = smallBlind;\n }\n\n public int getMaxRounds() {\n return maxRounds;\n }\n\n public void setMaxRounds(int maxRounds) {\n this.maxRounds = maxRounds;\n }\n\n public int getRounds4IncrementBlind() {\n return rounds4IncrementBlind;\n }\n\n public void setRounds4IncrementBlind(int rounds4IncrementBlind) {\n this.rounds4IncrementBlind = rounds4IncrementBlind;\n }\n\n @Override\n public String toString() {\n return \"{class:'Settings', maxPlayers:\" + maxPlayers + \", time:\" + time + \", maxErrors:\" + maxErrors + \", playerChip:\" + playerChip + \", maxRounds:\" + maxRounds + \", smallBlind:\" + smallBlind + \", rounds4IncrementBlind:\" + rounds4IncrementBlind + '}';\n }\n}", "public class GameController implements IGameController, Runnable {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(GameController.class);\n private static final int DISPATCHER_THREADS = 1;\n private static final int EXTRA_THREADS = 2;\n public static final String SYSTEM_CONTROLLER = \"system\";\n \n private final Map<String, IGameEventDispatcher<PokerEventType>> players = new HashMap<>();\n private final List<String> playersByName = new ArrayList<>();\n private final List<ExecutorService> subExecutors = new ArrayList<>();\n private final Map<PokerEventType, IGameEventProcessor<PokerEventType, IStrategy>> playerProcessors;\n private final GameEventDispatcher<ConnectorGameEventType, StateMachineConnector> connectorDispatcher;\n private final StateMachineConnector stateMachineConnector;\n private final IGameTimer timer;\n private Settings settings;\n private ExecutorService executors;\n private boolean finish = false;\n\n public GameController() {\n timer = new GameTimer(buildExecutor(DISPATCHER_THREADS));\n stateMachineConnector = new StateMachineConnector(timer, players);\n connectorDispatcher = new GameEventDispatcher<>(stateMachineConnector, buildConnectorProcessors(), buildExecutor(1), ConnectorGameEventType.EXIT);\n stateMachineConnector.setSystem(connectorDispatcher);\n timer.setNotifier(timeoutId -> connectorDispatcher.dispatch(new GameEvent<>(ConnectorGameEventType.TIMEOUT, SYSTEM_CONTROLLER, timeoutId)));\n playerProcessors = buildPlayerProcessors();\n }\n\n private ExecutorService buildExecutor(int threads) {\n ExecutorService result = Executors.newFixedThreadPool(threads);\n subExecutors.add(result);\n return result;\n }\n\n private static Map<ConnectorGameEventType, IGameEventProcessor<ConnectorGameEventType, StateMachineConnector>> buildConnectorProcessors() {\n Map<ConnectorGameEventType, IGameEventProcessor<ConnectorGameEventType, StateMachineConnector>> connectorProcessorsMap = new EnumMap<>(ConnectorGameEventType.class);\n connectorProcessorsMap.put(ConnectorGameEventType.CREATE_GAME, (connector, event) -> connector.createGame((Settings) event.getPayload()));\n connectorProcessorsMap.put(ConnectorGameEventType.ADD_PLAYER, (connector, event) -> connector.addPlayer(event.getSource()));\n connectorProcessorsMap.put(ConnectorGameEventType.INIT_GAME, (connector, event) -> connector.startGame());\n connectorProcessorsMap.put(ConnectorGameEventType.BET_COMMAND, (connector, event) -> connector.betCommand(event.getSource(), (BetCommand) event.getPayload()));\n connectorProcessorsMap.put(ConnectorGameEventType.TIMEOUT, (connector, event) -> connector.timeOutCommand((Long) event.getPayload()));\n return connectorProcessorsMap;\n }\n\n private Map<PokerEventType, IGameEventProcessor<PokerEventType, IStrategy>> buildPlayerProcessors() {\n Map<PokerEventType, IGameEventProcessor<PokerEventType, IStrategy>> playerProcessorsMap = new EnumMap<>(PokerEventType.class);\n playerProcessorsMap.put(PokerEventType.INIT_HAND, (strategy, event) -> strategy.initHand((GameInfo) event.getPayload()));\n playerProcessorsMap.put(PokerEventType.END_HAND, (strategy, event) -> strategy.endHand((GameInfo) event.getPayload()));\n playerProcessorsMap.put(PokerEventType.END_GAME, (strategy, event) -> strategy.endGame((Map<String, Double>) event.getPayload()));\n playerProcessorsMap.put(PokerEventType.BET_COMMAND, (strategy, event) -> strategy.onPlayerCommand(event.getSource(), (BetCommand) event.getPayload()));\n playerProcessorsMap.put(PokerEventType.CHECK, (strategy, event) -> strategy.check((List<Card>) event.getPayload()));\n playerProcessorsMap.put(PokerEventType.GET_COMMAND, (strategy, event) -> {\n GameInfo<PlayerInfo> gi = (GameInfo<PlayerInfo>) event.getPayload();\n String playerTurn = gi.getPlayers().get(gi.getPlayerTurn()).getName();\n BetCommand command = strategy.getCommand(gi);\n connectorDispatcher.dispatch(new GameEvent<>(ConnectorGameEventType.BET_COMMAND, playerTurn, command));\n });\n return playerProcessorsMap;\n }\n\n @Override\n public void setSettings(Settings settings) {\n this.settings = new Settings(settings);\n }\n\n @Override\n public synchronized boolean addStrategy(IStrategy strategy) {\n boolean result = false;\n String name = strategy.getName();\n if (!players.containsKey(name) && !SYSTEM_CONTROLLER.equals(name)) {\n players.put(name, new GameEventDispatcher<>(strategy, playerProcessors, buildExecutor(DISPATCHER_THREADS), PokerEventType.EXIT));\n playersByName.add(name);\n result = true;\n }\n return result;\n }\n\n private void check(boolean essentialCondition, String exceptionMessage) throws GameException {\n if (!essentialCondition) {\n throw new GameException(exceptionMessage);\n }\n }\n\n @Override\n public synchronized void start() throws GameException {\n LOGGER.debug(\"start\");\n check(settings != null, \"No se ha establecido una configuración.\");\n check(players.size() > 1, \"No se han agregado un número suficiente de jugadores.\");\n check(players.size() <= settings.getMaxPlayers(), \"El número de jugadores excede el máximo permitido por configuración.\");\n check(settings.getMaxErrors() > 0, \"El número de máximo de errores debe ser mayor que '0'.\");\n check(settings.getMaxRounds() > 0, \"El número de máximo de rondas debe ser mayor que '0'.\");\n check(settings.getRounds4IncrementBlind() > 1, \"El número de rondas hasta incrementar las ciegas debe ser mayor que '1'.\");\n check(settings.getTime() > 0, \"El tiempo máximo por jugador debe ser mayor que '0' y se indica en ms.\");\n check(settings.getPlayerChip() > 0, \"El número de fichas inicial por jugador debe ser mayor que '0', el valor recomendado es 5000.\");\n check(settings.getSmallBlind() > 0, \"La apuesta de la ciega pequeña debe ser mayor que '0' idealmente es la centesima parte de las fichas iniciales por jugador.\");\n executors = Executors.newFixedThreadPool(players.size() + EXTRA_THREADS);\n players.values().stream().forEach(executors::execute);\n stateMachineConnector.createGame(settings);\n timer.setTime(settings.getTime());\n playersByName.stream().forEach(stateMachineConnector::addPlayer);\n executors.execute(timer);\n new Thread(this).start();\n }\n\n @Override\n public synchronized void run() {\n LOGGER.debug(\"run\");\n connectorDispatcher.dispatch(new GameEvent<>(ConnectorGameEventType.INIT_GAME, SYSTEM_CONTROLLER));\n connectorDispatcher.run();\n // Fin de la ejecución\n exit();\n notifyAll();\n }\n\n @Override\n public Map<String, Double> getScores() {\n return stateMachineConnector.getScores();\n }\n \n @Override\n public synchronized void waitFinish() {\n if (!finish) {\n try {\n wait();\n } catch (Exception ex) {\n LOGGER.error(\"Esperando el final\", ex);\n }\n }\n }\n\n @Override\n public void stop() {\n exit();\n }\n\n private void exit() {\n if (!finish) {\n connectorDispatcher.exit();\n timer.exit();\n executors.shutdown();\n players.values().stream().forEach(IGameEventDispatcher::exit);\n subExecutors.stream().forEach(ExecutorService::shutdown);\n try {\n executors.awaitTermination(0, TimeUnit.SECONDS);\n } catch (Exception ex) {\n LOGGER.error(\"Error intentando eliminar todos los hilos\", ex);\n }\n finish = true;\n }\n }\n}", "public class TexasHoldEmView extends javax.swing.JFrame {\n\n private static final int WINDOW_HEIGHT = 800;\n private static final int WINDOW_WITH = 1280;\n private static final String WINDOW_TITLE = \"J Poker\";\n private static final String WINDOW_ICON = IMAGES_PATH + \"poker-chip.png\";\n\n private TexasHoldEmTablePanel jTablePanel;\n\n public TexasHoldEmView(IStrategy delegate) {\n initComponents();\n setTitle(WINDOW_TITLE);\n setIconImage(ImageManager.INSTANCE.getImage(WINDOW_ICON));\n setBounds(0, 0, WINDOW_WITH, WINDOW_HEIGHT);\n jTablePanel.setStrategy(delegate);\n }\n\n public IStrategy getStrategy() {\n return jTablePanel;\n }\n\n private void initComponents() {\n\n jTablePanel = new TexasHoldEmTablePanel();\n\n setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);\n\n jTablePanel.setPreferredSize(new java.awt.Dimension(WINDOW_WITH, WINDOW_HEIGHT));\n\n javax.swing.GroupLayout jTablePanelLayout = new javax.swing.GroupLayout(jTablePanel);\n jTablePanel.setLayout(jTablePanelLayout);\n jTablePanelLayout.setHorizontalGroup(\n jTablePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGap(0, WINDOW_WITH, Short.MAX_VALUE)\n );\n jTablePanelLayout.setVerticalGroup(\n jTablePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addGap(0, WINDOW_HEIGHT, Short.MAX_VALUE)\n );\n\n javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());\n getContentPane().setLayout(layout);\n layout.setHorizontalGroup(\n layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addComponent(jTablePanel, javax.swing.GroupLayout.DEFAULT_SIZE, WINDOW_WITH, Short.MAX_VALUE)\n );\n layout.setVerticalGroup(\n layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n .addComponent(jTablePanel, javax.swing.GroupLayout.DEFAULT_SIZE, WINDOW_HEIGHT, Short.MAX_VALUE)\n );\n pack();\n }\n}" ]
import org.poker.sample.strategies.RandomStrategy; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.poker.api.game.IGameController; import org.poker.api.game.IStrategy; import org.poker.api.game.Settings; import org.poker.engine.controller.GameController; import org.poker.gui.TexasHoldEmView; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * Copyright (C) 2016 David Pérez Cabrera <[email protected]> * * 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 org.poker.main; /** * * @author David Pérez Cabrera <[email protected]> */ public final class MainController { private static final Logger LOGGER = LoggerFactory.getLogger(MainController.class); private static final int PLAYERS = 10; private MainController() { } public static void main(String[] args) throws Exception { IStrategy strategyMain = new RandomStrategy("0");
TexasHoldEmView texasHoldEmView = new TexasHoldEmView(strategyMain);
5
ralscha/wampspring
src/main/java/ch/rasc/wampspring/config/WampSubProtocolHandler.java
[ "public class CallErrorMessage extends WampMessage {\n\tprivate final String callID;\n\n\tprivate final String errorURI;\n\n\tprivate final String errorDesc;\n\n\tprivate final Object errorDetails;\n\n\tpublic CallErrorMessage(CallMessage callMessage, String errorURI, String errorDesc) {\n\t\tthis(callMessage, errorURI, errorDesc, null);\n\t}\n\n\tpublic CallErrorMessage(CallMessage callMessage, String errorURI, String errorDesc,\n\t\t\tObject errorDetails) {\n\t\tsuper(WampMessageType.CALLERROR);\n\t\tthis.callID = callMessage.getCallID();\n\t\tthis.errorURI = errorURI;\n\t\tthis.errorDesc = errorDesc;\n\t\tthis.errorDetails = errorDetails;\n\n\t\tsetWebSocketSessionId(callMessage.getWebSocketSessionId());\n\t\tsetPrincipal(callMessage.getPrincipal());\n\t}\n\n\tpublic CallErrorMessage(JsonParser jp) throws IOException {\n\t\tsuper(WampMessageType.CALLERROR);\n\n\t\tif (jp.nextToken() != JsonToken.VALUE_STRING) {\n\t\t\tthrow new IOException();\n\t\t}\n\t\tthis.callID = jp.getValueAsString();\n\n\t\tif (jp.nextToken() != JsonToken.VALUE_STRING) {\n\t\t\tthrow new IOException();\n\t\t}\n\t\tthis.errorURI = jp.getValueAsString();\n\n\t\tif (jp.nextToken() != JsonToken.VALUE_STRING) {\n\t\t\tthrow new IOException();\n\t\t}\n\t\tthis.errorDesc = jp.getValueAsString();\n\n\t\tif (jp.nextToken() != JsonToken.END_ARRAY) {\n\t\t\tthis.errorDetails = jp.readValueAs(Object.class);\n\t\t}\n\t\telse {\n\t\t\tthis.errorDetails = null;\n\t\t}\n\t}\n\n\tpublic String getCallID() {\n\t\treturn this.callID;\n\t}\n\n\tpublic String getErrorURI() {\n\t\treturn this.errorURI;\n\t}\n\n\tpublic String getErrorDesc() {\n\t\treturn this.errorDesc;\n\t}\n\n\tpublic Object getErrorDetails() {\n\t\treturn this.errorDetails;\n\t}\n\n\t@Override\n\tpublic String toJson(JsonFactory jsonFactory) throws IOException {\n\t\ttry (StringWriter sw = new StringWriter();\n\t\t\t\tJsonGenerator jg = jsonFactory.createGenerator(sw)) {\n\t\t\tjg.writeStartArray();\n\t\t\tjg.writeNumber(getTypeId());\n\t\t\tjg.writeString(this.callID);\n\t\t\tjg.writeString(this.errorURI);\n\t\t\tjg.writeString(this.errorDesc);\n\t\t\tif (this.errorDetails != null) {\n\t\t\t\tjg.writeObject(this.errorDetails);\n\t\t\t}\n\t\t\tjg.writeEndArray();\n\t\t\tjg.close();\n\n\t\t\treturn sw.toString();\n\t\t}\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"CallErrorMessage [callID=\" + this.callID + \", errorURI=\" + this.errorURI\n\t\t\t\t+ \", errorDesc=\" + this.errorDesc + \", errorDetails=\" + this.errorDetails\n\t\t\t\t+ \"]\";\n\t}\n\n}", "public class CallMessage extends WampMessage {\n\tprivate final String callID;\n\n\tprivate final String procURI;\n\n\tprivate final List<Object> arguments;\n\n\tpublic CallMessage(String callID, String procURI, Object... arguments) {\n\t\tsuper(WampMessageType.CALL);\n\t\tthis.callID = callID;\n\t\tthis.procURI = procURI;\n\t\tif (arguments != null) {\n\t\t\tthis.arguments = Arrays.asList(arguments);\n\t\t}\n\t\telse {\n\t\t\tthis.arguments = null;\n\t\t}\n\n\t}\n\n\tpublic CallMessage(JsonParser jp) throws IOException {\n\t\tthis(jp, null);\n\t}\n\n\tpublic CallMessage(JsonParser jp, WampSession wampSession) throws IOException {\n\t\tsuper(WampMessageType.CALL);\n\n\t\tif (jp.nextToken() != JsonToken.VALUE_STRING) {\n\t\t\tthrow new IOException();\n\t\t}\n\t\tthis.callID = jp.getValueAsString();\n\n\t\tif (jp.nextToken() != JsonToken.VALUE_STRING) {\n\t\t\tthrow new IOException();\n\t\t}\n\t\tthis.procURI = replacePrefix(jp.getValueAsString(), wampSession);\n\n\t\tList<Object> args = new ArrayList<>();\n\t\twhile (jp.nextToken() != JsonToken.END_ARRAY) {\n\t\t\targs.add(jp.readValueAs(Object.class));\n\t\t}\n\n\t\tif (!args.isEmpty()) {\n\t\t\tthis.arguments = Collections.unmodifiableList(args);\n\t\t}\n\t\telse {\n\t\t\tthis.arguments = null;\n\t\t}\n\t}\n\n\tpublic String getCallID() {\n\t\treturn this.callID;\n\t}\n\n\tpublic String getProcURI() {\n\t\treturn this.procURI;\n\t}\n\n\tpublic List<Object> getArguments() {\n\t\treturn this.arguments;\n\t}\n\n\t@Override\n\tpublic String getDestination() {\n\t\treturn this.procURI;\n\t}\n\n\t@Override\n\tpublic String toJson(JsonFactory jsonFactory) throws IOException {\n\t\ttry (StringWriter sw = new StringWriter();\n\t\t\t\tJsonGenerator jg = jsonFactory.createGenerator(sw)) {\n\t\t\tjg.writeStartArray();\n\t\t\tjg.writeNumber(getTypeId());\n\t\t\tjg.writeString(this.callID);\n\t\t\tjg.writeString(this.procURI);\n\t\t\tif (this.arguments != null) {\n\t\t\t\tfor (Object argument : this.arguments) {\n\t\t\t\t\tjg.writeObject(argument);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tjg.writeEndArray();\n\t\t\tjg.close();\n\t\t\treturn sw.toString();\n\t\t}\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"CallMessage [callID=\" + this.callID + \", procURI=\" + this.procURI\n\t\t\t\t+ \", arguments=\" + this.arguments + \"]\";\n\t}\n\n}", "public class UnsubscribeMessage extends PubSubMessage {\n\n\tprivate boolean cleanup = false;\n\n\tpublic UnsubscribeMessage(String topicURI) {\n\t\tsuper(WampMessageType.UNSUBSCRIBE, topicURI);\n\t}\n\n\tpublic UnsubscribeMessage(JsonParser jp) throws IOException {\n\t\tthis(jp, null);\n\t}\n\n\tpublic UnsubscribeMessage(JsonParser jp, WampSession wampSession) throws IOException {\n\t\tsuper(WampMessageType.UNSUBSCRIBE);\n\t\tif (jp.nextToken() != JsonToken.VALUE_STRING) {\n\t\t\tthrow new IOException();\n\t\t}\n\t\tsetTopicURI(replacePrefix(jp.getValueAsString(), wampSession));\n\t}\n\n\t/**\n\t * Creates an internal unsubscribe message. The system creates this message when the\n\t * WebSocket session ends and sends it to the subscribed message handlers for cleaning\n\t * up\n\t *\n\t * @param sessionId the WebSocket session id\n\t **/\n\tpublic static UnsubscribeMessage createCleanupMessage(WebSocketSession session) {\n\t\tUnsubscribeMessage msg = new UnsubscribeMessage(\"**\");\n\n\t\tmsg.setWebSocketSessionId(session.getId());\n\t\tmsg.setPrincipal(session.getPrincipal());\n\t\tmsg.setWampSession(new WampSession(session));\n\n\t\tmsg.cleanup = true;\n\n\t\treturn msg;\n\t}\n\n\tpublic boolean isCleanup() {\n\t\treturn this.cleanup;\n\t}\n\n\t@Override\n\tpublic String toJson(JsonFactory jsonFactory) throws IOException {\n\t\ttry (StringWriter sw = new StringWriter();\n\t\t\t\tJsonGenerator jg = jsonFactory.createGenerator(sw)) {\n\t\t\tjg.writeStartArray();\n\t\t\tjg.writeNumber(getTypeId());\n\t\t\tjg.writeString(getTopicURI());\n\t\t\tjg.writeEndArray();\n\t\t\tjg.close();\n\t\t\treturn sw.toString();\n\t\t}\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"UnsubscribeMessage [topicURI=\" + getTopicURI() + \"]\";\n\t}\n\n}", "public abstract class WampMessage implements Message<Object> {\n\n\tprotected final static Object EMPTY_OBJECT = new Object();\n\n\tprivate final MutableMessageHeaders messageHeaders = new MutableMessageHeaders();\n\n\tWampMessage(WampMessageType type) {\n\t\tsetHeader(WampMessageHeader.WAMP_MESSAGE_TYPE, type);\n\t}\n\n\tint getTypeId() {\n\t\treturn getType().getTypeId();\n\t}\n\n\tpublic WampMessageType getType() {\n\t\treturn getHeader(WampMessageHeader.WAMP_MESSAGE_TYPE);\n\t}\n\n\tpublic void setHeader(WampMessageHeader header, Object value) {\n\t\tthis.messageHeaders.getRawHeaders().put(header.name(), value);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic <T> T getHeader(WampMessageHeader header) {\n\t\treturn (T) this.messageHeaders.get(header.name());\n\t}\n\n\tpublic void setDestinationTemplateVariables(Map<String, String> vars) {\n\t\tthis.messageHeaders.getRawHeaders().put(\n\t\t\t\tDestinationVariableMethodArgumentResolver.DESTINATION_TEMPLATE_VARIABLES_HEADER,\n\t\t\t\tvars);\n\t}\n\n\t/**\n\t * Convenient method to retrieve the WebSocket session id.\n\t */\n\tpublic String getWebSocketSessionId() {\n\t\treturn getHeader(WampMessageHeader.WEBSOCKET_SESSION_ID);\n\t}\n\n\tpublic void setWebSocketSessionId(String webSocketSessionId) {\n\t\tsetHeader(WampMessageHeader.WEBSOCKET_SESSION_ID, webSocketSessionId);\n\t}\n\n\tpublic String getDestination() {\n\t\treturn null;\n\t}\n\n\tpublic Principal getPrincipal() {\n\t\treturn getHeader(WampMessageHeader.PRINCIPAL);\n\t}\n\n\tvoid setPrincipal(Principal principal) {\n\t\tsetHeader(WampMessageHeader.PRINCIPAL, principal);\n\t}\n\n\tpublic WampSession getWampSession() {\n\t\treturn (WampSession) getHeader(WampMessageHeader.WAMP_SESSION);\n\t}\n\n\tvoid setWampSession(WampSession wampSession) {\n\t\tsetHeader(WampMessageHeader.WAMP_SESSION, wampSession);\n\t}\n\n\t@Override\n\tpublic Object getPayload() {\n\t\treturn EMPTY_OBJECT;\n\t}\n\n\t@Override\n\tpublic MessageHeaders getHeaders() {\n\t\treturn this.messageHeaders;\n\t}\n\n\tpublic static <T extends WampMessage> T fromJson(WebSocketSession session,\n\t\t\tJsonFactory jsonFactory, String json) throws IOException {\n\n\t\tWampSession wampSession = new WampSession(session);\n\n\t\tT newWampMessage = fromJson(jsonFactory, json, wampSession);\n\n\t\tnewWampMessage.setWebSocketSessionId(session.getId());\n\t\tnewWampMessage.setPrincipal(session.getPrincipal());\n\t\tnewWampMessage.setWampSession(wampSession);\n\n\t\treturn newWampMessage;\n\t}\n\n\tpublic abstract String toJson(JsonFactory jsonFactory) throws IOException;\n\n\tpublic static <T extends WampMessage> T fromJson(JsonFactory jsonFactory, String json)\n\t\t\tthrows IOException {\n\t\treturn fromJson(jsonFactory, json, null);\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static <T extends WampMessage> T fromJson(JsonFactory jsonFactory, String json,\n\t\t\tWampSession wampSession) throws IOException {\n\n\t\ttry (JsonParser jp = jsonFactory.createParser(json)) {\n\t\t\tif (jp.nextToken() != JsonToken.START_ARRAY) {\n\t\t\t\tthrow new IOException(\"Not a JSON array\");\n\t\t\t}\n\t\t\tif (jp.nextToken() != JsonToken.VALUE_NUMBER_INT) {\n\t\t\t\tthrow new IOException(\"Wrong message format\");\n\t\t\t}\n\n\t\t\tWampMessageType messageType = WampMessageType.fromTypeId(jp.getValueAsInt());\n\n\t\t\tswitch (messageType) {\n\t\t\tcase WELCOME:\n\t\t\t\treturn (T) new WelcomeMessage(jp);\n\t\t\tcase PREFIX:\n\t\t\t\treturn (T) new PrefixMessage(jp);\n\t\t\tcase CALL:\n\t\t\t\treturn (T) new CallMessage(jp, wampSession);\n\t\t\tcase CALLRESULT:\n\t\t\t\treturn (T) new CallResultMessage(jp);\n\t\t\tcase CALLERROR:\n\t\t\t\treturn (T) new CallErrorMessage(jp);\n\t\t\tcase SUBSCRIBE:\n\t\t\t\treturn (T) new SubscribeMessage(jp, wampSession);\n\t\t\tcase UNSUBSCRIBE:\n\t\t\t\treturn (T) new UnsubscribeMessage(jp, wampSession);\n\t\t\tcase PUBLISH:\n\t\t\t\treturn (T) new PublishMessage(jp, wampSession);\n\t\t\tcase EVENT:\n\t\t\t\treturn (T) new EventMessage(jp, wampSession);\n\t\t\tdefault:\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t}\n\t}\n\n\t@SuppressWarnings(\"serial\")\n\tprivate static class MutableMessageHeaders extends MessageHeaders {\n\n\t\tpublic MutableMessageHeaders() {\n\t\t\tsuper(null, MessageHeaders.ID_VALUE_NONE, -1L);\n\t\t}\n\n\t\t@Override\n\t\tpublic Map<String, Object> getRawHeaders() {\n\t\t\treturn super.getRawHeaders();\n\t\t}\n\t}\n\n\tprotected String replacePrefix(String uri, WampSession wampSession) {\n\t\tif (uri != null && wampSession != null && wampSession.hasPrefixes()) {\n\t\t\tString[] curie = uri.split(\":\");\n\t\t\tif (curie.length == 2) {\n\t\t\t\tString prefix = wampSession.getPrefix(curie[0]);\n\t\t\t\tif (prefix != null) {\n\t\t\t\t\treturn prefix + curie[1];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn uri;\n\t}\n\n}", "public enum WampMessageHeader {\n\tWAMP_MESSAGE_TYPE, PRINCIPAL, WEBSOCKET_SESSION_ID, WAMP_SESSION\n}", "public class WelcomeMessage extends WampMessage {\n\tpublic static final int PROTOCOL_VERSION = 1;\n\n\tprivate final String sessionId;\n\n\tprivate final int protocolVersion;\n\n\tprivate final String serverIdent;\n\n\tpublic WelcomeMessage(String sessionId, String serverIdent) {\n\t\tsuper(WampMessageType.WELCOME);\n\t\tthis.sessionId = sessionId;\n\t\tthis.serverIdent = serverIdent;\n\t\tthis.protocolVersion = PROTOCOL_VERSION;\n\t}\n\n\tpublic WelcomeMessage(JsonParser jp) throws IOException {\n\t\tsuper(WampMessageType.WELCOME);\n\n\t\tif (jp.nextToken() != JsonToken.VALUE_STRING) {\n\t\t\tthrow new IOException();\n\t\t}\n\t\tthis.sessionId = jp.getValueAsString();\n\n\t\tif (jp.nextToken() != JsonToken.VALUE_NUMBER_INT) {\n\t\t\tthrow new IOException();\n\t\t}\n\t\tthis.protocolVersion = jp.getValueAsInt();\n\n\t\tif (jp.nextToken() != JsonToken.VALUE_STRING) {\n\t\t\tthrow new IOException();\n\t\t}\n\t\tthis.serverIdent = jp.getValueAsString();\n\n\t}\n\n\t@Override\n\tpublic String getWebSocketSessionId() {\n\t\treturn this.sessionId;\n\t}\n\n\tpublic int getProtocolVersion() {\n\t\treturn this.protocolVersion;\n\t}\n\n\tpublic String getServerIdent() {\n\t\treturn this.serverIdent;\n\t}\n\n\t@Override\n\tpublic String toJson(JsonFactory jsonFactory) throws IOException {\n\t\ttry (StringWriter sw = new StringWriter();\n\t\t\t\tJsonGenerator jg = jsonFactory.createGenerator(sw)) {\n\t\t\tjg.writeStartArray();\n\t\t\tjg.writeNumber(getTypeId());\n\t\t\tjg.writeString(this.sessionId);\n\t\t\tjg.writeNumber(this.protocolVersion);\n\t\t\tjg.writeString(this.serverIdent);\n\t\t\tjg.writeEndArray();\n\t\t\tjg.close();\n\t\t\treturn sw.toString();\n\t\t}\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"WelcomeMessage [sessionId=\" + this.sessionId + \", protocolVersion=\"\n\t\t\t\t+ this.protocolVersion + \", serverIdent=\" + this.serverIdent + \"]\";\n\t}\n\n}" ]
import java.io.IOException; import java.util.Collections; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.util.Assert; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.SessionLimitExceededException; import org.springframework.web.socket.messaging.SubProtocolHandler; import com.fasterxml.jackson.core.JsonFactory; import ch.rasc.wampspring.message.CallErrorMessage; import ch.rasc.wampspring.message.CallMessage; import ch.rasc.wampspring.message.UnsubscribeMessage; import ch.rasc.wampspring.message.WampMessage; import ch.rasc.wampspring.message.WampMessageHeader; import ch.rasc.wampspring.message.WelcomeMessage;
/** * Copyright 2002-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ch.rasc.wampspring.config; /** * A WebSocket {@link SubProtocolHandler} for the WAMP v1 protocol. * * @author Rossen Stoyanchev * @author Andy Wilkinson * @author Ralph Schaer */ public class WampSubProtocolHandler implements SubProtocolHandler { public static final int MINIMUM_WEBSOCKET_MESSAGE_SIZE = 16 * 1024 + 256; private static final Log logger = LogFactory.getLog(WampSubProtocolHandler.class); private static final String SERVER_IDENTIFIER = "wampspring/1.1"; private final JsonFactory jsonFactory; public WampSubProtocolHandler(JsonFactory jsonFactory) { this.jsonFactory = jsonFactory; } @Override public List<String> getSupportedProtocols() { return Collections.singletonList("wamp"); } /** * Handle incoming WebSocket messages from clients. */ @Override public void handleMessageFromClient(WebSocketSession session, WebSocketMessage<?> webSocketMessage, MessageChannel outputChannel) { Assert.isInstanceOf(TextMessage.class, webSocketMessage);
WampMessage wampMessage = null;
3
mkovatsc/iot-semantics
semantic-ide/src/main/java/ch/ethz/inf/vs/semantics/ide/rest/QueryResource.java
[ "public class N3Linter {\n\n\tpublic static ArrayList<SemanticsErrors> lint(String input) {\n\t\tArrayList<SemanticsErrors> errors = new ArrayList<SemanticsErrors>();\n\t\tN3Lexer nl = new N3Lexer(new ANTLRInputStream(input));\n\t\tCommonTokenStream ts = new CommonTokenStream(nl);\n\t\tN3Parser np = new N3Parser(ts);\n\t\tnp.addErrorListener(new ANTLRErrorListener() {\n\t\t\t@Override\n\t\t\tpublic void syntaxError(@NotNull Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, @NotNull String msg, RecognitionException e) {\n\t\t\t\terrors.add(new SemanticsErrors(line, charPositionInLine, msg));\n\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void reportAmbiguity(@NotNull Parser recognizer, @NotNull DFA dfa, int startIndex, int stopIndex, boolean exact, BitSet ambigAlts, @NotNull ATNConfigSet configs) {\n\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void reportAttemptingFullContext(@NotNull Parser recognizer, @NotNull DFA dfa, int startIndex, int stopIndex, BitSet conflictingAlts, @NotNull ATNConfigSet configs) {\n\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void reportContextSensitivity(@NotNull Parser recognizer, @NotNull DFA dfa, int startIndex, int stopIndex, int prediction, @NotNull ATNConfigSet configs) {\n\n\t\t\t}\n\t\t});\n\t\tnp.n3Doc();\n\t\treturn errors;\n\t}\n\n}", "public class Query {\n\tprivate int id;\n\tprivate boolean watch;\n\tprivate String name;\n\tprivate String input;\n\tprivate String query;\n\n\tpublic String getInput() {\n\t\treturn input;\n\t}\n\n\tpublic void setInput(String input) {\n\t\tthis.input = input;\n\t}\n\n\tpublic String getQuery() {\n\t\treturn query;\n\t}\n\n\tpublic void setQuery(String query) {\n\t\tthis.query = query;\n\t}\n\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(int id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic boolean isWatch() {\n\t\treturn watch;\n\t}\n\n\tpublic void setWatch(boolean watch) {\n\t\tthis.watch = watch;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n}", "public class QueryResult {\n\n\tprivate String result;\n\tprivate ArrayList<SemanticsErrors> errquery;\n\tprivate ArrayList<SemanticsErrors> errinput;\n\n\tpublic QueryResult() {\n\n\t}\n\n\tpublic QueryResult(String result, ArrayList<SemanticsErrors> errquery, ArrayList<SemanticsErrors> errinput) {\n\n\t\tthis.setResult(result);\n\t\tthis.setErrquery(errquery);\n\t\tthis.setErrinput(errinput);\n\t}\n\n\tpublic String getResult() {\n\t\treturn result;\n\t}\n\n\tpublic void setResult(String result) {\n\t\tthis.result = result;\n\t}\n\n\tpublic ArrayList<SemanticsErrors> getErrquery() {\n\t\treturn errquery;\n\t}\n\n\tpublic void setErrquery(ArrayList<SemanticsErrors> errquery) {\n\t\tthis.errquery = errquery;\n\t}\n\n\tpublic ArrayList<SemanticsErrors> getErrinput() {\n\t\treturn errinput;\n\t}\n\n\tpublic void setErrinput(ArrayList<SemanticsErrors> errinput) {\n\t\tthis.errinput = errinput;\n\t}\n}", "public class SemanticsErrors {\n\n\tprivate int line;\n\tprivate int charPositionInLine;\n\tprivate String msg;\n\n\tpublic SemanticsErrors() {\n\n\t}\n\n\tpublic SemanticsErrors(int line, int charPositionInLine, String msg) {\n\n\t\tthis.setLine(line);\n\t\tthis.setCharPositionInLine(charPositionInLine);\n\t\tthis.setMsg(msg);\n\t}\n\n\tpublic int getLine() {\n\t\treturn line;\n\t}\n\n\tpublic void setLine(int line) {\n\t\tthis.line = line;\n\t}\n\n\tpublic int getCharPositionInLine() {\n\t\treturn charPositionInLine;\n\t}\n\n\tpublic void setCharPositionInLine(int charPositionInLine) {\n\t\tthis.charPositionInLine = charPositionInLine;\n\t}\n\n\tpublic String getMsg() {\n\t\treturn msg;\n\t}\n\n\tpublic void setMsg(String msg) {\n\t\tthis.msg = msg;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"line \" + line + \":\" + charPositionInLine + \" \" + msg;\n\t}\n}", "public abstract class Workspace {\n\n\tprotected int id;\n\n\tHashMap<Integer, Query> queries = new HashMap<>();\n\n\tpublic abstract Device deleteDevice(int id);\n\n\tpublic abstract Device addDevice(Device msg);\n\n\tpublic abstract Collection<Device> getDevices();\n\n\tpublic abstract Device getDevice(int id);\n\n\tpublic abstract Device updateDevice(int id, Device msg);\n\n\tpublic abstract String executeQuery(String goal, String input, boolean raw) throws Exception;\n\n\tpublic abstract void clearAnswers();\n\n\tpublic Query addQuery(Query msg) {\n\n\t\tmsg.setId(queries.keySet().stream().reduce(0, Integer::max) + 1);\n\t\tqueries.put(msg.getId(), msg);\n\t\treturn msg;\n\t}\n\n\tpublic Collection<Query> getQueries() {\n\t\treturn queries.values();\n\t}\n\n\tpublic Query getQuery(int id) {\n\t\treturn queries.get(id);\n\t}\n\n\tpublic Query deleteQuery(int id) {\n\t\treturn queries.remove(id);\n\t}\n\n\tpublic Query updateQuery(int id, Query msg) {\n\n\t\tQuery d = queries.get(id);\n\t\td.setName(msg.getName());\n\t\td.setWatch(msg.isWatch());\n\t\td.setInput(msg.getInput());\n\t\td.setQuery(msg.getQuery());\n\t\treturn d;\n\t}\n\n\tpublic abstract Collection<String> getHints();\n\n\tpublic abstract String planMashup(String query, String input) throws Exception;\n\n\tpublic abstract void addAnswer(String n3Document);\n\n\tpublic abstract Backup loadBackup(Backup backup);\n\n\tpublic Backup getBackup() {\n\n\t\tBackup backup = new Backup();\n\t\tbackup.setDevices(getDevices());\n\t\tbackup.setQueries(getQueries());\n\t\treturn backup;\n\t}\n\n\tpublic abstract WorkspaceInfo getWorkspaceInfo();\n\n\tpublic abstract void setName(String name);\n\n\tpublic abstract void save();\n\n\tpublic void remove() {\n\t\ttry {\n\t\t\tgetFile().delete();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tpublic File getFile() throws IOException {\n\t\tFile file = new File(WorkspaceManager.getFolder(), \"workspace\"+id+\".json\");\n\t\tif (!file.exists()) {\n\t\t\tfile.createNewFile();\n\t\t}\n\t\treturn file;\n\t}\n}", "public class WorkspaceManager {\n\tprivate static volatile WorkspaceManager instance = null;\n\tprivate static File persistenceFolder;\n\tprivate static Object lock = new Object();\n\tprivate Map<Integer, Workspace> workspaces;\n\tprivate int ID;\n\n\tprivate WorkspaceManager() {\n\t\tworkspaces = new HashMap<>();\n\t\tID = 1;\n\t\tfor (File ws : getFolder().listFiles()) {\n\t\t\tObjectMapper mapper = new ObjectMapper(); // can reuse, share globally\n\t\t\ttry {\n\t\t\t\tWorkspaceInfo workspaceinfo = mapper.readValue(ws, WorkspaceInfo.class);\n\t\t\t\tcreateWorkspace(workspaceinfo);\n\t\t\t} catch (Exception e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static WorkspaceManager getInstance() {\n\t\tif (instance == null) {\n\t\t\tsynchronized (WorkspaceManager.class) {\n\t\t\t\tif (instance == null) {\n\t\t\t\t\tinstance = new WorkspaceManager();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn instance;\n\t}\n\n\tpublic static File getFolder() {\n\t\tif (persistenceFolder==null) {\n\t\t\tsynchronized (lock) {\n\t\t\t\tif (persistenceFolder==null) {\n\t\t\t\t\tpersistenceFolder = new File(\"workspaces\");\n\t\t\t\t\tif (!persistenceFolder.exists()) {\n\t\t\t\t\t\tpersistenceFolder.mkdir();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn persistenceFolder;\n\t}\n\n\tpublic Workspace getWorkspace(int id) {\n\t\treturn workspaces.get(id);\n\t}\n\n\tpublic static Workspace get(int workspace) {\n\t\treturn getInstance().getWorkspace(workspace);\n\t}\n\n\tpublic static Collection<WorkspaceInfo> getWorkspaces() {\n\t\tArrayList<WorkspaceInfo> workspaces = new ArrayList<>();\n\t\tfor (Workspace w : getInstance().workspaces.values()) {\n\t\t\tworkspaces.add(w.getWorkspaceInfo());\n\t\t}\n\t\treturn workspaces;\n\t}\n\n\tpublic WorkspaceInfo deleteWorkspace(int id) {\n\t\tWorkspace workspace = get(id);\n\t\tWorkspaceInfo ws = workspace.getWorkspaceInfo();\n\t\tworkspaces.remove(id);\n\t\tworkspace.remove();\n\t\treturn ws;\n\t}\n\n\tpublic WorkspaceInfo createWorkspace(WorkspaceInfo ws) {\n\t\tsynchronized (this) {\n\t\t\tint id;\n\t\t\tif (!workspaces.containsKey(ws.getId()) && ws.getId()!=0) {\n\t\t\t\tid = ws.getId();\n\t\t\t\tID = Math.max(ID, id + 1);\n\t\t\t} else {\n\t\t\t\tid = ID;\n\t\t\t\tID++;\n\t\t\t}\n\t\t\tWorkspace workspace;\n\t\t\tif (\"remote\".equals(ws.getType())) {\n\n\t\t\t\tworkspace = new RemoteWorkspace(id, ws.getName(), ws.getUrl());\n\t\t\t} else {\n\n\t\t\t\tworkspace = new VirtualWorkspace(id, ws.getName());\n\t\t\t}\n\t\t\tworkspaces.put(id, workspace);\n\t\t\tif (ws.getBackup()!=null) {\n\t\t\t\tworkspace.loadBackup(ws.getBackup());\n\t\t\t}\n\t\t\tworkspace.save();\n\t\t\treturn workspace.getWorkspaceInfo();\n\t\t}\n\t}\n}" ]
import ch.ethz.inf.vs.semantics.ide.domain.N3Linter; import ch.ethz.inf.vs.semantics.ide.domain.Query; import ch.ethz.inf.vs.semantics.ide.domain.QueryResult; import ch.ethz.inf.vs.semantics.ide.domain.SemanticsErrors; import ch.ethz.inf.vs.semantics.ide.workspace.Workspace; import ch.ethz.inf.vs.semantics.ide.workspace.WorkspaceManager; import restx.annotations.*; import restx.factory.Component; import restx.security.PermitAll; import java.util.ArrayList; import java.util.Collection;
package ch.ethz.inf.vs.semantics.ide.rest; @Component @RestxResource public class QueryResource { @POST("/{workspace}/queries") @PermitAll public static Query postQuery(int workspace, Query msg) {
Workspace ws = WorkspaceManager.get(workspace);
5
badvision/jace
src/main/java/jace/state/StateManager.java
[ "public class Emulator {\r\n\r\n public static Emulator instance;\r\n public static EmulatorUILogic logic = new EmulatorUILogic();\r\n public static Thread mainThread;\r\n\r\n// public static void main(String... args) {\r\n// mainThread = Thread.currentThread();\r\n// instance = new Emulator(args);\r\n// }\r\n\r\n public static Apple2e computer;\r\n\r\n /**\r\n * Creates a new instance of Emulator\r\n * @param args\r\n */\r\n public Emulator(List<String> args) {\r\n instance = this;\r\n computer = new Apple2e();\r\n Configuration.buildTree();\r\n Configuration.loadSettings();\r\n mainThread = Thread.currentThread();\r\n applyConfiguration(args);\r\n }\r\n\r\n public void applyConfiguration(List<String> args) {\r\n Map<String, String> settings = new LinkedHashMap<>();\r\n if (args != null) {\r\n for (int i = 0; i < args.size(); i++) {\r\n if (args.get(i).startsWith(\"-\")) {\r\n String key = args.get(i).substring(1);\r\n if ((i + 1) < args.size()) {\r\n String val = args.get(i + 1);\r\n if (!val.startsWith(\"-\")) {\r\n settings.put(key, val);\r\n i++;\r\n } else {\r\n settings.put(key, \"true\");\r\n }\r\n } else {\r\n settings.put(key, \"true\");\r\n }\r\n } else {\r\n System.err.println(\"Did not understand parameter \" + args.get(i) + \", skipping.\");\r\n }\r\n }\r\n }\r\n Configuration.applySettings(settings);\r\n// EmulatorUILogic.registerDebugger();\r\n// computer.coldStart();\r\n }\r\n\r\n public static void resizeVideo() {\r\n// AbstractEmulatorFrame window = getFrame();\r\n// if (window != null) {\r\n// window.resizeVideo();\r\n// }\r\n }\r\n}", "public enum SoftSwitches {\r\n\r\n _80STORE(new MemorySoftSwitch(\"80Store\", 0x0c000, 0x0c001, 0x0c018, RAMEvent.TYPE.WRITE, false)),\r\n RAMRD(new MemorySoftSwitch(\"AuxRead (RAMRD)\", 0x0c002, 0x0c003, 0x0c013, RAMEvent.TYPE.WRITE, false)),\r\n RAMWRT(new MemorySoftSwitch(\"AuxWrite (RAMWRT)\", 0x0c004, 0x0c005, 0x0c014, RAMEvent.TYPE.WRITE, false)),\r\n CXROM(new MemorySoftSwitch(\"IntCXROM\", 0x0c006, 0x0c007, 0x0c015, RAMEvent.TYPE.WRITE, false)),\r\n AUXZP(new MemorySoftSwitch(\"AuxZeroPage\", 0x0c008, 0x0c009, 0x0c016, RAMEvent.TYPE.WRITE, false)),\r\n SLOTC3ROM(new MemorySoftSwitch(\"C3ROM\", 0x0c00a, 0x0c00b, 0x0c017, RAMEvent.TYPE.WRITE, false)),\r\n INTC8ROM(new IntC8SoftSwitch()),\r\n LCBANK1(new MemorySoftSwitch(\"LangCardBank1\",\r\n new int[]{0x0c088, 0x0c089, 0x0c08a, 0x0c08b, 0x0c08c, 0x0c08d, 0x0c08e, 0x0c08f},\r\n new int[]{0x0c080, 0x0c081, 0x0c082, 0x0c083, 0x0c084, 0x0c085, 0x0c086, 0x0c087},\r\n new int[]{0x0c011}, RAMEvent.TYPE.ANY, false)),\r\n LCRAM(new MemorySoftSwitch(\"LangCardRam/HRAMRD'\",\r\n new int[]{0x0c081, 0x0c082, 0x0c085, 0x0c086, 0x0c089, 0x0c08a, 0x0c08d, 0x0c08e},\r\n new int[]{0x0c080, 0x0c083, 0x0c084, 0x0c087, 0x0c088, 0x0c08b, 0x0c08c, 0x0c08f},\r\n new int[]{0x0c012}, RAMEvent.TYPE.ANY, false)),\r\n LCWRITE(new Memory2SoftSwitch(\"LangCardWrite\",\r\n new int[]{0x0c080, 0x0c082, 0x0c084, 0x0c086, 0x0c088, 0x0c08a, 0x0c08c, 0x0c08e},\r\n new int[]{0x0c081, 0x0c083, 0x0c085, 0x0c087, 0x0c089, 0x0c08b, 0x0c08d, 0x0c08f},\r\n null, RAMEvent.TYPE.ANY, true)),\r\n //Renamed as per Sather 5-7\r\n _80COL(new VideoSoftSwitch(\"80ColumnVideo (80COL/80VID)\", 0x0c00c, 0x0c00d, 0x0c01f, RAMEvent.TYPE.WRITE, false)),\r\n ALTCH(new VideoSoftSwitch(\"Mousetext\", 0x0c00e, 0x0c00f, 0x0c01e, RAMEvent.TYPE.WRITE, false){\r\n @Override\r\n public void stateChanged() {\r\n super.stateChanged();\r\n computer.getVideo().forceRefresh();\r\n }\r\n }),\r\n TEXT(new VideoSoftSwitch(\"Text\", 0x0c050, 0x0c051, 0x0c01a, RAMEvent.TYPE.ANY, true)),\r\n MIXED(new VideoSoftSwitch(\"Mixed\", 0x0c052, 0x0c053, 0x0c01b, RAMEvent.TYPE.ANY, false)),\r\n PAGE2(new VideoSoftSwitch(\"Page2\", 0x0c054, 0x0c055, 0x0c01c, RAMEvent.TYPE.ANY, false) {\r\n @Override\r\n public void stateChanged() {\r\n// if (computer == null) {\r\n// return;\r\n// }\r\n// if (computer == null && computer.getMemory() == null) {\r\n// return;\r\n// }\r\n// if (computer == null && computer.getVideo() == null) {\r\n// return;\r\n// }\r\n\r\n // PAGE2 is a hybrid switch; 80STORE ? memory : video\r\n if (_80STORE.isOn()) {\r\n computer.getMemory().configureActiveMemory();\r\n } else {\r\n computer.getVideo().configureVideoMode();\r\n }\r\n }\r\n }),\r\n HIRES(new VideoSoftSwitch(\"Hires\", 0x0c056, 0x0c057, 0x0c01d, RAMEvent.TYPE.ANY, false)),\r\n DHIRES(new VideoSoftSwitch(\"Double-hires\", 0x0c05f, 0x0c05e, 0x0c07f, RAMEvent.TYPE.ANY, false)),\r\n PB0(new MemorySoftSwitch(\"Pushbutton0\", -1, -1, 0x0c061, RAMEvent.TYPE.ANY, null)),\r\n PB1(new MemorySoftSwitch(\"Pushbutton1\", -1, -1, 0x0c062, RAMEvent.TYPE.ANY, null)),\r\n PB2(new MemorySoftSwitch(\"Pushbutton2\", -1, -1, 0x0c063, RAMEvent.TYPE.ANY, null)),\r\n PDLTRIG(new SoftSwitch(\"PaddleTrigger\",\r\n null,\r\n new int[]{0x0c070, 0x0c071, 0x0c072, 0x0c073, 0x0c074, 0x0c075, 0x0c076, 0x0c077,\r\n 0x0c078, 0x0c079, 0x0c07a, 0x0c07b, 0x0c07c, 0x0c07d, 0x0c07e, 0x0c07f},\r\n null, RAMEvent.TYPE.ANY, false) {\r\n @Override\r\n protected byte readSwitch() {\r\n setState(true);\r\n return computer.getVideo().getFloatingBus();\r\n }\r\n\r\n @Override\r\n public void stateChanged() {\r\n }\r\n }),\r\n PDL0(new MemorySoftSwitch(\"Paddle0\", -1, -1, 0x0c064, RAMEvent.TYPE.ANY, false)),\r\n PDL1(new MemorySoftSwitch(\"Paddle1\", -1, -1, 0x0c065, RAMEvent.TYPE.ANY, false)),\r\n PDL2(new MemorySoftSwitch(\"Paddle2\", -1, -1, 0x0c066, RAMEvent.TYPE.ANY, false)),\r\n PDL3(new MemorySoftSwitch(\"Paddle3\", -1, -1, 0x0c067, RAMEvent.TYPE.ANY, false)),\r\n AN0(new MemorySoftSwitch(\"Annunciator0\", 0x0c058, 0x0c059, -1, RAMEvent.TYPE.ANY, false)),\r\n AN1(new MemorySoftSwitch(\"Annunciator1\", 0x0c05a, 0x0c05b, -1, RAMEvent.TYPE.ANY, false)),\r\n AN2(new MemorySoftSwitch(\"Annunciator2\", 0x0c05c, 0x0c05d, -1, RAMEvent.TYPE.ANY, false)),\r\n AN3(new MemorySoftSwitch(\"Annunciator3\", 0x0c05e, 0x0c05f, -1, RAMEvent.TYPE.ANY, false)),\r\n KEYBOARD(new KeyboardSoftSwitch(\r\n \"Keyboard\",\r\n new int[]{0x0c010, 0x0c11, 0x0c012, 0x0c013, 0x0c014, 0x0c015, 0x0c016, 0x0c017,\r\n 0x0c018, 0x0c019, 0x0c01a, 0x0c01b, 0x0c01c, 0x0c01d, 0x0c01e, 0x0c01f},\r\n null,\r\n new int[]{0x0c000, 0x0c001, 0x0c002, 0x0c003, 0x0c004, 0x0c005, 0x0c006, 0x0c007,\r\n 0x0c008, 0x0c009, 0x0c00a, 0x0c00b, 0x0c00c, 0x0c00d, 0x0c00e, 0x0c00f, 0x0c010},\r\n RAMEvent.TYPE.WRITE, false)),\r\n //C010 should clear keyboard strobe when read as well\r\n KEYBOARD_STROBE_READ(new SoftSwitch(\"KeyStrobe_Read\", 0x0c010, -1, -1, RAMEvent.TYPE.READ, false) {\r\n @Override\r\n protected byte readSwitch() {\r\n return computer.getVideo().getFloatingBus();\r\n }\r\n\r\n @Override\r\n public void stateChanged() {\r\n KEYBOARD.getSwitch().setState(false);\r\n }\r\n }),\r\n TAPEOUT(new MemorySoftSwitch(\"TapeOut\", 0x0c020, 0x0c020, 0x0c060, RAMEvent.TYPE.ANY, false)),\r\n VBL(new VideoSoftSwitch(\"VBL\", -1, -1, 0x0c019, RAMEvent.TYPE.ANY, false)),\r\n FLOATING_BUS(new SoftSwitch(\"FloatingBus\", null, null, new int[]{0x0C050, 0x0C051, 0x0C052, 0x0C053, 0x0C054}, RAMEvent.TYPE.READ, null) {\r\n @Override\r\n protected byte readSwitch() {\r\n if (computer.getVideo() == null) {\r\n return 0;\r\n }\r\n return computer.getVideo().getFloatingBus();\r\n }\r\n\r\n @Override\r\n public void stateChanged() {\r\n }\r\n });\r\n\r\n /*\r\n 2C:VBL (new MemorySoftSwitch(0x0c070, 0x0*, 0x0c041, RAMEvent.TYPE.ANY, false)),\r\n 2C:VBLENABLE (new MemorySoftSwitch(0x0c05a, 0x0c05b, 0x0-, RAMEvent.TYPE.ANY, false)),\r\n 2C:XINT (new MemorySoftSwitch(0x0c015 (r), c048-c04f (r/w), 0x0-, 0x0-, RAMEvent.TYPE.ANY, false)),\r\n 2C:YINT (new MemorySoftSwitch(0x0c017 (r), c048-c04f (r/w), 0x0-, 0x0-, RAMEvent.TYPE.ANY, false)),\r\n 2C:MBUTTON (new MemorySoftSwitch(0x0*, 0x0*, 0x0c063, RAMEvent.TYPE.ANY, false)),\r\n 2C:80/40 switch (new MemorySoftSwitch(0x0*, 0x0*, 0x0c060, RAMEvent.TYPE.ANY, false)),\r\n 2C:XDirection (new MemorySoftSwitch(0x0*, 0x0*, 0x0c066, RAMEvent.TYPE.ANY, false)),\r\n 2C:YDirection (new MemorySoftSwitch(0x0*, 0x0*, 0x0c067, RAMEvent.TYPE.ANY, false)), \r\n */\r\n private final SoftSwitch softswitch;\r\n\r\n /**\r\n * Creates a new instance of SoftSwitches\r\n */\r\n private SoftSwitches(SoftSwitch softswitch) {\r\n this.softswitch = softswitch;\r\n }\r\n\r\n public SoftSwitch getSwitch() {\r\n return softswitch;\r\n }\r\n\r\n public boolean getState() {\r\n return softswitch.getState();\r\n }\r\n\r\n public final boolean isOn() {\r\n return softswitch.getState();\r\n }\r\n\r\n public final boolean isOff() {\r\n return !softswitch.getState();\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return softswitch.toString();\r\n }\r\n}", "public interface Reconfigurable {\n public String getName();\n public String getShortName();\n public void reconfigure();\n}", "public abstract class Computer implements Reconfigurable {\n\n public RAM memory;\n public CPU cpu;\n public Video video;\n public Keyboard keyboard;\n public StateManager stateManager;\n public Motherboard motherboard;\n public boolean romLoaded;\n @ConfigurableField(category = \"advanced\", name = \"State management\", shortName = \"rewind\", description = \"This enables rewind support, but consumes a lot of memory when active.\")\n public boolean enableStateManager;\n public final SoundMixer mixer;\n final private BooleanProperty runningProperty = new SimpleBooleanProperty(false);\n\n /**\n * Creates a new instance of Computer\n */\n public Computer() {\n keyboard = new Keyboard(this);\n mixer = new SoundMixer(this);\n romLoaded = false;\n }\n\n public RAM getMemory() {\n return memory;\n }\n\n public Motherboard getMotherboard() {\n return motherboard;\n }\n\n ChangeListener<Boolean> runningPropertyListener = (prop, oldVal, newVal) -> runningProperty.set(newVal);\n public void setMotherboard(Motherboard m) {\n if (motherboard != null && motherboard.isRunning()) {\n motherboard.suspend();\n }\n motherboard = m;\n }\n\n public BooleanProperty getRunningProperty() {\n return runningProperty;\n }\n \n public boolean isRunning() {\n return getRunningProperty().get();\n }\n \n public void notifyVBLStateChanged(boolean state) {\n for (Optional<Card> c : getMemory().cards) {\n c.ifPresent(card -> card.notifyVBLStateChanged(state));\n }\n if (state && stateManager != null) {\n stateManager.notifyVBLActive();\n }\n }\n\n public void setMemory(RAM memory) {\n if (this.memory != memory) {\n if (this.memory != null) {\n this.memory.detach();\n }\n memory.attach();\n }\n this.memory = memory;\n }\n\n public void waitForNextCycle() {\n //@TODO IMPLEMENT TIMER SLEEP CODE!\n }\n\n public Video getVideo() {\n return video;\n }\n\n public void setVideo(Video video) {\n this.video = video;\n }\n\n public CPU getCpu() {\n return cpu;\n }\n\n public void setCpu(CPU cpu) {\n this.cpu = cpu;\n }\n\n public void loadRom(String path) throws IOException {\n memory.loadRom(path);\n romLoaded = true;\n }\n\n public void deactivate() {\n if (cpu != null) {\n cpu.suspend();\n }\n if (motherboard != null) {\n motherboard.suspend();\n }\n if (video != null) {\n video.suspend(); \n }\n if (mixer != null) {\n mixer.detach();\n }\n }\n\n @InvokableAction(\n name = \"Cold boot\",\n description = \"Process startup sequence from power-up\",\n category = \"general\",\n alternatives = \"Full reset;reset emulator\",\n consumeKeyEvent = true,\n defaultKeyMapping = {\"Ctrl+Shift+Backspace\", \"Ctrl+Shift+Delete\"})\n public void invokeColdStart() {\n if (!romLoaded) {\n Thread delayedStart = new Thread(() -> {\n while (!romLoaded) {\n Thread.yield();\n }\n coldStart();\n });\n delayedStart.start();\n } else {\n coldStart();\n }\n }\n\n public abstract void coldStart();\n\n @InvokableAction(\n name = \"Warm boot\",\n description = \"Process user-initatiated reboot (ctrl+apple+reset)\",\n category = \"general\",\n alternatives = \"reboot;reset;three-finger-salute;restart\",\n defaultKeyMapping = {\"Ctrl+Ignore Alt+Ignore Meta+Backspace\", \"Ctrl+Ignore Alt+Ignore Meta+Delete\"})\n public void invokeWarmStart() {\n warmStart();\n }\n\n public abstract void warmStart();\n\n public Keyboard getKeyboard() {\n return this.keyboard;\n }\n\n protected abstract void doPause();\n\n protected abstract void doResume();\n\n @InvokableAction(name = \"Pause\", description = \"Stops the computer, allowing reconfiguration of core elements\", alternatives = \"freeze;halt\", defaultKeyMapping = {\"meta+pause\", \"alt+pause\"})\n public boolean pause() {\n boolean result = getRunningProperty().get();\n doPause();\n getRunningProperty().set(false);\n return result;\n }\n\n @InvokableAction(name = \"Resume\", description = \"Resumes the computer if it was previously paused\", alternatives = \"unpause;unfreeze;resume;play\", defaultKeyMapping = {\"meta+shift+pause\", \"alt+shift+pause\"})\n public void resume() {\n doResume();\n getRunningProperty().set(true);\n }\n\n @Override\n public void reconfigure() {\n mixer.reconfigure();\n if (enableStateManager) {\n stateManager = StateManager.getInstance(this);\n } else {\n stateManager = null;\n StateManager.getInstance(this).invalidate();\n }\n }\n}", "@Stateful\r\npublic class PagedMemory {\r\n\r\n public enum Type {\r\n\r\n CARD_FIRMWARE(0x0c800),\r\n LANGUAGE_CARD(0x0d000),\r\n FIRMWARE_MAIN(0x0d000),\r\n FIRMWARE_80COL(0x0c300),\r\n SLOW_ROM(0x0c100),\r\n RAM(0x0000);\r\n protected int baseAddress;\r\n\r\n private Type(int newBase) {\r\n baseAddress = newBase;\r\n }\r\n\r\n public int getBaseAddress() {\r\n return baseAddress;\r\n }\r\n }\r\n // This is a fixed array, used for internal-only!!\r\n @Stateful\r\n public byte[][] internalMemory = new byte[0][];\r\n @Stateful\r\n public Type type;\r\n\r\n /**\r\n * Creates a new instance of PagedMemory\r\n */\r\n Computer computer;\r\n public PagedMemory(int size, Type memType, Computer computer) {\r\n this.computer = computer;\r\n type = memType;\r\n internalMemory = new byte[size >> 8][256];\r\n for (int i = 0; i < size; i += 256) {\r\n byte[] b = new byte[256];\r\n Arrays.fill(b, (byte) 0x00);\r\n internalMemory[i >> 8] = b;\r\n }\r\n }\r\n\r\n public PagedMemory(byte[] romData, Type memType) {\r\n type = memType;\r\n loadData(romData);\r\n }\r\n\r\n public void loadData(byte[] romData) {\r\n for (int i = 0; i < romData.length; i += 256) {\r\n byte[] b = new byte[256];\r\n for (int j = 0; j < 256; j++) {\r\n b[j] = romData[i + j];\r\n }\r\n internalMemory[i >> 8] = b;\r\n }\r\n }\r\n\r\n public void loadData(byte[] romData, int offset, int length) {\r\n for (int i = 0; i < length; i += 256) {\r\n byte[] b = new byte[256];\r\n for (int j = 0; j < 256; j++) {\r\n b[j] = romData[offset + i + j];\r\n }\r\n internalMemory[i >> 8] = b;\r\n }\r\n }\r\n\r\n public byte[][] getMemory() {\r\n return internalMemory;\r\n }\r\n\r\n public byte[] get(int pageNumber) {\r\n return internalMemory[pageNumber];\r\n }\r\n\r\n public void set(int pageNumber, byte[] bank) {\r\n internalMemory[pageNumber] = bank;\r\n }\r\n\r\n public byte[] getMemoryPage(int memoryBase) {\r\n int offset = memoryBase - type.baseAddress;\r\n// int page = offset >> 8;\r\n int page = (offset >> 8) & 0x0ff;\r\n// return get(page);\r\n return internalMemory[page];\r\n }\r\n\r\n public void setBanks(int sourceStart, int sourceLength, int targetStart, PagedMemory source) {\r\n for (int i = 0; i < sourceLength; i++) {\r\n set(targetStart + i, source.get(sourceStart + i));\r\n }\r\n }\r\n\r\n public byte readByte(int address) {\r\n return getMemoryPage(address)[address & 0x0ff];\r\n }\r\n\r\n public void writeByte(int address, byte value) {\r\n byte[] page = getMemoryPage(address);\r\n StateManager.markDirtyValue(page, computer);\r\n getMemoryPage(address)[address & 0x0ff] = value;\r\n }\r\n\r\n public void fillBanks(PagedMemory source) {\r\n byte[][] sourceMemory = source.getMemory();\r\n int sourceBase = source.type.getBaseAddress() >> 8;\r\n int thisBase = type.getBaseAddress() >> 8;\r\n int start = sourceBase > thisBase ? sourceBase : thisBase;\r\n int sourceEnd = sourceBase + source.getMemory().length;\r\n int thisEnd = thisBase + getMemory().length;\r\n int end = sourceEnd < thisEnd ? sourceEnd : thisEnd;\r\n for (int i = start; i < end; i++) {\r\n set(i - thisBase, sourceMemory[i - sourceBase]);\r\n }\r\n }\r\n}", "@Stateful\r\npublic abstract class Video extends Device {\r\n\r\n @Stateful\r\n WritableImage video;\r\n WritableImage visible;\r\n VideoWriter currentWriter;\r\n private byte floatingBus = 0;\r\n private int width = 560;\r\n private int height = 192;\r\n @Stateful\r\n public int x = 0;\r\n @Stateful\r\n public int y = 0;\r\n @Stateful\r\n public int scannerAddress;\r\n @Stateful\r\n public int vPeriod = 0;\r\n @Stateful\r\n public int hPeriod = 0;\r\n static final public int CYCLES_PER_LINE = 65;\r\n static final public int TOTAL_LINES = 262;\r\n static final public int APPLE_CYCLES_PER_LINE = 40;\r\n static final public int APPLE_SCREEN_LINES = 192;\r\n static final public int HBLANK = CYCLES_PER_LINE - APPLE_CYCLES_PER_LINE;\r\n static final public int VBLANK = (TOTAL_LINES - APPLE_SCREEN_LINES) * CYCLES_PER_LINE;\r\n static public int[] textOffset;\r\n static public int[] hiresOffset;\r\n static public int[] textRowLookup;\r\n static public int[] hiresRowLookup;\r\n private boolean screenDirty;\r\n private boolean lineDirty;\r\n private boolean isVblank = false;\r\n static VideoWriter[][] writerCheck = new VideoWriter[40][192];\r\n\r\n static {\r\n textOffset = new int[192];\r\n hiresOffset = new int[192];\r\n textRowLookup = new int[0x0400];\r\n hiresRowLookup = new int[0x02000];\r\n for (int i = 0; i < 192; i++) {\r\n textOffset[i] = calculateTextOffset(i >> 3);\r\n hiresOffset[i] = calculateHiresOffset(i);\r\n }\r\n for (int i = 0; i < 0x0400; i++) {\r\n textRowLookup[i] = identifyTextRow(i);\r\n }\r\n for (int i = 0; i < 0x2000; i++) {\r\n hiresRowLookup[i] = identifyHiresRow(i);\r\n }\r\n }\r\n private int forceRedrawRowCount = 0;\r\n Thread updateThread;\r\n\r\n /**\r\n * Creates a new instance of Video\r\n *\r\n * @param computer\r\n */\r\n public Video(Computer computer) {\r\n super(computer);\r\n suspend();\r\n video = new WritableImage(560, 192);\r\n visible = new WritableImage(560, 192);\r\n vPeriod = 0;\r\n hPeriod = 0;\r\n _forceRefresh();\r\n }\r\n\r\n public void setWidth(int w) {\r\n width = w;\r\n }\r\n\r\n public int getWidth() {\r\n return width;\r\n }\r\n\r\n public void setHeight(int h) {\r\n height = h;\r\n }\r\n\r\n public int getHeight() {\r\n return height;\r\n }\r\n\r\n public VideoWriter getCurrentWriter() {\r\n return currentWriter;\r\n }\r\n\r\n public void setCurrentWriter(VideoWriter currentWriter) {\r\n if (this.currentWriter != currentWriter || currentWriter.isMixed()) {\r\n this.currentWriter = currentWriter;\r\n forceRedrawRowCount = APPLE_SCREEN_LINES + 1;\r\n }\r\n }\r\n @ConfigurableField(category = \"video\", name = \"Min. Screen Refesh\", defaultValue = \"15\", description = \"Minimum number of miliseconds to wait before trying to redraw.\")\r\n public static int MIN_SCREEN_REFRESH = 15;\r\n\r\n Runnable redrawScreen = () -> {\r\n if (visible != null && video != null) {\r\n// if (computer.getRunningProperty().get()) {\r\n screenDirty = false;\r\n visible.getPixelWriter().setPixels(0, 0, 560, 192, video.getPixelReader(), 0, 0);\r\n// }\r\n }\r\n };\r\n\r\n public void redraw() {\r\n javafx.application.Platform.runLater(redrawScreen);\r\n }\r\n\r\n public void vblankStart() {\r\n if (screenDirty && isRunning()) {\r\n redraw();\r\n }\r\n }\r\n\r\n abstract public void vblankEnd();\r\n\r\n abstract public void hblankStart(WritableImage screen, int y, boolean isDirty);\r\n\r\n public void setScannerLocation(int loc) {\r\n scannerAddress = loc;\r\n }\r\n\r\n @Override\r\n public void tick() {\r\n setScannerLocation(currentWriter.getYOffset(y));\r\n setFloatingBus(computer.getMemory().readRaw(scannerAddress + x));\r\n if (hPeriod > 0) {\r\n hPeriod--;\r\n if (hPeriod == 0) {\r\n x = -1;\r\n }\r\n } else {\r\n if (!isVblank && x < APPLE_CYCLES_PER_LINE) {\r\n draw();\r\n }\r\n if (x >= APPLE_CYCLES_PER_LINE - 1) {\r\n int yy = y + hblankOffsetY;\r\n if (yy < 0) {\r\n yy += APPLE_SCREEN_LINES;\r\n }\r\n if (yy >= APPLE_SCREEN_LINES) {\r\n yy -= (TOTAL_LINES - APPLE_SCREEN_LINES);\r\n }\r\n x = hblankOffsetX - 1;\r\n if (!isVblank) {\r\n if (lineDirty) {\r\n screenDirty = true;\r\n currentWriter.clearDirty(y);\r\n }\r\n hblankStart(video, y, lineDirty);\r\n lineDirty = false;\r\n forceRedrawRowCount--;\r\n }\r\n hPeriod = HBLANK;\r\n y++;\r\n if (y >= APPLE_SCREEN_LINES) {\r\n if (!isVblank) {\r\n y = APPLE_SCREEN_LINES - (TOTAL_LINES - APPLE_SCREEN_LINES);\r\n isVblank = true;\r\n vblankStart();\r\n computer.getMotherboard().vblankStart();\r\n } else {\r\n y = 0;\r\n isVblank = false;\r\n vblankEnd();\r\n computer.getMotherboard().vblankEnd();\r\n }\r\n }\r\n }\r\n }\r\n x++;\r\n }\r\n\r\n abstract public void configureVideoMode();\r\n\r\n protected static int byteDoubler(byte b) {\r\n int num\r\n = // Skip hi-bit because it's not used in display\r\n // ((b&0x080)<<7) |\r\n ((b & 0x040) << 6)\r\n | ((b & 0x020) << 5)\r\n | ((b & 0x010) << 4)\r\n | ((b & 0x08) << 3)\r\n | ((b & 0x04) << 2)\r\n | ((b & 0x02) << 1)\r\n | (b & 0x01);\r\n return num | (num << 1);\r\n }\r\n @ConfigurableField(name = \"Waits per cycle\", category = \"Advanced\", description = \"Adjust the delay for the scanner\")\r\n public static int waitsPerCycle = 0;\r\n @ConfigurableField(name = \"Hblank X offset\", category = \"Advanced\", description = \"Adjust where the hblank period starts relative to the start of the line\")\r\n public static int hblankOffsetX = -29;\r\n @ConfigurableField(name = \"Hblank Y offset\", category = \"Advanced\", description = \"Adjust which line the HBLANK starts on (0=current, 1=next, etc)\")\r\n public static int hblankOffsetY = 1;\r\n\r\n private void draw() {\r\n if (lineDirty || forceRedrawRowCount > 0 || currentWriter.isRowDirty(y)) {\r\n lineDirty = true;\r\n currentWriter.displayByte(video, x, y, textOffset[y], hiresOffset[y]);\r\n }\r\n setWaitCycles(waitsPerCycle);\r\n doPostDraw();\r\n }\r\n\r\n static public int calculateHiresOffset(int y) {\r\n return calculateTextOffset(y >> 3) + ((y & 7) << 10);\r\n }\r\n\r\n static public int calculateTextOffset(int y) {\r\n return ((y & 7) << 7) + 40 * (y >> 3);\r\n }\r\n\r\n static public int identifyTextRow(int y) {\r\n //floor((x-1024)/128) + floor(((x-1024)%128)/40)*8\r\n // Caller must check result is <= 23, if so then they are in a screenhole!\r\n return (y >> 7) + (((y & 0x7f) / 40) << 3);\r\n }\r\n\r\n static public int identifyHiresRow(int y) {\r\n int blockOffset = identifyTextRow(y & 0x03ff);\r\n // Caller must check results is > 0, if not then they are in a screenhole!\r\n if (blockOffset > 23) {\r\n return -1;\r\n }\r\n return ((y >> 10) & 7) + (blockOffset << 3);\r\n }\r\n\r\n public abstract void doPostDraw();\r\n\r\n public byte getFloatingBus() {\r\n return floatingBus;\r\n }\r\n\r\n private void setFloatingBus(byte floatingBus) {\r\n this.floatingBus = floatingBus;\r\n }\r\n\r\n @InvokableAction(name = \"Refresh screen\",\r\n category = \"display\",\r\n description = \"Marks screen contents as changed, forcing full screen redraw\",\r\n alternatives = \"redraw\",\r\n defaultKeyMapping = {\"ctrl+shift+r\"})\r\n public static final void forceRefresh() {\r\n if (Emulator.computer != null && Emulator.computer.video != null) {\r\n Emulator.computer.video._forceRefresh();\r\n }\r\n }\r\n\r\n private void _forceRefresh() {\r\n lineDirty = true;\r\n screenDirty = true;\r\n forceRedrawRowCount = APPLE_SCREEN_LINES + 1;\r\n }\r\n\r\n @Override\r\n public String getShortName() {\r\n return \"vid\";\r\n }\r\n\r\n public Image getFrameBuffer() {\r\n return visible;\r\n }\r\n}\r" ]
import jace.Emulator; import jace.apple2e.SoftSwitches; import jace.config.ConfigurableField; import jace.config.InvokableAction; import jace.config.Reconfigurable; import jace.core.Computer; import jace.core.PagedMemory; import jace.core.Video; import java.awt.image.BufferedImage; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import java.util.logging.Level; import java.util.logging.Logger; import javafx.scene.image.Image; import javafx.scene.image.WritableImage; import javafx.scene.input.KeyCode;
/* * Copyright (C) 2012 Brendan Robert (BLuRry) [email protected]. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ package jace.state; /** * * @author Brendan Robert (BLuRry) [email protected] */ public class StateManager implements Reconfigurable { private static StateManager instance; public static StateManager getInstance(Computer computer) { if (instance == null) { instance = new StateManager(computer); } return instance; } State alphaState; Set<ObjectGraphNode> allStateVariables; WeakHashMap<Object, ObjectGraphNode> objectLookup; long maxMemory = -1; long freeRequired = -1;
@ConfigurableField(category = "Emulator", name = "Max states", description = "How many states can be captured, oldest states are automatically truncated.", defaultValue = "150")
0
lanixzcj/LoveTalkClient
src/com/example/lovetalk/activity/NewFriendActivity.java
[ "public class NewFriendAdapter extends BaseListAdapter<AddRequest> {\n\n\tpublic NewFriendAdapter(Context context, List<AddRequest> list) {\n\t\tsuper(context, list);\n\t\t// TODO Auto-generated constructor stub\n\t}\n\n\t@Override\n\tpublic View getView(int position, View conView, ViewGroup parent) {\n\t\t// TODO Auto-generated method stub\n\t\tif (conView == null) {\n\t\t\tLayoutInflater mInflater = LayoutInflater.from(ctx);\n\t\t\tconView = mInflater.inflate(R.layout.contact_add_friend_item, null);\n\t\t}\n\t\tfinal AddRequest addRequest = datas.get(position);\n\t\tTextView nameView = ViewHolder.findViewById(conView, R.id.name);\n\t\tImageView avatarView = ViewHolder.findViewById(conView, R.id.avatar);\n\t\tfinal Button addBtn = ViewHolder.findViewById(conView, R.id.add);\n\n\t\tString avatarUrl = getAvatarUrl(addRequest.getFromUser());\n\t\tUserService.displayAvatar(avatarUrl, avatarView);\n\n\t\tint status = addRequest.getStatus();\n\t\tif (status == AddRequest.STATUS_WAIT) {\n\t\t\taddBtn.setOnClickListener(new OnClickListener() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(View arg0) {\n\t\t\t\t\t// TODO Auto-generated method stub\n\t\t\t\t\tagreeAdd(addBtn, addRequest);\n\t\t\t\t}\n\t\t\t});\n\t\t} else if (status == AddRequest.STATUS_DONE) {\n\t\t\ttoAgreedTextView(addBtn);\n\t\t}\n\t\tnameView.setText(addRequest.getFromUser().getUsername());\n\t\treturn conView;\n\t}\n\n\tpublic String getAvatarUrl(AVUser user) {\n\t\tAVFile avatar = user.getAVFile(\"avatar\");\n\t\tif (avatar != null) {\n\t\t\treturn avatar.getUrl();\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic void toAgreedTextView(Button addBtn) {\n\t\taddBtn.setText(R.string.agreed);\n\t\taddBtn.setBackgroundDrawable(null);\n\t\taddBtn.setTextColor(Utils.getColor(R.color.base_color_text_black));\n\t\taddBtn.setEnabled(false);\n\t}\n\n\tprivate void agreeAdd(final Button addBtn, final AddRequest addRequest) {\n\t\tAddRequestService.agreeAddRequest(addRequest, new SaveCallback() {\n\t\t\t@Override\n\t\t\tpublic void done(AVException e) {\n\t\t\t\ttoAgreedTextView(addBtn);\n\t\t\t}\n\t\t});\n\t}\n}", "@AVClassName(\"AddRequest\")\npublic class AddRequest extends AVObject {\n\tpublic static final int STATUS_WAIT = 0;\n\tpublic static final int STATUS_DONE = 1;\n\n\tpublic static final String FROM_USER = \"fromUser\";\n\tpublic static final String TO_USER = \"toUser\";\n\tpublic static final String STATUS = \"status\";\n\t//User fromUser;\n\t//User toUser;\n\t//int status;\n\n\tpublic AddRequest() {\n\t}\n\n\tpublic AVUser getFromUser() {\n\t\treturn getAVUser(FROM_USER, AVUser.class);\n\t}\n\n\tpublic void setFromUser(AVUser fromUser) {\n\t\tput(FROM_USER, fromUser);\n\t}\n\n\tpublic AVUser getToUser() {\n\t\treturn getAVUser(TO_USER, AVUser.class);\n\t}\n\n\tpublic void setToUser(AVUser toUser) {\n\t\tput(TO_USER, toUser);\n\t}\n\n\tpublic int getStatus() {\n\t\treturn getInt(STATUS);\n\t}\n\n\tpublic void setStatus(int status) {\n\t\tput(STATUS, status);\n\t}\n}", "public class AddRequestService {\n\tpublic static int countAddRequests() throws AVException {\n\t\tAVQuery<AddRequest> q = AVObject.getQuery(AddRequest.class);\n\t\tq.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);\n\t\tq.whereEqualTo(AddRequest.TO_USER, AVUser.getCurrentUser());\n\t\ttry {\n\t\t\treturn q.count();\n\t\t} catch (AVException e) {\n\t\t\tif (e.getCode() == AVException.CACHE_MISS) {\n\t\t\t\treturn 0;\n\t\t\t} else {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static List<AddRequest> findAddRequests() throws AVException {\n\t\tAVUser user = AVUser.getCurrentUser();\n\t\tAVQuery<AddRequest> q = AVObject.getQuery(AddRequest.class);\n\t\tq.include(AddRequest.FROM_USER);\n\t\tq.whereEqualTo(AddRequest.TO_USER, user);\n\t\tq.orderByDescending(\"createdAt\");\n\t\tq.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);\n\t\treturn q.find();\n\t}\n\n\tpublic static boolean hasAddRequest() throws AVException {\n\t\tPreferenceMap preferenceMap = PreferenceMap.getMyPrefDao(DemoApplication.context);\n\t\tint addRequestN = preferenceMap.getAddRequestN();\n\t\tint requestN = countAddRequests();\n\t\tif (requestN > addRequestN) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic static void agreeAddRequest(final AddRequest addRequest, final SaveCallback saveCallback) {\n\t\tUserService.addFriend(addRequest.getFromUser().getObjectId(), new SaveCallback() {\n\t\t\t@Override\n\t\t\tpublic void done(AVException e) {\n\t\t\t\tif (e != null) {\n\t\t\t\t\tif (e.getCode() == AVException.DUPLICATE_VALUE) {\n\t\t\t\t\t\taddRequest.setStatus(AddRequest.STATUS_DONE);\n\t\t\t\t\t\taddRequest.saveInBackground(saveCallback);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tsaveCallback.done(e);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\taddRequest.setStatus(AddRequest.STATUS_DONE);\n\t\t\t\t\taddRequest.saveInBackground(saveCallback);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic static void createAddRequest(AVUser toUser) throws Exception {\n\t\tAVUser curUser = AVUser.getCurrentUser();\n\t\tAVQuery<AddRequest> q = AVObject.getQuery(AddRequest.class);\n\t\tq.whereEqualTo(AddRequest.FROM_USER, curUser);\n\t\tq.whereEqualTo(AddRequest.TO_USER, toUser);\n\t\tq.whereEqualTo(AddRequest.STATUS, AddRequest.STATUS_WAIT);\n\t\tint count = 0;\n\t\ttry {\n\t\t\tcount = q.count();\n\t\t} catch (AVException e) {\n\t\t\te.printStackTrace();\n\t\t\tif (e.getCode() == AVException.OBJECT_NOT_FOUND) {\n\t\t\t\tcount = 0;\n\t\t\t} else {\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t\tif (count > 0) {\n\t\t\tthrow new Exception(DemoApplication.context.getString(R.string.contact_alreadyCreateAddRequest));\n\t\t} else {\n\t\t\tAddRequest add = new AddRequest();\n\t\t\tadd.setFromUser(curUser);\n\t\t\tadd.setToUser(toUser);\n\t\t\tadd.setStatus(AddRequest.STATUS_WAIT);\n\t\t\tadd.save();\n\t\t}\n\t}\n\n\tpublic static void createAddRequestInBackground(Context ctx, final AVUser user) {\n\t\tnew MyAsyncTask(ctx) {\n\t\t\t@Override\n\t\t\tprotected void doInBack() throws Exception {\n\t\t\t\tAddRequestService.createAddRequest(user);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected void onSucceed() {\n\t\t\t\tUtils.toast(R.string.contact_sendRequestSucceed);\n\t\t\t}\n\t\t}.execute();\n\t}\n}", "public class PreferenceMap {\n\tpublic static final String ADD_REQUEST_N = \"addRequestN\";\n\tpublic static final String LATITUDE = \"latitude\";\n\tpublic static final String LONGITUDE = \"longitude\";\n\tpublic static final String ADDRESS = \"address\";\n\tpublic static final String NOTIFY_WHEN_NEWS = \"notifyWhenNews\";\n\n\tContext context;\n\tSharedPreferences pref;\n\tSharedPreferences.Editor editor;\n\t// int addRequestN;\n\t// String latitude;\n\t// String longitude;\n\tpublic static PreferenceMap currentUserPreferenceMap;\n\n\tpublic PreferenceMap(Context context, String prefName) {\n\t\tthis.context = context;\n\t\tpref = context.getSharedPreferences(prefName, Context.MODE_PRIVATE);\n\t\teditor = pref.edit();\n\t}\n\n\tpublic static PreferenceMap getCurUserPrefDao(Context context) {\n\t\tif (currentUserPreferenceMap == null) {\n\t\t\tcurrentUserPreferenceMap = new PreferenceMap(context, AVUser.getCurrentUser().getObjectId());\n\t\t}\n\t\treturn currentUserPreferenceMap;\n\t}\n\n\tpublic static PreferenceMap getMyPrefDao(Context context) {\n\t\tAVUser user = AVUser.getCurrentUser();\n\t\tif (user == null) {\n\t\t\tthrow new RuntimeException(\"user is null\");\n\t\t}\n\t\treturn new PreferenceMap(context, user.getObjectId());\n\t}\n\n\tpublic int getAddRequestN() {\n\t\treturn pref.getInt(ADD_REQUEST_N, 0);\n\t}\n\n\tpublic void setAddRequestN(int addRequestN) {\n\t\teditor.putInt(ADD_REQUEST_N, addRequestN).commit();\n\t}\n\n\tprivate String getLatitude() {\n\t\treturn pref.getString(LATITUDE, null);\n\t}\n\n\tprivate void setLatitude(String latitude) {\n\t\teditor.putString(LATITUDE, latitude).commit();\n\t}\n\n\tprivate String getLongitude() {\n\t\treturn pref.getString(LONGITUDE, null);\n\t}\n\n\tprivate void setLongitude(String longitude) {\n\t\teditor.putString(LONGITUDE, longitude).commit();\n\t}\n\n\tpublic String getAddress() {\n\t\treturn pref.getString(ADDRESS, null);\n\t}\n\n\tpublic void setAddress(String address) {\n\t\teditor.putString(ADDRESS, address).commit();\n\t}\n\n\tpublic AVGeoPoint getLocation() {\n\t\tString latitudeStr = getLatitude();\n\t\tString longitudeStr = getLongitude();\n\t\tif (latitudeStr == null || longitudeStr == null) {\n\t\t\treturn null;\n\t\t}\n\t\tdouble latitude = Double.parseDouble(latitudeStr);\n\t\tdouble longitude = Double.parseDouble(longitudeStr);\n\t\treturn new AVGeoPoint(latitude, longitude);\n\t}\n\n\tpublic void setLocation(AVGeoPoint location) {\n\t\tif (location == null) {\n\t\t\tthrow new NullPointerException(\"location is null\");\n\t\t}\n\t\tsetLatitude(location.getLatitude() + \"\");\n\t\tsetLongitude(location.getLongitude() + \"\");\n\t}\n}", "public abstract class MyAsyncTask extends AsyncTask<Void, Void, Void> {\n\tProgressDialog dialog;\n\tprotected Context context;\n\tboolean openDialog = true;\n\tException exception;\n\n\tprotected MyAsyncTask(Context context) {\n\t\tthis.context = context;\n\t}\n\n\tprotected MyAsyncTask(Context context, boolean openDialog) {\n\t\tthis.context = context;\n\t\tthis.openDialog = openDialog;\n\t}\n\n\tpublic MyAsyncTask setOpenDialog(boolean openDialog) {\n\t\tthis.openDialog = openDialog;\n\t\treturn this;\n\t}\n\n\tpublic ProgressDialog getDialog() {\n\t\treturn dialog;\n\t}\n\n\t@Override\n\tprotected void onPreExecute() {\n\t\tsuper.onPreExecute();\n\t\tif (openDialog) {\n\t\t\tdialog = Utils.showSpinnerDialog((Activity) context);\n\t\t}\n\t}\n\n\t@Override\n\tprotected Void doInBackground(Void... params) {\n\t\ttry {\n\t\t\tdoInBack();\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\texception = e;\n\t\t}\n\t\treturn null;\n\t}\n\n\t@Override\n\tprotected void onPostExecute(Void aVoid) {\n\t\tsuper.onPostExecute(aVoid);\n\t\tif (openDialog) {\n\t\t\tif (dialog.isShowing()) {\n\t\t\t\tdialog.dismiss();\n\t\t\t}\n\t\t}\n\t\tonPost(exception);\n\t}\n\n\n\n\tprotected void onPost(Exception e) {\n\t\tif (e != null) {\n\t\t\te.printStackTrace();\n\t\t\tUtils.toast(e.getMessage());\n\t\t\t//Utils.toast(ctx, R.string.pleaseCheckNetwork);\n\t\t} else {\n\t\t\tonSucceed();\n\t\t}\n\t}\n\n\tprotected abstract void doInBack() throws Exception;\n\tprotected abstract void onSucceed();\n}" ]
import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ListView; import com.avos.avoscloud.AVUser; import com.example.lovetalk.R; import com.example.lovetalk.adapter.NewFriendAdapter; import com.example.lovetalk.service.AddRequest; import com.example.lovetalk.service.AddRequestService; import com.example.lovetalk.service.PreferenceMap; import com.example.lovetalk.util.MyAsyncTask; import java.util.ArrayList; import java.util.List;
package com.example.lovetalk.activity; public class NewFriendActivity extends BaseActivity implements OnItemLongClickListener { ListView listview;
NewFriendAdapter adapter;
0
senseobservationsystems/sense-android-library
sense-android-library/src/nl/sense_os/service/deviceprox/BluetoothDeviceProximity.java
[ "public static class DataPoint implements BaseColumns {\n\n public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE\n + \"/vnd.sense_os.data_point\";\n public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE\n + \"/vnd.sense_os.data_point\";\n public static final String CONTENT_URI_PATH = \"/recent_values\";\n @Deprecated\n public static final String CONTENT_PERSISTED_URI_PATH = \"/persisted_values\";\n public static final String CONTENT_REMOTE_URI_PATH = \"/remote_values\";\n\n /**\n * The name of the sensor that generated the data point. <br>\n * <br>\n * TYPE: String\n */\n public static final String SENSOR_NAME = \"sensor_name\";\n /**\n * Description of the sensor that generated the data point. Can either be the hardware name,\n * or any other useful description. <br>\n * <br>\n * TYPE: String\n */\n public static final String SENSOR_DESCRIPTION = \"sensor_description\";\n /**\n * The data type of the data point. <br>\n * <br>\n * TYPE: String\n * \n * @see SenseDataTypes\n */\n public static final String DATA_TYPE = \"data_type\";\n /**\n * The human readable display name of the sensor that generated the data point. <br>\n * <br>\n * TYPE: String\n * \n * @see SenseDataTypes\n */\n public static final String DISPLAY_NAME = \"display_name\";\n /**\n * Time stamp for the data point, in milliseconds. <br>\n * <br>\n * TYPE: long\n */\n public static final String TIMESTAMP = \"timestamp\";\n /**\n * Data point value. <br>\n * <br>\n * TYPE: String\n */\n public static final String VALUE = \"value\";\n /**\n * Transmit state of the data point, signalling whether the point has been sent to\n * CommonSense already.<br>\n * <br>\n * TYPE: integer status code: 0 (not sent), or 1 (sent)\n */\n public static final String TRANSMIT_STATE = \"transmit_state\";\n /**\n * Device UUID of the sensor. Use this for sensors that are originated from\n * \"external sensors\", or leave <code>null</code> to use the phone as default device.<br>\n * <br>\n * TYPE: String\n */\n public static final String DEVICE_UUID = \"device_uuid\";\n\n private DataPoint() {\n // class should not be instantiated\n }\n}", "public static class SensorNames {\n\n /**\n * Fall detector sensor. Can be a real fall or a regular free fall for demo's. Part of the\n * Motion sensors.\n */\n public static final String FALL_DETECTOR = \"fall_detector\";\n\n /** Noise level sensor. Part of the Ambience sensors. */\n public static final String NOISE = \"noise_sensor\";\n\n /** Noise level sensor (Burst-mode). Part of the Ambience sensors. */\n public static final String NOISE_BURST = \"noise_sensor (burst-mode)\";\n\n /** Audio spectrum sensor. Part of the Ambience sensors. */\n public static final String AUDIO_SPECTRUM = \"audio_spectrum\";\n\n /** Microphone output. Part of the Ambience sensors (real-time mode only). */\n public static final String MIC = \"microphone\";\n\n /** Light sensor. Part of the Ambience sensors. */\n public static final String LIGHT = \"light\";\n\n /** Camera Light sensor. Part of the Ambience sensors. */\n public static final String CAMERA_LIGHT = \"camera_light\";\n\n /** Bluetooth discovery sensor. Part of the Neighboring Devices sensors. */\n public static final String BLUETOOTH_DISCOVERY = \"bluetooth_discovery\";\n\n /** Wi-Fi scan sensor. Part of the Neighboring Devices sensors. */\n public static final String WIFI_SCAN = \"wifi scan\";\n\n /** NFC sensor. Part of the Neighboring Devices sensors. */\n public static final String NFC_SCAN = \"nfc_scan\";\n\n /** Acceleration sensor. Part of the Motion sensors, also used in Zephyr BioHarness */\n public static final String ACCELEROMETER = \"accelerometer\";\n\n /** Motion sensor. The basis for the other Motion sensors. */\n public static final String MOTION = \"motion\";\n\n /** Linear acceleration sensor name. Part of the Motion sensors. */\n public static final String LIN_ACCELERATION = \"linear acceleration\";\n\n /** Gyroscope sensor name. Part of the Motion sensors. */\n public static final String GYRO = \"gyroscope\";\n\n /** Magnetic field sensor name. Part of the Ambience sensors. */\n public static final String MAGNETIC_FIELD = \"magnetic field\";\n\n /** Orientation sensor name. Part of the Motion sensors. */\n public static final String ORIENT = \"orientation\";\n\n /** Epi-mode accelerometer sensor. Special part of the Motion sensors. */\n public static final String ACCELEROMETER_EPI = \"accelerometer (epi-mode)\";\n\n /** Burst-mode accelerometer sensor. Special part of the Motion sensors. */\n public static final String ACCELEROMETER_BURST = \"accelerometer (burst-mode)\";\n\n /** Burst-mode gyroscope sensor. Special part of the Motion sensors. */\n public static final String GYRO_BURST = \"gyroscope (burst-mode)\";\n\n /** Burst-mode linear acceleration sensor. Special part of the Motion sensors. */\n public static final String LINEAR_BURST = \"linear acceleration (burst-mode)\";\n\n /** Motion energy sensor name. Special part of the Motion sensors. */\n public static final String MOTION_ENERGY = \"motion energy\";\n\n /*** battery sensor for Zephyr BioHarness external sensor */\n public static final String BATTERY_LEVEL = \"battery level\";\n\n /** heart rate sensor for Zephyr BioHarness and HxM external sensors */\n public static final String HEART_RATE = \"heart rate\";\n\n /** respiration rate sensor for Zephyr BioHarness external sensor */\n public static final String RESPIRATION = \"respiration rate\";\n\n /** temperature sensor for Zephyr BioHarness external sensor */\n public static final String TEMPERATURE = \"temperature\";\n\n /** worn status for Zephyr BioHarness external sensor */\n public static final String WORN_STATUS = \"worn status\";\n\n /** blood pressure sensor */\n public static final String BLOOD_PRESSURE = \"blood_pressure\";\n\n /** reaction time sensor */\n public static final String REACTION_TIME = \"reaction_time\";\n\n /** speed sensor for Zephyr HxM external sensor */\n public static final String SPEED = \"speed\";\n\n /** distance sensor for Zephyr HxM external sensor */\n public static final String DISTANCE = \"distance\";\n\n /** battery sensor for Zephyr HxM external sensor */\n public static final String BATTERY_CHARGE = \"battery charge\";\n\n /** strides sensor (stappenteller) for Zephyr HxM external sensor */\n public static final String STRIDES = \"strides\";\n\n /** Location sensor. */\n public static final String LOCATION = \"position\";\n\n /** TimeZone sensor. */\n public static final String TIME_ZONE = \"time_zone\";\n\n /** Battery sensor. Part of the Phone State sensors. */\n public static final String BATTERY_SENSOR = \"battery sensor\";\n \n /** App info sensor. Part of the Phone State sensors. */\n public static final String APP_INFO_SENSOR = \"app_info\";\n\n /** Screen activity sensor. Part of the Phone State sensors. */\n public static final String SCREEN_ACTIVITY = \"screen activity\";\n\n /** Pressure sensor. Part of the Phone State sensors. */\n public static final String PRESSURE = \"pressure\";\n\n /** Proximity sensor. Part of the Phone State sensors. */\n public static final String PROXIMITY = \"proximity\";\n\n /** Call state sensor. Part of the Phone State sensors. */\n public static final String CALL_STATE = \"call state\";\n\n /** Data connection state sensor. Part of the Phone State sensors. */\n public static final String DATA_CONN = \"data connection\";\n\n /** IP address sensor. Part of the Phone State sensors. */\n public static final String IP_ADDRESS = \"ip address\";\n\n /** Mobile service state sensor. Part of the Phone State sensors. */\n public static final String SERVICE_STATE = \"service state\";\n\n /** Mobile signal strength sensor. Part of the Phone State sensors. */\n public static final String SIGNAL_STRENGTH = \"signal strength\";\n\n /** Unread messages sensor. Part of the Phone State sensors. */\n public static final String UNREAD_MSG = \"unread msg\";\n\n /** Data connection type sensor. Part of the Phone State sensors. */\n public static final String CONN_TYPE = \"connection type\";\n\n /** Monitor status since DTCs cleared. Part of the OBD-II sensors. */\n public static final String MONITOR_STATUS = \"monitor status\";\n\n /** Fuel system status. Part of the OBD-II sensors. */\n public static final String FUEL_SYSTEM_STATUS = \"fuel system status\";\n\n /** Calculated engine load. Part of the OBD-II sensors. */\n public static final String ENGINE_LOAD = \"calculated engine load value\";\n\n /** Engine coolant. Part of the OBD-II sensors. */\n public static final String ENGINE_COOLANT = \"engine coolant\";\n\n /** Short/Long term fuel trim bank 1 & 2. Part of the OBD-II sensors. */\n public static final String FUEL_TRIM = \"fuel trim\";\n\n /** Fuel Pressure. Part of the OBD-II sensors. */\n public static final String FUEL_PRESSURE = \"fuel pressure\";\n\n /** Intake manifold absolute pressure. Part of the OBD-II sensors. */\n public static final String INTAKE_PRESSURE = \"intake manifold absolute pressure\";\n\n /** Engine RPM. Part of the OBD-II sensors. */\n public static final String ENGINE_RPM = \"engine RPM\";\n\n /** Vehicle speed. Part of the OBD-II sensors. */\n public static final String VEHICLE_SPEED = \"vehicle speed\";\n\n /** Timing advance. Part of the OBD-II sensors. */\n public static final String TIMING_ADVANCE = \"timing advance\";\n\n /** Intake air temperature. Part of the OBD-II sensors. */\n public static final String INTAKE_TEMPERATURE = \"intake air temperature\";\n\n /** MAF air flow rate. Part of the OBD-II sensors. */\n public static final String MAF_AIRFLOW = \"MAF air flow rate\";\n\n /** Throttle position. Part of the OBD-II sensors. */\n public static final String THROTTLE_POSITION = \"throttle position\";\n\n /** Commanded secondary air status. Part of the OBD-II sensors. */\n public static final String AIR_STATUS = \"commanded secondary air status\";\n\n /** Oxygen sensors. Part of the OBD-II sensors. */\n public static final String OXYGEN_SENSORS = \"oxygen sensors\";\n\n /** OBD standards. Part of the OBD-II sensors. */\n public static final String OBD_STANDARDS = \"OBD standards\";\n\n /** Auxiliary input status. Part of the OBD-II sensors. */\n public static final String AUXILIARY_INPUT = \"auxiliary input status\";\n\n /** Run time since engine start. Part of the OBD-II sensors. */\n public static final String RUN_TIME = \"run time\";\n\n /** Ambient temperature sensor. Part of the ambience sensors. From API >= 14 only */\n public static final String AMBIENT_TEMPERATURE = \"ambient_temperature\";\n\n /** Relative humidity sensor. Part of the ambience sensors. From API >= 14 only */\n public static final String RELATIVE_HUMIDITY = \"relative_humidity\";\n\n /** Bluetooth number of neighbours, count sensor */\n public static final String BLUETOOTH_NEIGHBOURS_COUNT = \"bluetooth neighbours count\";\n\n /** Traveled distance for each day */\n public static final String TRAVELED_DISTANCE_24H = \"traveled distance 24h\";\n\n /** Traveled distance for each hour */\n public static final String TRAVELED_DISTANCE_1H = \"traveled distance 1h\";\n\n public static final String LOUDNESS = \"loudness\";\n\n public static final String ATTACHED_TO_MYRIANODE = \"attachedToMyriaNode\";\n\n public static final String APP_INSTALLED = \"installed_apps\";\n\n public static final String APP_FOREGROUND = \"foreground_app\";\n\n private SensorNames() {\n // class should not be instantiated\n }\n}", "public class SNTP {\n private static final String TAG = \"SNTP\";\n\n private static final int ORIGINATE_TIME_OFFSET = 24;\n private static final int RECEIVE_TIME_OFFSET = 32;\n private static final int TRANSMIT_TIME_OFFSET = 40;\n private static final int NTP_PACKET_SIZE = 48;\n\n private static final int NTP_PORT = 123;\n private static final int NTP_MODE_CLIENT = 3;\n private static final int NTP_VERSION = 3;\n public static final String HOST_WORLDWIDE = \"pool.ntp.org\";\n public static final String HOST_ASIA = \"asia.pool.ntp.org\";\n public static final String HOST_EUROPE = \"europe.pool.ntp.org\";\n public static final String HOST_NORTH_AMERICA = \"north-america.pool.ntp.org\";\n public static final String HOST_SOUTH_AMERICA = \"south-america.pool.ntp.org\";\n public static final String HOST_OCEANIA = \"oceania.pool.ntp.org\";\n private boolean useSimulateTime = false;\n\n // Number of seconds between Jan 1, 1900 and Jan 1, 1970\n // 70 years plus 17 leap days\n private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;\n\n // system time computed from NTP server response\n private long mNtpTime;\n\n // value of SystemClock.elapsedRealtime() corresponding to mNtpTime\n private long mNtpTimeReference;\n\n // round trip time in milliseconds\n private long mRoundTripTime;\n\n private long clockOffset = -1;\n\n private static SNTP sntp = null;\n\n /**\n * Returns whether time simulation is used\n * @return True is simulate time is being used\n */\n public boolean isSimulatingTime()\n {\n return useSimulateTime;\n }\n\n /**\n * Sets the current simulation time\n *\n * Will set the clock to the provided simulation time.<br>\n * #getTime will give the updated time based on this simulation time<br>\n * @param time The epoch time in ms to use as current time\n */\n public void setCurrentSimulationTime(long time)\n {\n clockOffset = time - System.currentTimeMillis();\n useSimulateTime = true;\n }\n\n /**\n * Disables the time simulation\n */\n public void disableTimeSimulation()\n {\n if(!useSimulateTime)\n return;\n clockOffset = -1;\n useSimulateTime = false;\n }\n /*\n * Nice singleton :)\n */\n public synchronized static SNTP getInstance() {\n if (sntp == null)\n sntp = new SNTP();\n return sntp;\n }\n\n /**\n * Sends an SNTP request to the given host and processes the response.\n * \n * @param host\n * host name of the server.\n * @param timeout\n * network timeout in milliseconds.\n * @return true if the transaction was successful.\n */\n public boolean requestTime(String host, int timeout) {\n\ttry {\n\t DatagramSocket socket = new DatagramSocket();\n\t socket.setSoTimeout(timeout);\n\t InetAddress address = InetAddress.getByName(host);\n\t byte[] buffer = new byte[NTP_PACKET_SIZE];\n\t DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);\n\n\t // set mode = 3 (client) and version = 3\n\t // mode is in low 3 bits of first byte\n\t // version is in bits 3-5 of first byte\n\t buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);\n\n\t // get current time and write it to the request packet\n\t long requestTime = System.currentTimeMillis();\n\t long requestTicks = SystemClock.elapsedRealtime();\n\t writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime);\n\n\t socket.send(request);\n\n\t // read the response\n\t DatagramPacket response = new DatagramPacket(buffer, buffer.length);\n\t socket.receive(response);\n\t long responseTicks = SystemClock.elapsedRealtime();\n\t long responseTime = requestTime + (responseTicks - requestTicks);\n\t socket.close();\n\n\t // extract the results\n\t long originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET);\n\t long receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);\n\t long transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET);\n\t long roundTripTime = responseTicks - requestTicks - (transmitTime - receiveTime);\n\t // receiveTime = originateTime + transit + skew\n\t // responseTime = transmitTime + transit - skew\n\t // clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2\n\t // = ((originateTime + transit + skew - originateTime) +\n\t // (transmitTime - (transmitTime + transit - skew)))/2\n\t // = ((transit + skew) + (transmitTime - transmitTime - transit + skew))/2\n\t // = (transit + skew - transit + skew)/2\n\t // = (2 * skew)/2 = skew\n\t clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime)) / 2;\n\t // if (Config.LOGD) Log.d(TAG, \"round trip: \" + roundTripTime + \" ms\");\n\t // if (Config.LOGD) Log.d(TAG, \"clock offset: \" + clockOffset + \" ms\");\n\n\t // save our results - use the times on this side of the network latency\n\t // (response rather than request time)\n\t mNtpTime = responseTime + clockOffset;\n\t mNtpTimeReference = responseTicks;\n\t mRoundTripTime = roundTripTime;\n\t} catch (Exception e) {\n\t Log.w(TAG, \"Request time failed: \" + e);\n\t return false;\n\t}\n\n\treturn true;\n }\n\n /**\n * Get the current time, based on NTP clockOffset if or System time\n * \n * @return the ntp time from the worldwide pool if available else the system time\n */\n public long getTime() {\n\t// get the clock offset\n\tif (clockOffset == -1) {\n\t if (requestTime(HOST_WORLDWIDE, 1000)) {\n\t\treturn getNtpTime();\n\t } else {\n\t\tclockOffset = 0;\n\t }\n\t}\n\n\treturn System.currentTimeMillis() + clockOffset;\n }\n\n /**\n * Returns the time computed from the NTP transaction.\n * \n * @return time value computed from NTP server response.\n */\n public long getNtpTime() {\n \t//Log.d(TAG,\"SNTP time requested\");\n \t//return 1412175540000l;\n \treturn mNtpTime;\n }\n\n /**\n * Returns the reference clock value (value of SystemClock.elapsedRealtime()) corresponding to\n * the NTP time.\n * \n * @return reference clock corresponding to the NTP time.\n */\n public long getNtpTimeReference() {\n\treturn mNtpTimeReference;\n }\n\n /**\n * Returns the round trip time of the NTP transaction\n * \n * @return round trip time in milliseconds.\n */\n public long getRoundTripTime() {\n\treturn mRoundTripTime;\n }\n\n /**\n * Reads an unsigned 32 bit big endian number from the given offset in the buffer.\n */\n private long read32(byte[] buffer, int offset) {\n\tbyte b0 = buffer[offset];\n\tbyte b1 = buffer[offset + 1];\n\tbyte b2 = buffer[offset + 2];\n\tbyte b3 = buffer[offset + 3];\n\n\t// convert signed bytes to unsigned values\n\tint i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);\n\tint i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);\n\tint i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);\n\tint i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);\n\n\treturn ((long) i0 << 24) + ((long) i1 << 16) + ((long) i2 << 8) + (long) i3;\n }\n\n /**\n * Reads the NTP time stamp at the given offset in the buffer and returns it as a system time\n * (milliseconds since January 1, 1970).\n */\n private long readTimeStamp(byte[] buffer, int offset) {\n\tlong seconds = read32(buffer, offset);\n\tlong fraction = read32(buffer, offset + 4);\n\treturn ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);\n }\n\n /**\n * Writes system time (milliseconds since January 1, 1970) as an NTP time stamp at the given\n * offset in the buffer.\n */\n private void writeTimeStamp(byte[] buffer, int offset, long time) {\n\tlong seconds = time / 1000L;\n\tlong milliseconds = time - seconds * 1000L;\n\tseconds += OFFSET_1900_TO_1970;\n\n\t// write seconds in big endian format\n\tbuffer[offset++] = (byte) (seconds >> 24);\n\tbuffer[offset++] = (byte) (seconds >> 16);\n\tbuffer[offset++] = (byte) (seconds >> 8);\n\tbuffer[offset++] = (byte) (seconds >> 0);\n\n\tlong fraction = milliseconds * 0x100000000L / 1000L;\n\t// write fraction in big endian format\n\tbuffer[offset++] = (byte) (fraction >> 24);\n\tbuffer[offset++] = (byte) (fraction >> 16);\n\tbuffer[offset++] = (byte) (fraction >> 8);\n\t// low order bits should be random data\n\tbuffer[offset++] = (byte) (Math.random() * 255.0);\n }\n}", "public class SensorDataPoint {\n\n public enum DataType {\n INT, FLOAT, BOOL, DOUBLE, STRING, ARRAYLIST, JSON, JSONSTRING, FILE, SENSOREVENT\n };\n\n /**\n * Name of the sensor that produced the data point.\n */\n public String sensorName;\n /**\n * Description of the sensor that produces the data point. Corresponds to the \"sensor_type\"\n * field in the CommonSense API.\n */\n public String sensorDescription;\n /**\n * Time stamp of the data point.\n */\n public long timeStamp;\n private DataType dataType;\n private Object value;\n\n /**\n * @see #SensorDataPoint(int)\n */\n public SensorDataPoint(Object value) { \n this.value = value;\n }\n \n /**\n * @see #SensorDataPoint(int)\n */\n public SensorDataPoint(ArrayList<SensorDataPoint> value) {\n dataType = DataType.ARRAYLIST;\n this.value = value;\n }\n\n /**\n * @see #SensorDataPoint(int)\n */\n public SensorDataPoint(Boolean value) {\n dataType = DataType.BOOL;\n this.value = value;\n }\n\n /**\n * @see #SensorDataPoint(int)\n */\n public SensorDataPoint(double value) {\n dataType = DataType.DOUBLE;\n this.value = value;\n }\n\n /**\n * @see #SensorDataPoint(int)\n */\n public SensorDataPoint(float value) {\n dataType = DataType.FLOAT;\n this.value = value;\n }\n\n /**\n * Sets the value of the SensorDataPoint based on the input value the dataType. The dataType can\n * be changed by {@link #setDataType(DataType)}.\n * \n * @param value\n * The input value which is stored in the SensorDataPoint\n */\n public SensorDataPoint(int value) {\n dataType = DataType.INT;\n this.value = value;\n }\n\n /**\n * @see #setValue(int)\n */\n public SensorDataPoint(JSONObject value) {\n dataType = DataType.JSON;\n this.value = value;\n }\n\n /**\n * @see #setValue(int)\n */\n public SensorDataPoint(SensorEvent value) {\n dataType = DataType.SENSOREVENT;\n this.value = value;\n }\n\n /**\n * @see #setValue(int)\n */\n public SensorDataPoint(String value) {\n dataType = DataType.STRING;\n this.value = value;\n }\n\n /**\n * @see #getIntValue()\n */\n @SuppressWarnings(\"unchecked\")\n public ArrayList<SensorDataPoint> getArrayValue() {\n return (ArrayList<SensorDataPoint>) value;\n }\n\n /**\n * @see #getIntValue()\n */\n public Boolean getBoolValue() {\n return (Boolean) value;\n }\n\n /**\n * Returns the dataType of the SensorDataPoint\n * \n * @return DataTypes\n */\n public DataType getDataType() {\n return dataType;\n }\n\n /**\n * @see #getIntValue()\n */\n public double getDoubleValue() {\n return (Double) value;\n }\n\n /**\n * @see #getIntValue()\n */\n public float getFloatValue() {\n return (Float) value;\n }\n\n /**\n * Return the value of the SensorDataPoint\n * \n * @return value\n */\n public int getIntValue() {\n return (Integer) value;\n }\n\n /**\n * @see #getIntValue()\n */\n public JSONObject getJSONValue() {\n return (JSONObject) value;\n }\n\n /**\n * @see #getIntValue()\n */\n public SensorEvent getSensorEventValue() {\n return (SensorEvent) value;\n }\n\n /**\n * @see #getIntValue()\n */\n public String getStringValue() {\n return (String) value;\n }\n\n /**\n * Sets the data type.\n * \n * This method overrides the dataType which has been set automatically. This method can be used\n * when a more precise dataType like FILE is needed.\n * \n * @param dataType\n * The dataType of the SensorDataPoint\n */\n public void setDataType(DataType dataType) {\n this.dataType = dataType;\n }\n}", "public abstract class BaseDataProducer implements DataProducer {\n\n\tprotected final String TAG = \"BaseDataProducer\";\n\t\n /** The DataProcessors which are subscribed to this sensor for sensor data */\n protected List<DataConsumer> mSubscribers = new ArrayList<DataConsumer>();\n\n /**\n * Adds a data consumer as subscriber to this data producer. This method is synchronized to\n * prevent concurrent modifications to the list of subscribers.\n * \n * @param consumer\n * The DataProcessor that wants the sensor data as input\n * @return <code>true</code> if the DataConsumer was successfully subscribed\n */\n @Override\n public synchronized boolean addSubscriber(DataConsumer consumer) {\n if (!hasSubscriber(consumer)) {\n return mSubscribers.add(consumer);\n } else {\n return false;\n }\n }\n\n /**\n * Checks subscribers if the sample is complete. This method uses\n * {@link DataConsumer#isSampleComplete()} to see if the sample is completed, or if the data\n * processors need more data.\n * \n * @return true when all the subscribers have complete samples\n */\n protected synchronized boolean checkSubscribers() {\n boolean complete = true;\n for (DataConsumer subscriber : mSubscribers) {\n if (subscriber != null) {\n complete &= subscriber.isSampleComplete();\n }\n }\n return complete;\n }\n\n @Override\n public synchronized boolean hasSubscriber(DataConsumer consumer) {\n for (DataConsumer subscriber : mSubscribers) {\n if (subscriber != null && subscriber.equals(consumer)) {\n return true;\n }\n }\n return false;\n }\n\n @Override\n public boolean hasSubscribers() {\n return !mSubscribers.isEmpty();\n }\n\n /**\n * Notifies subscribers that a new sample is starting. This method calls\n * {@link DataConsumer#startNewSample()} on each subscriber.\n */\n protected synchronized void notifySubscribers() {\n for (DataConsumer subscriber : mSubscribers) {\n if (subscriber != null) {\n subscriber.startNewSample();\n }\n }\n }\n\n /**\n * Removes a data subscriber if present. This method is synchronized to prevent concurrent\n * modifications.\n * \n * @param subscriber\n * The DataConsumer that should be unsubscribed\n */\n @Override\n public synchronized boolean removeSubscriber(DataConsumer consumer) {\n if (mSubscribers.contains(consumer)) {\n return mSubscribers.remove(consumer);\n }\n return true;\n }\n\n /**\n * Sends data to all subscribed data consumers.\n * \n * @param dataPoint\n * The SensorDataPoint to send\n */\n // TODO: do a-sync\n protected synchronized void sendToSubscribers(SensorDataPoint dataPoint) {\n for (DataConsumer subscriber : mSubscribers) {\n if (subscriber != null && !subscriber.isSampleComplete()) {\n \ttry\n \t{\n \t\tsubscriber.onNewData(dataPoint);\n \t}\n \tcatch(Exception e)\n \t{\n \t\tLog.e(TAG, \"Error sending data to subscriber.\", e);\n \t}\n }\n }\n }\n}" ]
import java.util.HashMap; import java.util.Map; import java.util.Vector; import nl.sense_os.service.R; import nl.sense_os.service.constants.SenseDataTypes; import nl.sense_os.service.constants.SensorData.DataPoint; import nl.sense_os.service.constants.SensorData.SensorNames; import nl.sense_os.service.provider.SNTP; import nl.sense_os.service.shared.SensorDataPoint; import nl.sense_os.service.subscription.BaseDataProducer; import org.json.JSONException; import org.json.JSONObject; import android.app.AlarmManager; import android.app.PendingIntent; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Handler; import android.os.Looper; import android.util.Log;
/************************************************************************************************** * Copyright (C) 2010 Sense Observation Systems, Rotterdam, the Netherlands. All rights reserved. * *************************************************************************************************/ package nl.sense_os.service.deviceprox; /** * Represents the Bluetooth scan sensor. Sets up periodic scans of the network on a separate thread. * * @author Ted Schmidt <[email protected]> */ public class BluetoothDeviceProximity extends BaseDataProducer{ /** * Receiver for Bluetooth state broadcasts */ private class BluetoothReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (!scanEnabled || null == scanThread) { Log.w(TAG, "Bluetooth broadcast received while sensor is disabled"); return; } String action = intent.getAction(); if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) { onBluetoothStateChanged(intent); } else if (BluetoothDevice.ACTION_FOUND.equals(action)) { onDeviceFound(intent); } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { onScanFinished(); } } } /** * Receiver for alarms to start scan */ private class ScanAlarmReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (!scanEnabled) { Log.w(TAG, "Bluetooth scan alarm received while sensor is disabled"); return; } else { // stop any old threads try { if (null != scanThread) { scanThread.stop(); scanHandler.removeCallbacks(scanThread); } } catch (Exception e) { Log.e(TAG, "Exception clearing old bluetooth scan threads. " + e); } // start new scan scanHandler.post(scanThread = new ScanThread()); } } } /** * Bluetooth discovery thread */ private class ScanThread implements Runnable { // private boolean btActiveFromTheStart = false; // removed private Vector<Map<BluetoothDevice, Short>> deviceArray; public ScanThread() { // send address try { btAdapter = BluetoothAdapter.getDefaultAdapter(); // btActiveFromTheStart = btAdapter.isEnabled(); } catch (Exception e) { Log.e(TAG, "Exception preparing Bluetooth scan thread:", e); } } @Override public void run() { Log.v(TAG, "Run Bluetooth discovery thread"); if (scanEnabled) { if (btAdapter.isEnabled()) { // start discovery deviceArray = new Vector<Map<BluetoothDevice, Short>>(); context.registerReceiver(btReceiver, new IntentFilter( BluetoothDevice.ACTION_FOUND)); context.registerReceiver(btReceiver, new IntentFilter( BluetoothAdapter.ACTION_DISCOVERY_FINISHED)); Log.i(TAG, "Starting Bluetooth discovery"); btAdapter.startDiscovery(); } else if (btAdapter.getState() == BluetoothAdapter.STATE_TURNING_ON) { // listen for the adapter state to change to STATE_ON context.registerReceiver(btReceiver, new IntentFilter( BluetoothAdapter.ACTION_STATE_CHANGED)); } else { // ask user for permission to start bluetooth // Log.v(TAG, "Asking user to start bluetooth"); Intent startBt = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startBt.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(startBt); // listen for the adapter state to change to STATE_ON context.registerReceiver(btReceiver, new IntentFilter( BluetoothAdapter.ACTION_STATE_CHANGED)); } } else { stop(); } } public void stop() { try { Log.i(TAG, "Stopping Bluetooth discovery thread"); context.unregisterReceiver(btReceiver); btAdapter.cancelDiscovery(); /* * do not have to switch off the bluetooth anymore because we ask the user * explicitly */ // if (!btActiveFromTheStart) { btAdapter.disable(); } } catch (Exception e) { Log.e(TAG, "Error in stopping BT discovery:" + e.getMessage()); } } } private static final String TAG = "Bluetooth DeviceProximity"; private static final int REQ_CODE = 333; private final BluetoothReceiver btReceiver = new BluetoothReceiver(); private final ScanAlarmReceiver alarmReceiver = new ScanAlarmReceiver(); private BluetoothAdapter btAdapter; private final Context context; private boolean scanEnabled = false; private final Handler scanHandler = new Handler(Looper.getMainLooper()); private int scanInterval = 0; private ScanThread scanThread = null; public BluetoothDeviceProximity(Context context) { this.context = context; } public int getScanInterval() { return scanInterval; } private void onDeviceFound(Intent intent) { BluetoothDevice remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); Short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, (short) 0); HashMap<BluetoothDevice, Short> mapValue = new HashMap<BluetoothDevice, Short>(); mapValue.put(remoteDevice, rssi); scanThread.deviceArray.add(mapValue); } private void onScanFinished() { try { for (Map<BluetoothDevice, Short> value : scanThread.deviceArray) { BluetoothDevice btd = value.entrySet().iterator().next().getKey(); JSONObject deviceJson = new JSONObject(); deviceJson.put("address", btd.getAddress()); deviceJson.put("name", btd.getName()); deviceJson.put("rssi", value.entrySet().iterator().next().getValue()); this.notifySubscribers(); SensorDataPoint dataPoint = new SensorDataPoint(deviceJson);
dataPoint.sensorName = SensorNames.BLUETOOTH_DISCOVERY;
1
utds3lab/SMVHunter
dynamic/src/com/android/hierarchyviewerlib/ui/TreeView.java
[ "public abstract class HierarchyViewerDirector implements IDeviceChangeListener,\n IWindowChangeListener {\n\t\n\tstatic Logger logger = Logger.getLogger(HierarchyViewerDirector.class);\n\tstatic boolean logDebug = logger.isDebugEnabled();\n\t\n protected static HierarchyViewerDirector sDirector;\n\n public static final String TAG = \"hierarchyviewer\";\n\n private int mPixelPerfectRefreshesInProgress = 0;\n\n private Timer mPixelPerfectRefreshTimer = new Timer();\n\n private boolean mAutoRefresh = false;\n\n public static final int DEFAULT_PIXEL_PERFECT_AUTOREFRESH_INTERVAL = 5;\n\n private int mPixelPerfectAutoRefreshInterval = DEFAULT_PIXEL_PERFECT_AUTOREFRESH_INTERVAL;\n\n private PixelPerfectAutoRefreshTask mCurrentAutoRefreshTask;\n\n private String mFilterText = \"\"; //$NON-NLS-1$\n\n public void terminate() {\n WindowUpdater.terminate();\n mPixelPerfectRefreshTimer.cancel();\n }\n\n public abstract String getAdbLocation();\n\n public static HierarchyViewerDirector getDirector() {\n return sDirector;\n }\n\n /**\n * Init the DeviceBridge with an existing {@link AndroidDebugBridge}.\n * @param bridge the bridge object to use\n */\n public void acquireBridge(AndroidDebugBridge bridge) {\n DeviceBridge.acquireBridge(bridge);\n }\n\n /**\n * Creates an {@link AndroidDebugBridge} connected to adb at the given location.\n *\n * If a bridge is already running, this disconnects it and creates a new one.\n *\n * @param adbLocation the location to adb.\n */\n public void initDebugBridge() {\n DeviceBridge.initDebugBridge(getAdbLocation());\n }\n\n public void stopDebugBridge() {\n DeviceBridge.terminate();\n }\n\n public void populateDeviceSelectionModel() {\n IDevice[] devices = DeviceBridge.getDevices();\n for (IDevice device : devices) {\n deviceConnected(device);\n }\n }\n\n public void startListenForDevices() {\n DeviceBridge.startListenForDevices(this);\n }\n\n public void stopListenForDevices() {\n DeviceBridge.stopListenForDevices(this);\n }\n\n public abstract void executeInBackground(String taskName, Runnable task);\n\n @Override\n public void deviceConnected(final IDevice device) {\n executeInBackground(\"Connecting device\", new Runnable() {\n @Override\n public void run() {\n if (DeviceSelectionModel.getModel().containsDevice(device)) {\n windowsChanged(device);\n } else if (device.isOnline()) {\n DeviceBridge.setupDeviceForward(device);\n if (!DeviceBridge.isViewServerRunning(device)) {\n if (!DeviceBridge.startViewServer(device)) {\n // Let's do something interesting here... Try again\n // in 2 seconds.\n try {\n Thread.sleep(2000);\n } catch (InterruptedException e) {\n }\n if (!DeviceBridge.startViewServer(device)) {\n Log.e(TAG, \"Unable to debug device \" + device);\n DeviceBridge.removeDeviceForward(device);\n } else {\n loadViewServerInfoAndWindows(device);\n }\n return;\n }\n }\n loadViewServerInfoAndWindows(device);\n }\n }\n });\n }\n\n private void loadViewServerInfoAndWindows(final IDevice device) {\n\n ViewServerInfo viewServerInfo = DeviceBridge.loadViewServerInfo(device);\n if (viewServerInfo == null) {\n return;\n }\n Window[] windows = DeviceBridge.loadWindows(device);\n DeviceSelectionModel.getModel().addDevice(device, windows, viewServerInfo);\n if (viewServerInfo.protocolVersion >= 3) {\n WindowUpdater.startListenForWindowChanges(HierarchyViewerDirector.this, device);\n focusChanged(device);\n }\n\n }\n\n @Override\n public void deviceDisconnected(final IDevice device) {\n executeInBackground(\"Disconnecting device\", new Runnable() {\n @Override\n public void run() {\n ViewServerInfo viewServerInfo = DeviceBridge.getViewServerInfo(device);\n if (viewServerInfo != null && viewServerInfo.protocolVersion >= 3) {\n WindowUpdater.stopListenForWindowChanges(HierarchyViewerDirector.this, device);\n }\n DeviceBridge.removeDeviceForward(device);\n DeviceBridge.removeViewServerInfo(device);\n DeviceSelectionModel.getModel().removeDevice(device);\n if (PixelPerfectModel.getModel().getDevice() == device) {\n PixelPerfectModel.getModel().setData(null, null, null);\n }\n Window treeViewWindow = TreeViewModel.getModel().getWindow();\n if (treeViewWindow != null && treeViewWindow.getDevice() == device) {\n TreeViewModel.getModel().setData(null, null);\n mFilterText = \"\"; //$NON-NLS-1$\n }\n }\n });\n }\n\n @Override\n public void deviceChanged(IDevice device, int changeMask) {\n if ((changeMask & IDevice.CHANGE_STATE) != 0 && device.isOnline()) {\n deviceConnected(device);\n }\n }\n\n @Override\n public void windowsChanged(final IDevice device) {\n executeInBackground(\"Refreshing windows\", new Runnable() {\n @Override\n public void run() {\n if (!DeviceBridge.isViewServerRunning(device)) {\n if (!DeviceBridge.startViewServer(device)) {\n Log.e(TAG, \"Unable to debug device \" + device);\n return;\n }\n }\n Window[] windows = DeviceBridge.loadWindows(device);\n DeviceSelectionModel.getModel().updateDevice(device, windows);\n }\n });\n }\n\n @Override\n public void focusChanged(final IDevice device) {\n executeInBackground(\"Updating focus\", new Runnable() {\n @Override\n public void run() {\n int focusedWindow = DeviceBridge.getFocusedWindow(device);\n DeviceSelectionModel.getModel().updateFocusedWindow(device, focusedWindow);\n }\n });\n }\n\n public void refreshPixelPerfect() {\n final IDevice device = PixelPerfectModel.getModel().getDevice();\n if (device != null) {\n // Some interesting logic here. We don't want to refresh the pixel\n // perfect view 1000 times in a row if the focus keeps changing. We\n // just\n // want it to refresh following the last focus change.\n boolean proceed = false;\n synchronized (this) {\n if (mPixelPerfectRefreshesInProgress <= 1) {\n proceed = true;\n mPixelPerfectRefreshesInProgress++;\n }\n }\n if (proceed) {\n executeInBackground(\"Refreshing pixel perfect screenshot\", new Runnable() {\n @Override\n public void run() {\n Image screenshotImage = getScreenshotImage(device);\n if (screenshotImage != null) {\n PixelPerfectModel.getModel().setImage(screenshotImage);\n }\n synchronized (HierarchyViewerDirector.this) {\n mPixelPerfectRefreshesInProgress--;\n }\n }\n\n });\n }\n }\n }\n\n public void refreshPixelPerfectTree() {\n final IDevice device = PixelPerfectModel.getModel().getDevice();\n if (device != null) {\n executeInBackground(\"Refreshing pixel perfect tree\", new Runnable() {\n @Override\n public void run() {\n ViewNode viewNode =\n DeviceBridge.loadWindowData(Window.getFocusedWindow(device));\n if (viewNode != null) {\n PixelPerfectModel.getModel().setTree(viewNode);\n }\n }\n\n });\n }\n }\n\n public void loadPixelPerfectData(final IDevice device) {\n executeInBackground(\"Loading pixel perfect data\", new Runnable() {\n @Override\n public void run() {\n Image screenshotImage = getScreenshotImage(device);\n if (screenshotImage != null) {\n ViewNode viewNode =\n DeviceBridge.loadWindowData(Window.getFocusedWindow(device));\n if (viewNode != null) {\n PixelPerfectModel.getModel().setData(device, screenshotImage, viewNode);\n }\n }\n }\n });\n }\n\n private Image getScreenshotImage(IDevice device) {\n try {\n final RawImage screenshot = device.getScreenshot();\n if (screenshot == null) {\n return null;\n }\n class ImageContainer {\n public Image image;\n }\n final ImageContainer imageContainer = new ImageContainer();\n Display.getDefault().syncExec(new Runnable() {\n @Override\n public void run() {\n ImageData imageData =\n new ImageData(screenshot.width, screenshot.height, screenshot.bpp,\n new PaletteData(screenshot.getRedMask(), screenshot\n .getGreenMask(), screenshot.getBlueMask()), 1,\n screenshot.data);\n imageContainer.image = new Image(Display.getDefault(), imageData);\n }\n });\n return imageContainer.image;\n } catch (IOException e) {\n Log.e(TAG, \"Unable to load screenshot from device \" + device);\n } catch (TimeoutException e) {\n Log.e(TAG, \"Timeout loading screenshot from device \" + device);\n } catch (AdbCommandRejectedException e) {\n Log.e(TAG, \"Adb rejected command to load screenshot from device \" + device);\n }\n return null;\n }\n\n public void loadViewTreeData(final Window window) {\n executeInBackground(\"Loading view hierarchy\", new Runnable() {\n @Override\n public void run() {\n\n mFilterText = \"\"; //$NON-NLS-1$\n\n ViewNode viewNode = DeviceBridge.loadWindowData(window);\n if (viewNode != null) {\n DeviceBridge.loadProfileData(window, viewNode);\n viewNode.setViewCount();\n TreeViewModel.getModel().setData(window, viewNode);\n }\n }\n });\n }\n\n public void loadOverlay(final Shell shell) {\n Display.getDefault().syncExec(new Runnable() {\n @Override\n public void run() {\n FileDialog fileDialog = new FileDialog(shell, SWT.OPEN);\n fileDialog.setFilterExtensions(new String[] {\n \"*.jpg;*.jpeg;*.png;*.gif;*.bmp\" //$NON-NLS-1$\n });\n fileDialog.setFilterNames(new String[] {\n \"Image (*.jpg, *.jpeg, *.png, *.gif, *.bmp)\"\n });\n fileDialog.setText(\"Choose an overlay image\");\n String fileName = fileDialog.open();\n if (fileName != null) {\n try {\n Image image = new Image(Display.getDefault(), fileName);\n PixelPerfectModel.getModel().setOverlayImage(image);\n } catch (SWTException e) {\n Log.e(TAG, \"Unable to load image from \" + fileName);\n }\n }\n }\n });\n }\n\n public void showCapture(final Shell shell, final ViewNode viewNode) {\n executeInBackground(\"Capturing node\", new Runnable() {\n @Override\n public void run() {\n final Image image = loadCapture(viewNode);\n if (image != null) {\n\n Display.getDefault().syncExec(new Runnable() {\n @Override\n public void run() {\n CaptureDisplay.show(shell, viewNode, image);\n }\n });\n }\n }\n });\n }\n\n public Image loadCapture(ViewNode viewNode) {\n final Image image = DeviceBridge.loadCapture(viewNode.window, viewNode);\n if (image != null) {\n viewNode.image = image;\n\n // Force the layout viewer to redraw.\n TreeViewModel.getModel().notifySelectionChanged();\n }\n return image;\n }\n\n public void loadCaptureInBackground(final ViewNode viewNode) {\n executeInBackground(\"Capturing node\", new Runnable() {\n @Override\n public void run() {\n loadCapture(viewNode);\n }\n });\n }\n\n public void showCapture(Shell shell) {\n DrawableViewNode viewNode = TreeViewModel.getModel().getSelection();\n if (viewNode != null) {\n showCapture(shell, viewNode.viewNode);\n }\n }\n\n public void refreshWindows() {\n executeInBackground(\"Refreshing windows\", new Runnable() {\n @Override\n public void run() {\n IDevice[] devicesA = DeviceSelectionModel.getModel().getDevices();\n IDevice[] devicesB = DeviceBridge.getDevices();\n HashSet<IDevice> deviceSet = new HashSet<IDevice>();\n for (int i = 0; i < devicesB.length; i++) {\n deviceSet.add(devicesB[i]);\n }\n for (int i = 0; i < devicesA.length; i++) {\n if (deviceSet.contains(devicesA[i])) {\n windowsChanged(devicesA[i]);\n deviceSet.remove(devicesA[i]);\n } else {\n deviceDisconnected(devicesA[i]);\n }\n }\n for (IDevice device : deviceSet) {\n deviceConnected(device);\n }\n }\n });\n }\n\n public void loadViewHierarchy() {\n Window window = DeviceSelectionModel.getModel().getSelectedWindow();\n if(logDebug) logger.debug(window.getTitle());\n if (window != null) {\n loadViewTreeData(window);\n }\n }\n\n public void inspectScreenshot() {\n IDevice device = DeviceSelectionModel.getModel().getSelectedDevice();\n if (device != null) {\n loadPixelPerfectData(device);\n }\n }\n\n public void saveTreeView(final Shell shell) {\n Display.getDefault().syncExec(new Runnable() {\n @Override\n public void run() {\n final DrawableViewNode viewNode = TreeViewModel.getModel().getTree();\n if (viewNode != null) {\n FileDialog fileDialog = new FileDialog(shell, SWT.SAVE);\n fileDialog.setFilterExtensions(new String[] {\n \"*.png\" //$NON-NLS-1$\n });\n fileDialog.setFilterNames(new String[] {\n \"Portable Network Graphics File (*.png)\"\n });\n fileDialog.setText(\"Choose where to save the tree image\");\n final String fileName = fileDialog.open();\n if (fileName != null) {\n executeInBackground(\"Saving tree view\", new Runnable() {\n @Override\n public void run() {\n Image image = TreeView.paintToImage(viewNode);\n ImageLoader imageLoader = new ImageLoader();\n imageLoader.data = new ImageData[] {\n image.getImageData()\n };\n String extensionedFileName = fileName;\n if (!extensionedFileName.toLowerCase().endsWith(\".png\")) { //$NON-NLS-1$\n extensionedFileName += \".png\"; //$NON-NLS-1$\n }\n try {\n imageLoader.save(extensionedFileName, SWT.IMAGE_PNG);\n } catch (SWTException e) {\n Log.e(TAG, \"Unable to save tree view as a PNG image at \"\n + fileName);\n }\n image.dispose();\n }\n });\n }\n }\n }\n });\n }\n\n public void savePixelPerfect(final Shell shell) {\n Display.getDefault().syncExec(new Runnable() {\n @Override\n public void run() {\n Image untouchableImage = PixelPerfectModel.getModel().getImage();\n if (untouchableImage != null) {\n final ImageData imageData = untouchableImage.getImageData();\n FileDialog fileDialog = new FileDialog(shell, SWT.SAVE);\n fileDialog.setFilterExtensions(new String[] {\n \"*.png\" //$NON-NLS-1$\n });\n fileDialog.setFilterNames(new String[] {\n \"Portable Network Graphics File (*.png)\"\n });\n fileDialog.setText(\"Choose where to save the screenshot\");\n final String fileName = fileDialog.open();\n if (fileName != null) {\n executeInBackground(\"Saving pixel perfect\", new Runnable() {\n @Override\n public void run() {\n ImageLoader imageLoader = new ImageLoader();\n imageLoader.data = new ImageData[] {\n imageData\n };\n String extensionedFileName = fileName;\n if (!extensionedFileName.toLowerCase().endsWith(\".png\")) { //$NON-NLS-1$\n extensionedFileName += \".png\"; //$NON-NLS-1$\n }\n try {\n imageLoader.save(extensionedFileName, SWT.IMAGE_PNG);\n } catch (SWTException e) {\n Log.e(TAG, \"Unable to save tree view as a PNG image at \"\n + fileName);\n }\n }\n });\n }\n }\n }\n });\n }\n\n public void capturePSD(final Shell shell) {\n Display.getDefault().syncExec(new Runnable() {\n @Override\n public void run() {\n final Window window = TreeViewModel.getModel().getWindow();\n if (window != null) {\n FileDialog fileDialog = new FileDialog(shell, SWT.SAVE);\n fileDialog.setFilterExtensions(new String[] {\n \"*.psd\" //$NON-NLS-1$\n });\n fileDialog.setFilterNames(new String[] {\n \"Photoshop Document (*.psd)\"\n });\n fileDialog.setText(\"Choose where to save the window layers\");\n final String fileName = fileDialog.open();\n if (fileName != null) {\n executeInBackground(\"Saving window layers\", new Runnable() {\n @Override\n public void run() {\n PsdFile psdFile = DeviceBridge.captureLayers(window);\n if (psdFile != null) {\n String extensionedFileName = fileName;\n if (!extensionedFileName.toLowerCase().endsWith(\".psd\")) { //$NON-NLS-1$\n extensionedFileName += \".psd\"; //$NON-NLS-1$\n }\n try {\n psdFile.write(new FileOutputStream(extensionedFileName));\n } catch (FileNotFoundException e) {\n Log.e(TAG, \"Unable to write to file \" + fileName);\n }\n }\n }\n });\n }\n }\n }\n });\n }\n\n public void reloadViewHierarchy() {\n Window window = TreeViewModel.getModel().getWindow();\n if (window != null) {\n loadViewTreeData(window);\n }\n }\n\n public void invalidateCurrentNode() {\n final DrawableViewNode selectedNode = TreeViewModel.getModel().getSelection();\n if (selectedNode != null) {\n executeInBackground(\"Invalidating view\", new Runnable() {\n @Override\n public void run() {\n DeviceBridge.invalidateView(selectedNode.viewNode);\n }\n });\n }\n }\n\n public void relayoutCurrentNode() {\n final DrawableViewNode selectedNode = TreeViewModel.getModel().getSelection();\n if (selectedNode != null) {\n executeInBackground(\"Request layout\", new Runnable() {\n @Override\n public void run() {\n DeviceBridge.requestLayout(selectedNode.viewNode);\n }\n });\n }\n }\n\n public void dumpDisplayListForCurrentNode() {\n final DrawableViewNode selectedNode = TreeViewModel.getModel().getSelection();\n if (selectedNode != null) {\n executeInBackground(\"Dump displaylist\", new Runnable() {\n @Override\n public void run() {\n DeviceBridge.outputDisplayList(selectedNode.viewNode);\n }\n });\n }\n }\n\n public void loadAllViews() {\n executeInBackground(\"Loading all views\", new Runnable() {\n @Override\n public void run() {\n DrawableViewNode tree = TreeViewModel.getModel().getTree();\n if (tree != null) {\n loadViewRecursive(tree.viewNode);\n // Force the layout viewer to redraw.\n TreeViewModel.getModel().notifySelectionChanged();\n }\n }\n });\n }\n\n private void loadViewRecursive(ViewNode viewNode) {\n Image image = DeviceBridge.loadCapture(viewNode.window, viewNode);\n if (image == null) {\n return;\n }\n viewNode.image = image;\n final int N = viewNode.children.size();\n for (int i = 0; i < N; i++) {\n loadViewRecursive(viewNode.children.get(i));\n }\n }\n\n public void filterNodes(String filterText) {\n this.mFilterText = filterText;\n DrawableViewNode tree = TreeViewModel.getModel().getTree();\n if (tree != null) {\n tree.viewNode.filter(filterText);\n // Force redraw\n TreeViewModel.getModel().notifySelectionChanged();\n }\n }\n\n public String getFilterText() {\n return mFilterText;\n }\n\n private static class PixelPerfectAutoRefreshTask extends TimerTask {\n @Override\n public void run() {\n HierarchyViewerDirector.getDirector().refreshPixelPerfect();\n }\n };\n\n public void setPixelPerfectAutoRefresh(boolean value) {\n synchronized (mPixelPerfectRefreshTimer) {\n if (value == mAutoRefresh) {\n return;\n }\n mAutoRefresh = value;\n if (mAutoRefresh) {\n mCurrentAutoRefreshTask = new PixelPerfectAutoRefreshTask();\n mPixelPerfectRefreshTimer.schedule(mCurrentAutoRefreshTask,\n mPixelPerfectAutoRefreshInterval * 1000,\n mPixelPerfectAutoRefreshInterval * 1000);\n } else {\n mCurrentAutoRefreshTask.cancel();\n mCurrentAutoRefreshTask = null;\n }\n }\n }\n\n public void setPixelPerfectAutoRefreshInterval(int value) {\n synchronized (mPixelPerfectRefreshTimer) {\n if (mPixelPerfectAutoRefreshInterval == value) {\n return;\n }\n mPixelPerfectAutoRefreshInterval = value;\n if (mAutoRefresh) {\n mCurrentAutoRefreshTask.cancel();\n long timeLeft =\n Math.max(0, mPixelPerfectAutoRefreshInterval\n * 1000\n - (System.currentTimeMillis() - mCurrentAutoRefreshTask\n .scheduledExecutionTime()));\n mCurrentAutoRefreshTask = new PixelPerfectAutoRefreshTask();\n mPixelPerfectRefreshTimer.schedule(mCurrentAutoRefreshTask, timeLeft,\n mPixelPerfectAutoRefreshInterval * 1000);\n }\n }\n }\n\n public int getPixelPerfectAutoRefreshInverval() {\n return mPixelPerfectAutoRefreshInterval;\n }\n}", "public static enum ProfileRating {\n RED, YELLOW, GREEN, NONE\n};", "public class TreeViewModel {\n public static final double MAX_ZOOM = 2;\n\n public static final double MIN_ZOOM = 0.2;\n\n private Window mWindow;\n\n private DrawableViewNode mTree;\n\n private DrawableViewNode mSelectedNode;\n\n private Rectangle mViewport;\n\n private double mZoom;\n\n private final ArrayList<ITreeChangeListener> mTreeChangeListeners =\n new ArrayList<ITreeChangeListener>();\n\n private static TreeViewModel sModel;\n\n public static TreeViewModel getModel() {\n if (sModel == null) {\n sModel = new TreeViewModel();\n }\n return sModel;\n }\n\n public void setData(Window window, ViewNode viewNode) {\n synchronized (this) {\n if (mTree != null) {\n mTree.viewNode.dispose();\n }\n this.mWindow = window;\n if (viewNode == null) {\n mTree = null;\n } else {\n mTree = new DrawableViewNode(viewNode);\n mTree.setLeft();\n mTree.placeRoot();\n }\n mViewport = null;\n mZoom = 1;\n mSelectedNode = null;\n }\n notifyTreeChanged();\n }\n\n public void setSelection(DrawableViewNode selectedNode) {\n synchronized (this) {\n this.mSelectedNode = selectedNode;\n }\n notifySelectionChanged();\n }\n\n public void setViewport(Rectangle viewport) {\n synchronized (this) {\n this.mViewport = viewport;\n }\n notifyViewportChanged();\n }\n\n public void setZoom(double newZoom) {\n Point zoomPoint = null;\n synchronized (this) {\n if (mTree != null && mViewport != null) {\n zoomPoint =\n new Point(mViewport.x + mViewport.width / 2, mViewport.y + mViewport.height / 2);\n }\n }\n zoomOnPoint(newZoom, zoomPoint);\n }\n\n public void zoomOnPoint(double newZoom, Point zoomPoint) {\n synchronized (this) {\n if (mTree != null && this.mViewport != null) {\n if (newZoom < MIN_ZOOM) {\n newZoom = MIN_ZOOM;\n }\n if (newZoom > MAX_ZOOM) {\n newZoom = MAX_ZOOM;\n }\n mViewport.x = zoomPoint.x - (zoomPoint.x - mViewport.x) * mZoom / newZoom;\n mViewport.y = zoomPoint.y - (zoomPoint.y - mViewport.y) * mZoom / newZoom;\n mViewport.width = mViewport.width * mZoom / newZoom;\n mViewport.height = mViewport.height * mZoom / newZoom;\n mZoom = newZoom;\n }\n }\n notifyZoomChanged();\n }\n\n public DrawableViewNode getTree() {\n synchronized (this) {\n return mTree;\n }\n }\n\n public Window getWindow() {\n synchronized (this) {\n return mWindow;\n }\n }\n\n public Rectangle getViewport() {\n synchronized (this) {\n return mViewport;\n }\n }\n\n public double getZoom() {\n synchronized (this) {\n return mZoom;\n }\n }\n\n public DrawableViewNode getSelection() {\n synchronized (this) {\n return mSelectedNode;\n }\n }\n\n public static interface ITreeChangeListener {\n public void treeChanged();\n\n public void selectionChanged();\n\n public void viewportChanged();\n\n public void zoomChanged();\n }\n\n private ITreeChangeListener[] getTreeChangeListenerList() {\n ITreeChangeListener[] listeners = null;\n synchronized (mTreeChangeListeners) {\n if (mTreeChangeListeners.size() == 0) {\n return null;\n }\n listeners =\n mTreeChangeListeners.toArray(new ITreeChangeListener[mTreeChangeListeners.size()]);\n }\n return listeners;\n }\n\n public void notifyTreeChanged() {\n ITreeChangeListener[] listeners = getTreeChangeListenerList();\n if (listeners != null) {\n for (int i = 0; i < listeners.length; i++) {\n listeners[i].treeChanged();\n }\n }\n }\n\n public void notifySelectionChanged() {\n ITreeChangeListener[] listeners = getTreeChangeListenerList();\n if (listeners != null) {\n for (int i = 0; i < listeners.length; i++) {\n listeners[i].selectionChanged();\n }\n }\n }\n\n public void notifyViewportChanged() {\n ITreeChangeListener[] listeners = getTreeChangeListenerList();\n if (listeners != null) {\n for (int i = 0; i < listeners.length; i++) {\n listeners[i].viewportChanged();\n }\n }\n }\n\n public void notifyZoomChanged() {\n ITreeChangeListener[] listeners = getTreeChangeListenerList();\n if (listeners != null) {\n for (int i = 0; i < listeners.length; i++) {\n listeners[i].zoomChanged();\n }\n }\n }\n\n public void addTreeChangeListener(ITreeChangeListener listener) {\n synchronized (mTreeChangeListeners) {\n mTreeChangeListeners.add(listener);\n }\n }\n\n public void removeTreeChangeListener(ITreeChangeListener listener) {\n synchronized (mTreeChangeListeners) {\n mTreeChangeListeners.remove(listener);\n }\n }\n}", "public static interface ITreeChangeListener {\n public void treeChanged();\n\n public void selectionChanged();\n\n public void viewportChanged();\n\n public void zoomChanged();\n}", "public class DrawableViewNode {\n public ViewNode viewNode;\n\n public final ArrayList<DrawableViewNode> children = new ArrayList<DrawableViewNode>();\n\n public final static int NODE_HEIGHT = 100;\n\n public final static int NODE_WIDTH = 180;\n\n public final static int CONTENT_LEFT_RIGHT_PADDING = 9;\n\n public final static int CONTENT_TOP_BOTTOM_PADDING = 8;\n\n public final static int CONTENT_INTER_PADDING = 3;\n\n public final static int INDEX_PADDING = 7;\n\n public final static int LEAF_NODE_SPACING = 9;\n\n public final static int NON_LEAF_NODE_SPACING = 15;\n\n public final static int PARENT_CHILD_SPACING = 50;\n\n public final static int PADDING = 30;\n\n public int treeHeight;\n\n public int treeWidth;\n\n public boolean leaf;\n\n public DrawableViewNode parent;\n\n public int left;\n\n public double top;\n\n public int topSpacing;\n\n public int bottomSpacing;\n\n public boolean treeDrawn;\n\n public static class Rectangle {\n public double x, y, width, height;\n\n public Rectangle() {\n\n }\n\n public Rectangle(Rectangle other) {\n this.x = other.x;\n this.y = other.y;\n this.width = other.width;\n this.height = other.height;\n }\n\n public Rectangle(double x, double y, double width, double height) {\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n }\n\n @Override\n public String toString() {\n return \"{\" + x + \", \" + y + \", \" + width + \", \" + height + \"}\"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$\n }\n\n }\n\n public static class Point {\n public double x, y;\n\n public Point() {\n }\n\n public Point(double x, double y) {\n this.x = x;\n this.y = y;\n }\n\n @Override\n public String toString() {\n return \"(\" + x + \", \" + y + \")\"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$\n }\n }\n\n public Rectangle bounds = new Rectangle();\n\n public DrawableViewNode(ViewNode viewNode) {\n this.viewNode = viewNode;\n treeDrawn = !viewNode.willNotDraw;\n if (viewNode.children.size() == 0) {\n treeHeight = NODE_HEIGHT;\n treeWidth = NODE_WIDTH;\n leaf = true;\n } else {\n leaf = false;\n int N = viewNode.children.size();\n treeHeight = 0;\n treeWidth = 0;\n for (int i = 0; i < N; i++) {\n DrawableViewNode child = new DrawableViewNode(viewNode.children.get(i));\n children.add(child);\n child.parent = this;\n treeHeight += child.treeHeight;\n treeWidth = Math.max(treeWidth, child.treeWidth);\n if (i != 0) {\n DrawableViewNode prevChild = children.get(i - 1);\n if (prevChild.leaf && child.leaf) {\n treeHeight += LEAF_NODE_SPACING;\n prevChild.bottomSpacing = LEAF_NODE_SPACING;\n child.topSpacing = LEAF_NODE_SPACING;\n } else {\n treeHeight += NON_LEAF_NODE_SPACING;\n prevChild.bottomSpacing = NON_LEAF_NODE_SPACING;\n child.topSpacing = NON_LEAF_NODE_SPACING;\n }\n }\n treeDrawn |= child.treeDrawn;\n }\n treeWidth += NODE_WIDTH + PARENT_CHILD_SPACING;\n }\n }\n\n public void setLeft() {\n if (parent == null) {\n left = PADDING;\n bounds.x = 0;\n bounds.width = treeWidth + 2 * PADDING;\n } else {\n left = parent.left + NODE_WIDTH + PARENT_CHILD_SPACING;\n }\n int N = children.size();\n for (int i = 0; i < N; i++) {\n children.get(i).setLeft();\n }\n }\n\n public void placeRoot() {\n top = PADDING + (treeHeight - NODE_HEIGHT) / 2.0;\n double currentTop = PADDING;\n int N = children.size();\n for (int i = 0; i < N; i++) {\n DrawableViewNode child = children.get(i);\n child.place(currentTop, top - currentTop);\n currentTop += child.treeHeight + child.bottomSpacing;\n }\n bounds.y = 0;\n bounds.height = treeHeight + 2 * PADDING;\n }\n\n private void place(double treeTop, double rootDistance) {\n if (treeHeight <= rootDistance) {\n top = treeTop + treeHeight - NODE_HEIGHT;\n } else if (rootDistance <= -NODE_HEIGHT) {\n top = treeTop;\n } else {\n if (children.size() == 0) {\n top = treeTop;\n } else {\n top =\n rootDistance + treeTop - NODE_HEIGHT + (2.0 * NODE_HEIGHT)\n / (treeHeight + NODE_HEIGHT) * (treeHeight - rootDistance);\n }\n }\n int N = children.size();\n double currentTop = treeTop;\n for (int i = 0; i < N; i++) {\n DrawableViewNode child = children.get(i);\n child.place(currentTop, rootDistance);\n currentTop += child.treeHeight + child.bottomSpacing;\n rootDistance -= child.treeHeight + child.bottomSpacing;\n }\n }\n\n public DrawableViewNode getSelected(double x, double y) {\n if (x >= left && x < left + NODE_WIDTH && y >= top && y <= top + NODE_HEIGHT) {\n return this;\n }\n int N = children.size();\n for (int i = 0; i < N; i++) {\n DrawableViewNode selected = children.get(i).getSelected(x, y);\n if (selected != null) {\n return selected;\n }\n }\n return null;\n }\n\n /*\n * Moves the node the specified distance up.\n */\n public void move(double distance) {\n top -= distance;\n\n // Get the root\n DrawableViewNode root = this;\n while (root.parent != null) {\n root = root.parent;\n }\n\n // Figure out the new tree top.\n double treeTop;\n if (top + NODE_HEIGHT <= root.top) {\n treeTop = top + NODE_HEIGHT - treeHeight;\n } else if (top >= root.top + NODE_HEIGHT) {\n treeTop = top;\n } else {\n if (leaf) {\n treeTop = top;\n } else {\n double distanceRatio = 1 - (root.top + NODE_HEIGHT - top) / (2.0 * NODE_HEIGHT);\n treeTop = root.top - treeHeight + distanceRatio * (treeHeight + NODE_HEIGHT);\n }\n }\n // Go up the tree and figure out the tree top.\n DrawableViewNode node = this;\n while (node.parent != null) {\n int index = node.viewNode.index;\n for (int i = 0; i < index; i++) {\n DrawableViewNode sibling = node.parent.children.get(i);\n treeTop -= sibling.treeHeight + sibling.bottomSpacing;\n }\n node = node.parent;\n }\n\n // Update the bounds.\n root.bounds.y = Math.min(root.top - PADDING, treeTop - PADDING);\n root.bounds.height =\n Math.max(treeTop + root.treeHeight + PADDING, root.top + NODE_HEIGHT + PADDING)\n - root.bounds.y;\n // Place all the children of the root\n double currentTop = treeTop;\n int N = root.children.size();\n for (int i = 0; i < N; i++) {\n DrawableViewNode child = root.children.get(i);\n child.place(currentTop, root.top - currentTop);\n currentTop += child.treeHeight + child.bottomSpacing;\n }\n\n }\n}", "public static class Point {\n public double x, y;\n\n public Point() {\n }\n\n public Point(double x, double y) {\n this.x = x;\n this.y = y;\n }\n\n @Override\n public String toString() {\n return \"(\" + x + \", \" + y + \")\"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$\n }\n}", "public static class Rectangle {\n public double x, y, width, height;\n\n public Rectangle() {\n\n }\n\n public Rectangle(Rectangle other) {\n this.x = other.x;\n this.y = other.y;\n this.width = other.width;\n this.height = other.height;\n }\n\n public Rectangle(double x, double y, double width, double height) {\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n }\n\n @Override\n public String toString() {\n return \"{\" + x + \", \" + y + \", \" + width + \", \" + height + \"}\"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$\n }\n\n}" ]
import java.text.DecimalFormat; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.MouseMoveListener; import org.eclipse.swt.events.MouseWheelListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Path; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Transform; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import com.android.ddmuilib.ImageLoader; import com.android.hierarchyviewerlib.HierarchyViewerDirector; import com.android.hierarchyviewerlib.device.ViewNode.ProfileRating; import com.android.hierarchyviewerlib.models.TreeViewModel; import com.android.hierarchyviewerlib.models.TreeViewModel.ITreeChangeListener; import com.android.hierarchyviewerlib.ui.util.DrawableViewNode; import com.android.hierarchyviewerlib.ui.util.DrawableViewNode.Point; import com.android.hierarchyviewerlib.ui.util.DrawableViewNode.Rectangle;
private Listener mResizeListener = new Listener() { @Override public void handleEvent(Event e) { synchronized (TreeView.this) { if (mTree != null && mViewport != null) { // Keep the center in the same place. Point viewCenter = new Point(mViewport.x + mViewport.width / 2, mViewport.y + mViewport.height / 2); mViewport.width = getBounds().width / mZoom; mViewport.height = getBounds().height / mZoom; mViewport.x = viewCenter.x - mViewport.width / 2; mViewport.y = viewCenter.y - mViewport.height / 2; } } if (mViewport != null) { mModel.setViewport(mViewport); } } }; private KeyListener mKeyListener = new KeyListener() { @Override public void keyPressed(KeyEvent e) { boolean selectionChanged = false; DrawableViewNode clickedNode = null; synchronized (TreeView.this) { if (mTree != null && mViewport != null && mSelectedNode != null) { switch (e.keyCode) { case SWT.ARROW_LEFT: if (mSelectedNode.parent != null) { mSelectedNode = mSelectedNode.parent; selectionChanged = true; } break; case SWT.ARROW_UP: // On up and down, it is cool to go up and down only // the leaf nodes. // It goes well with the layout viewer DrawableViewNode currentNode = mSelectedNode; while (currentNode.parent != null && currentNode.viewNode.index == 0) { currentNode = currentNode.parent; } if (currentNode.parent != null) { selectionChanged = true; currentNode = currentNode.parent.children .get(currentNode.viewNode.index - 1); while (currentNode.children.size() != 0) { currentNode = currentNode.children .get(currentNode.children.size() - 1); } } if (selectionChanged) { mSelectedNode = currentNode; } break; case SWT.ARROW_DOWN: currentNode = mSelectedNode; while (currentNode.parent != null && currentNode.viewNode.index + 1 == currentNode.parent.children .size()) { currentNode = currentNode.parent; } if (currentNode.parent != null) { selectionChanged = true; currentNode = currentNode.parent.children .get(currentNode.viewNode.index + 1); while (currentNode.children.size() != 0) { currentNode = currentNode.children.get(0); } } if (selectionChanged) { mSelectedNode = currentNode; } break; case SWT.ARROW_RIGHT: DrawableViewNode rightNode = null; double mostOverlap = 0; final int N = mSelectedNode.children.size(); // We consider all the children and pick the one // who's tree overlaps the most. for (int i = 0; i < N; i++) { DrawableViewNode child = mSelectedNode.children.get(i); DrawableViewNode topMostChild = child; while (topMostChild.children.size() != 0) { topMostChild = topMostChild.children.get(0); } double overlap = Math.min(DrawableViewNode.NODE_HEIGHT, Math.min( mSelectedNode.top + DrawableViewNode.NODE_HEIGHT - topMostChild.top, topMostChild.top + child.treeHeight - mSelectedNode.top)); if (overlap > mostOverlap) { mostOverlap = overlap; rightNode = child; } } if (rightNode != null) { mSelectedNode = rightNode; selectionChanged = true; } break; case SWT.CR: clickedNode = mSelectedNode; break; } } } if (selectionChanged) { mModel.setSelection(mSelectedNode); } if (clickedNode != null) {
HierarchyViewerDirector.getDirector().showCapture(getShell(), clickedNode.viewNode);
0
Catbag/redux-android-sample
app/src/testShared/shared/TestHelper.java
[ "public class DataManager {\n private static Float sRiffsyNext = null;\n private final RiffsyRoutes mRiffsyRoutes;\n\n private Database mDatabase;\n private boolean mIsSavingAppState = false;\n private SaveAppStateRunnable mNextSaveAppStateRunnable;\n\n public DataManager(Context context) {\n mDatabase = new Database(context);\n mRiffsyRoutes = RetrofitBuilder.getInstance()\n .createApiEndpoint(RiffsyRoutes.class, RiffsyRoutes.BASE_URL);\n }\n\n public boolean isSavingAppState() {\n return mIsSavingAppState;\n }\n\n public void saveAppState(AppState appState) {\n mNextSaveAppStateRunnable = new DataManager.SaveAppStateRunnable(appState);\n executeSaveAppStateTask();\n }\n\n public void loadAppState(final LoadAppStateListener listener) {\n new Thread(() -> {\n try {\n listener.onLoaded(mDatabase.getAppState());\n } catch (SnappydbException | IOException e) {\n listener.onLoaded(getAppStateDefault());\n Log.e(getClass().getSimpleName(), \"appstate not loaded\", e);\n }\n }).start();\n }\n\n public void fetchGifs(final GifListLoadListener listener) {\n Call call = mRiffsyRoutes.getTrendingResults(RiffsyRoutes.DEFAULT_LIMIT_COUNT, sRiffsyNext);\n call.enqueue(new Callback<RiffsyResponse>() {\n @Override\n public void onResponse(Call<RiffsyResponse> call, Response<RiffsyResponse> response) {\n Map<String, Gif> gifs = extractGifsFromRiffsyResponse(response);\n\n sRiffsyNext = response.body().next();\n boolean hasMore = sRiffsyNext != null;\n listener.onLoaded(gifs, hasMore);\n }\n\n @Override\n public void onFailure(Call<RiffsyResponse> call, Throwable t) {\n Log.e(getClass().getSimpleName(), \"onFailure\", t);\n }\n });\n }\n\n private void executeSaveAppStateTask() {\n if (mNextSaveAppStateRunnable != null && !mIsSavingAppState) {\n mIsSavingAppState = true;\n ThreadUtils.runInBackground(mNextSaveAppStateRunnable);\n mNextSaveAppStateRunnable = null;\n }\n }\n\n private void onFinishedSaveAppStateTask() {\n ThreadUtils.runOnMain(() -> {\n mIsSavingAppState = false;\n executeSaveAppStateTask();\n });\n }\n\n @NonNull\n private Map<String, Gif> extractGifsFromRiffsyResponse(Response<RiffsyResponse> response) {\n List<RiffsyResult> results = response.body().results();\n Map<String, Gif> gifs = new LinkedHashMap<>();\n for (RiffsyResult result : results) {\n List<RiffsyMedia> riffsyMedias = result.media();\n if (riffsyMedias.size() > 0) {\n Gif gif = ImmutableGif.builder()\n .url(riffsyMedias.get(0).gif().url())\n .title(result.title())\n .uuid(UUID.randomUUID().toString()).build();\n gifs.put(gif.getUuid(), gif);\n }\n }\n return gifs;\n }\n\n public static AppState getAppStateDefault() {\n String[] uuids = {\"1\", \"2\", \"3\", \"4\", \"5\" };\n String[] titles = {\"Gif 1\", \"Gif 2\", \"Gif 3\", \"Gif 4\", \"Gif 5\" };\n String[] urls = {\n \"https://media.giphy.com/media/l0HlE56oAxpngfnWM/giphy.gif\",\n \"http://inspirandoideias.com.br/blog/wp-content/uploads/2015/03/\"\n + \"b3368a682fc5ff891e41baad2731f4b6.gif\",\n \"https://media.giphy.com/media/9fbYYzdf6BbQA/giphy.gif\",\n \"https://media.giphy.com/media/l2YWl1oQlNvthGWrK/giphy.gif\",\n \"https://media.giphy.com/media/3oriNQHSU0bVcFW5sA/giphy.gif\"\n };\n\n Map<String, Gif> gifs = new LinkedHashMap<>();\n for (int i = 0; i < titles.length; i++) {\n Gif gif = buildGif(uuids[i], titles[i], urls[i]);\n gifs.put(gif.getUuid(), gif);\n }\n\n return ImmutableAppState.builder().putAllGifs(gifs).build();\n }\n\n private static Gif buildGif(String uuid, String title, String url) {\n return ImmutableGif.builder().uuid(uuid).title(title).url(url).build();\n }\n\n public interface LoadAppStateListener {\n void onLoaded(AppState appState);\n }\n\n public interface GifListLoadListener {\n void onLoaded(Map<String, Gif> gifs, boolean hasMore);\n }\n\n private class SaveAppStateRunnable implements Runnable {\n\n private AppState mAppState;\n\n public SaveAppStateRunnable(AppState appState) {\n mAppState = appState;\n }\n\n @Override\n public void run() {\n try {\n mDatabase.saveAppState(mAppState);\n } catch (SnappydbException | JsonProcessingException e) {\n Log.e(getClass().getSimpleName(), \"unsaved appstate\", e);\n }\n onFinishedSaveAppStateTask();\n }\n\n }\n\n}", "public class FileDownloader {\n\n private static RetrofitBuilder.DownloadRoute sRoutes;\n\n public FileDownloader() {\n sRoutes = RetrofitBuilder.getInstance().createDownloadEndpoint();\n }\n\n public void download(String fileUrl, String pathToSave,\n SuccessDownloadListener successDownloadListener,\n FailureDownloadListener failureDownloadListener) {\n Call<ResponseBody> call = sRoutes.downloadFileWithDynamicUrlSync(fileUrl);\n call.enqueue(new Callback<ResponseBody>() {\n @Override\n public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {\n if (response.isSuccessful()) {\n try {\n readFromNetAndWriteToDisk(response.body().byteStream(), pathToSave);\n } catch (IOException e) {\n if (failureDownloadListener != null) {\n failureDownloadListener\n .onFailure(new FileNotFoundException(\"Not found\"));\n }\n }\n\n if (successDownloadListener != null) successDownloadListener.onSuccess();\n } else if (failureDownloadListener != null) {\n failureDownloadListener.onFailure(new FileNotFoundException(\"Not found\"));\n }\n }\n\n @Override\n public void onFailure(Call<ResponseBody> call, Throwable t) {\n Log.e(FileDownloader.class.getSimpleName(), \"error\");\n failureDownloadListener.onFailure(new Exception(t));\n }\n });\n }\n\n private void readFromNetAndWriteToDisk(InputStream inputStream, String pathToSave)\n throws IOException {\n\n File futureStudioIconFile = new File(pathToSave);\n OutputStream outputStream = new FileOutputStream(futureStudioIconFile);\n byte[] fileReader = new byte[4096];\n\n while (true) {\n //Here the download is done...if some progress was made, here is the local\n int read = inputStream.read(fileReader);\n\n if (read == -1) {\n break;\n }\n outputStream.write(fileReader, 0, read);\n }\n\n outputStream.flush();\n inputStream.close();\n outputStream.close();\n }\n\n public interface SuccessDownloadListener {\n void onSuccess();\n }\n\n public interface FailureDownloadListener {\n void onFailure(Exception e);\n }\n\n}", "public class PersistenceMiddleware extends BaseMiddleware<AppState> implements\n StateListener<AppState> {\n\n private DataManager mDataManager;\n\n public PersistenceMiddleware(DataManager dataManager) {\n super();\n mDataManager = dataManager;\n }\n\n @Override\n public void intercept(AppState appState, Action action) throws Exception {\n switch(action.Type) {\n case APP_STATE_LOAD:\n loadAppState();\n break;\n default:\n break;\n }\n }\n\n @Override\n public boolean hasStateChanged(AppState newState, AppState oldState) {\n return newState != oldState;\n }\n\n @Override\n public void onStateChanged(AppState appState) {\n mDataManager.saveAppState(appState);\n }\n\n private void loadAppState() {\n mDataManager.loadAppState(appState -> mDispatcher.dispatch(\n new Action(APP_STATE_LOADED, appState)));\n }\n\n}", "public class RestMiddleware extends BaseMiddleware<AppState> {\n private final Context mContext;\n private final FileDownloader mFileDownloader;\n private DataManager mDataManager;\n\n public RestMiddleware(Context context, DataManager dataManager, FileDownloader fileDownloader) {\n super();\n mContext = context;\n mDataManager = dataManager;\n mFileDownloader = fileDownloader;\n }\n\n @Override\n public void intercept(AppState appState, Action action) throws Exception {\n switch(action.Type) {\n case GIF_DOWNLOAD_START:\n downloadGif(appState, action);\n break;\n case GIF_LIST_FETCHING:\n fetchGifs(appState);\n break;\n default:\n break;\n }\n }\n\n private void fetchGifs(AppState appState) {\n if (appState.getHasMoreGifs()) {\n mDataManager.fetchGifs((gifs, hasMore) -> {\n Map<String, Object> params = new HashMap<>();\n params.put(PayloadParams.PARAM_GIFS, gifs);\n params.put(PayloadParams.PARAM_HAS_MORE, hasMore);\n mDispatcher.dispatch(new Action(GIF_LIST_UPDATED, params));\n });\n }\n }\n\n private void downloadGif(AppState appState, Action action) {\n Gif gif = appState.getGifs().get(action.Payload.toString());\n String pathToSave = mContext.getExternalFilesDir(null) + File.separator\n + gif.getUuid() + \".gif\";\n\n mFileDownloader.download(gif.getUrl(), pathToSave,\n () -> {\n Map<String, Object> params = new HashMap<>();\n params.put(PayloadParams.PARAM_UUID, gif.getUuid());\n params.put(PayloadParams.PARAM_PATH, pathToSave);\n mDispatcher.dispatch(new Action(GIF_DOWNLOAD_SUCCESS, params));\n },\n e -> mDispatcher.dispatch(new Action(GIF_DOWNLOAD_FAILURE, gif.getUuid())));\n }\n}", "@SuppressWarnings(\"PMD.BooleanGetMethodName\")\[email protected]\n@JsonSerialize(as = ImmutableAppState.class)\n@JsonDeserialize(as = ImmutableAppState.class)\npublic abstract class AppState {\n\n @Value.Default\n public Map<String, Gif> getGifs() {\n return new LinkedHashMap<>();\n }\n\n @Value.Default\n public boolean getHasMoreGifs() {\n return true;\n }\n\n public String toJson() throws JsonProcessingException {\n return new ObjectMapper().writeValueAsString(this);\n }\n\n public static AppState fromJson(String json) throws IOException {\n ObjectMapper mapper = new ObjectMapper();\n mapper.registerModule(new GuavaModule());\n return mapper.readValue(json, AppState.class);\n }\n\n}", "@SuppressWarnings(\"PMD.BooleanGetMethodName\")\[email protected]\n@JsonSerialize(as = ImmutableGif.class)\n@JsonDeserialize(as = ImmutableGif.class)\npublic abstract class Gif {\n\n public enum Status {\n PAUSED, LOOPING, DOWNLOADING, DOWNLOADED, NOT_DOWNLOADED, DOWNLOAD_FAILED\n }\n\n //abstract method are immutable by default\n public abstract String getUuid();\n\n @Value.Default\n public String getPath() {\n return \"\";\n }\n\n public abstract String getUrl();\n \n public abstract String getTitle();\n\n @Value.Default\n public boolean getWatched() {\n return false;\n }\n\n @Value.Default\n public Status getStatus() {\n return Status.NOT_DOWNLOADED;\n }\n\n public String toJson() throws JsonProcessingException {\n return new ObjectMapper().writeValueAsString(this);\n }\n\n public static Gif fromJson(String json) throws IOException {\n return new ObjectMapper().readValue(json, Gif.class);\n }\n\n}" ]
import android.content.Context; import android.util.Log; import com.umaplay.fluxxan.Action; import com.umaplay.fluxxan.Fluxxan; import com.umaplay.fluxxan.StateListener; import org.mockito.ArgumentCaptor; import java.util.LinkedHashMap; import java.util.Map; import java.util.Random; import java.util.UUID; import br.com.catbag.gifreduxsample.asyncs.data.DataManager; import br.com.catbag.gifreduxsample.asyncs.data.net.downloader.FileDownloader; import br.com.catbag.gifreduxsample.middlewares.PersistenceMiddleware; import br.com.catbag.gifreduxsample.middlewares.RestMiddleware; import br.com.catbag.gifreduxsample.models.AppState; import br.com.catbag.gifreduxsample.models.Gif; import br.com.catbag.gifreduxsample.models.ImmutableAppState; import br.com.catbag.gifreduxsample.models.ImmutableGif; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock;
} } public Fluxxan<AppState> getFluxxan() { return mFluxxan; } public void sleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Log.e(getClass().getSimpleName(), "", e); } } // Helpers methods to dry up unit tests public void dispatchAction(Action action) { getFluxxan().getDispatcher().dispatch(action); // Since the dispatcher send actions in background we need wait the response arrives while (!isStateChanged() || getFluxxan().getDispatcher().isDispatching()) { sleep(5); } setStateChanged(false); } public void dispatchFakeAppState(AppState state) { dispatchAction(new Action(FakeReducer.FAKE_REDUCE_ACTION, state)); } public Gif firstAppStateGif() { Map<String, Gif> gifs = getFluxxan().getState().getGifs(); if (gifs.size() <= 0) return null; return gifs.values().iterator().next(); } public static AppState buildAppState(Gif gif) { return ImmutableAppState.builder().putGifs(gif.getUuid(), gif).build(); } public static AppState buildAppState(Map<String, Gif> gifs) { return ImmutableAppState.builder().gifs(gifs).build(); } public static Gif buildGif() { return gifBuilderWithDefault().build(); } public static Gif buildGif(Gif.Status status) { return buildGif(status, DEFAULT_UUID); } public static Gif buildGif(Gif.Status status, String uuid) { return gifBuilderWithDefault() .uuid(uuid) .status(status) .build(); } public static ImmutableGif.Builder gifBuilderWithEmpty() { return ImmutableGif.builder() .uuid(UUID.randomUUID().toString()) .title("") .url(""); } public static ImmutableGif.Builder gifBuilderWithDefault() { return ImmutableGif.builder() .uuid(DEFAULT_UUID) .title("Gif") .url("https://media.giphy.com/media/l0HlE56oAxpngfnWM/giphy.gif") .status(Gif.Status.NOT_DOWNLOADED); } public static Map<String, Gif> buildFiveGifs() { String[] titles = {"Gif 1", "Gif 2", "Gif 3", "Gif 4", "Gif 5" }; String[] urls = { "https://media.giphy.com/media/l0HlE56oAxpngfnWM/giphy.gif", "http://inspirandoideias.com.br/blog/wp-content/uploads/2015/03/" + "b3368a682fc5ff891e41baad2731f4b6.gif", "https://media.giphy.com/media/9fbYYzdf6BbQA/giphy.gif", "https://media.giphy.com/media/l2YWl1oQlNvthGWrK/giphy.gif", "https://media.giphy.com/media/3oriNQHSU0bVcFW5sA/giphy.gif" }; Map<String, Gif> gifs = new LinkedHashMap<>(); for (int i = 0; i < titles.length; i++) { Gif gif = ImmutableGif.builder().uuid(UUID.randomUUID().toString()) .title(titles[i]) .url(urls[i]) .build(); gifs.put(gif.getUuid(), gif); } return gifs; } public DataManager mockDataManagerFetch(Map<String, Gif> expectedGifs, boolean expectedHasMore) { DataManager dataManager = mock(DataManager.class); ArgumentCaptor<DataManager.GifListLoadListener> listenerCaptor = ArgumentCaptor.forClass(DataManager.GifListLoadListener.class); doAnswer((invocationOnMock) -> { new Thread(() -> { // The fluxxan don't let we dispatch when it's dispatching while (mFluxxan.getDispatcher().isDispatching()) { try { Thread.sleep(5); } catch (InterruptedException e) { Log.e("Test", e.getMessage(), e); } } listenerCaptor.getValue().onLoaded(expectedGifs, expectedHasMore); }).start(); return null; }).when(dataManager).fetchGifs(listenerCaptor.capture()); return dataManager; } private void clearRestMiddleware() {
getFluxxan().getDispatcher().unregisterMiddleware(RestMiddleware.class);
3
nidi3/raml-tester-proxy
raml-tester-client/src/test/java/guru/nidi/ramlproxy/MockTest.java
[ "public abstract class RamlProxyServer implements AutoCloseable {\n private static final Logger log = LoggerFactory.getLogger(RamlProxyServer.class);\n\n protected final ServerOptions options;\n private final ReportSaver saver;\n private final Thread shutdownHook;\n\n public RamlProxyServer(ServerOptions options, ReportSaver saver) {\n this.options = options;\n this.saver = saver;\n shutdownHook = shutdownHook(saver);\n Runtime.getRuntime().addShutdownHook(shutdownHook);\n }\n\n abstract protected void start() throws Exception;\n\n abstract protected boolean stop() throws Exception;\n\n abstract public void waitForServer() throws InterruptedException;\n\n abstract public boolean isStopped();\n\n protected void doStart() {\n for (int i = 0; i < 10; i++) {\n try {\n start();\n return;\n } catch (BindException e) {\n log.warn(\"Another server is still running. Retry to start again in 10 ms...\");\n try {\n Thread.sleep(10);\n } catch (InterruptedException e1) {\n //ignore\n }\n } catch (Exception e) {\n throw new RuntimeException(\"Problem starting server\", e);\n }\n }\n throw new RuntimeException(\"Another server is still running. Stop it.\");\n }\n\n public RamlDefinition fetchRamlDefinition() {\n return options.fetchRamlDefinition();\n }\n\n public RamlReport validateRaml(RamlDefinition ramlDefinition) {\n return options.validateRaml(ramlDefinition);\n }\n\n public void delay() {\n if (options.getMaxDelay() > 0) {\n final int delay = options.getMinDelay() + (int) Math.floor(Math.random() * (1 + options.getMaxDelay() - options.getMinDelay()));\n try {\n Thread.sleep(delay);\n } catch (InterruptedException e) {\n //ignore\n }\n }\n }\n\n public ReportSaver getSaver() {\n return saver;\n }\n\n @Override\n public void close() throws Exception {\n if (stop()) {\n Runtime.getRuntime().removeShutdownHook(shutdownHook);\n shutdownHook.start();\n shutdownHook.join();\n }\n }\n\n private static Thread shutdownHook(final ReportSaver saver) {\n final Thread thread = new Thread(new Runnable() {\n @Override\n public void run() {\n saver.flushUsage();\n }\n });\n thread.setDaemon(true);\n return thread;\n }\n}", "public class ServerOptions {\n private final int port;\n private final String target;\n private final File mockDir;\n private final String ramlUri;\n private final String baseUri;\n private final File saveDir;\n private final ReportFormat fileFormat;\n private final boolean ignoreXheaders;\n private final boolean asyncMode;\n private final int minDelay, maxDelay;\n private final ValidatorConfigurator validatorConfigurator;\n\n public ServerOptions(int port, String targetOrMockDir, String ramlUri, String baseUri) {\n this(port, target(targetOrMockDir), mockDir(targetOrMockDir), ramlUri, baseUri, null, null, false, false, 0, 0, ValidatorConfigurator.NONE);\n }\n\n public ServerOptions(int port, String targetOrMockDir, String ramlUri, String baseUri, File saveDir, ReportFormat fileFormat, boolean ignoreXheaders) {\n this(port, target(targetOrMockDir), mockDir(targetOrMockDir), ramlUri, baseUri, saveDir, fileFormat, ignoreXheaders, false, 0, 0, ValidatorConfigurator.NONE);\n }\n\n public ServerOptions(int port, String target, File mockDir, String ramlUri, String baseUri, File saveDir, ReportFormat fileFormat, boolean ignoreXheaders, boolean asyncMode, int minDelay, int maxDelay, ValidatorConfigurator validatorConfigurator) {\n this.port = port;\n this.target = target;\n this.mockDir = mockDir;\n this.ramlUri = ramlUri;\n this.baseUri = baseUri;\n this.saveDir = saveDir;\n this.fileFormat = fileFormat == null ? ReportFormat.TEXT : fileFormat;\n this.ignoreXheaders = ignoreXheaders;\n this.asyncMode = asyncMode;\n this.minDelay = minDelay;\n this.maxDelay = maxDelay;\n this.validatorConfigurator = validatorConfigurator;\n }\n\n public ServerOptions withoutAsyncMode() {\n return new ServerOptions(port, target, mockDir, ramlUri, baseUri, saveDir, fileFormat, ignoreXheaders, false, minDelay, maxDelay, validatorConfigurator);\n }\n\n private static String target(String targetOrMockDir) {\n return targetOrMockDir.startsWith(\"http\") ? targetOrMockDir : null;\n }\n\n private static File mockDir(String targetOrMockDir) {\n return targetOrMockDir.startsWith(\"http\") ? null : new File(targetOrMockDir);\n }\n\n public List<String> asCli() {\n final String args = \"\" +\n (\"-p\" + port) +\n (target == null ? \"\" : (\" -t\" + target)) +\n (mockDir == null ? \"\" : (\" -m\" + mockDir.getAbsolutePath())) +\n (\" -r\" + ramlUri) +\n (baseUri == null ? \"\" : (\" -b\" + baseUri)) +\n (saveDir == null ? \"\" : (\" -s\" + saveDir)) +\n (fileFormat == null ? \"\" : (\" -f\" + fileFormat)) +\n (ignoreXheaders ? \" -i\" : \"\") +\n (asyncMode ? \" -a\" : \"\") +\n (\" -d\" + minDelay + \"-\" + maxDelay) +\n (\" \" + validatorConfigurator.asCli());\n return Arrays.asList(args.split(\" \"));\n }\n\n public int getPort() {\n return port;\n }\n\n public String getTarget() {\n return target;\n }\n\n public String getTargetUrl() {\n return target.startsWith(\"http\") ? target : (\"http://\" + target);\n }\n\n public boolean isMockMode() {\n return mockDir != null;\n }\n\n public boolean isValidationOnly() {\n return target == null && mockDir == null;\n }\n\n public File getMockDir() {\n return mockDir;\n }\n\n public String getRamlUri() {\n return ramlUri;\n }\n\n public File getSaveDir() {\n return saveDir;\n }\n\n public String getBaseUri() {\n return baseUri;\n }\n\n public String getBaseOrTargetUri() {\n return getBaseUri() == null\n ? (target == null ? null : getTargetUrl())\n : getBaseUri();\n }\n\n public ReportFormat getFileFormat() {\n return fileFormat;\n }\n\n public boolean isIgnoreXheaders() {\n return ignoreXheaders;\n }\n\n public boolean isAsyncMode() {\n return asyncMode;\n }\n\n public int getMinDelay() {\n return minDelay;\n }\n\n public int getMaxDelay() {\n return maxDelay;\n }\n\n public ValidatorConfigurator getValidatorConfigurator() {\n return validatorConfigurator;\n }\n\n public RamlDefinition fetchRamlDefinition() {\n return RamlLoaders.fromFile(\".\")\n .load(getRamlUri())\n .ignoringXheaders(isIgnoreXheaders())\n .assumingBaseUri(getBaseOrTargetUri());\n }\n\n public RamlReport validateRaml(RamlDefinition ramlDefinition) {\n return getValidatorConfigurator().configure(ramlDefinition.validator()).validate();\n }\n\n @Override\n public String toString() {\n return \"ServerOptions{\" +\n \"port=\" + port +\n \", target='\" + target + '\\'' +\n \", mockDir=\" + mockDir +\n \", ramlUri='\" + ramlUri + '\\'' +\n \", baseUri='\" + baseUri + '\\'' +\n \", saveDir=\" + saveDir +\n \", fileFormat=\" + fileFormat +\n \", ignoreXheaders=\" + ignoreXheaders +\n \", asyncMode=\" + asyncMode +\n \", minDelay=\" + minDelay +\n \", maxDelay=\" + maxDelay +\n \", validatorConfigurator=\" + validatorConfigurator +\n '}';\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n\n final ServerOptions that = (ServerOptions) o;\n\n if (port != that.port) {\n return false;\n }\n if (ignoreXheaders != that.ignoreXheaders) {\n return false;\n }\n if (asyncMode != that.asyncMode) {\n return false;\n }\n if (minDelay != that.minDelay) {\n return false;\n }\n if (maxDelay != that.maxDelay) {\n return false;\n }\n if (target != null ? !target.equals(that.target) : that.target != null) {\n return false;\n }\n if (mockDir != null ? !mockDir.equals(that.mockDir) : that.mockDir != null) {\n return false;\n }\n if (ramlUri != null ? !ramlUri.equals(that.ramlUri) : that.ramlUri != null) {\n return false;\n }\n if (baseUri != null ? !baseUri.equals(that.baseUri) : that.baseUri != null) {\n return false;\n }\n if (saveDir != null ? !saveDir.equals(that.saveDir) : that.saveDir != null) {\n return false;\n }\n if (fileFormat != that.fileFormat) {\n return false;\n }\n return !(validatorConfigurator != null ? !validatorConfigurator.equals(that.validatorConfigurator) : that.validatorConfigurator != null);\n\n }\n\n @Override\n public int hashCode() {\n int result = port;\n result = 31 * result + (target != null ? target.hashCode() : 0);\n result = 31 * result + (mockDir != null ? mockDir.hashCode() : 0);\n result = 31 * result + (ramlUri != null ? ramlUri.hashCode() : 0);\n result = 31 * result + (baseUri != null ? baseUri.hashCode() : 0);\n result = 31 * result + (saveDir != null ? saveDir.hashCode() : 0);\n result = 31 * result + (fileFormat != null ? fileFormat.hashCode() : 0);\n result = 31 * result + (ignoreXheaders ? 1 : 0);\n result = 31 * result + (asyncMode ? 1 : 0);\n result = 31 * result + minDelay;\n result = 31 * result + maxDelay;\n result = 31 * result + (validatorConfigurator != null ? validatorConfigurator.hashCode() : 0);\n return result;\n }\n\n}", "public class ReportSaver {\n private final Map<String, List<ReportInfo>> reports = new HashMap<>();\n private final ReportAggregator aggregator;\n\n public ReportSaver() {\n this(new MultiReportAggregator());\n }\n\n public ReportSaver(ReportAggregator aggregator) {\n this.aggregator = aggregator;\n }\n\n public final synchronized void addReport(RamlReport report, ServletRamlRequest request, ServletRamlResponse response) {\n addingReport(report, request, response);\n aggregator.addReport(report);\n getOrCreateInfos(report.getRaml().title()).add(new ReportInfo(report, request, response));\n }\n\n public final synchronized void flushReports() {\n flushingReports(reports.entrySet());\n reports.clear();\n }\n\n public final void flushUsage() {\n flushingUsage(aggregator);\n aggregator.clear();\n }\n\n protected void addingReport(RamlReport report, ServletRamlRequest request, ServletRamlResponse response) {\n }\n\n protected void flushingReports(Iterable<Map.Entry<String, List<ReportInfo>>> reports) {\n }\n\n protected void flushingUsage(ReportAggregator aggregator) {\n }\n\n public synchronized Iterable<Map.Entry<String, List<ReportInfo>>> getReports() {\n return reports.entrySet();\n }\n\n public synchronized List<ReportInfo> getReports(String context) {\n return reports.get(context);\n }\n\n public ReportAggregator getAggregator() {\n return aggregator;\n }\n\n private List<ReportInfo> getOrCreateInfos(String name) {\n List<ReportInfo> reportList = reports.get(name);\n if (reportList == null) {\n reportList = new ArrayList<>();\n reports.put(name, reportList);\n }\n return reportList;\n }\n\n public static class ReportInfo {\n private final RamlReport report;\n private final SavableServletRamlRequest request;\n private final SavableServletRamlResponse response;\n\n public ReportInfo(RamlReport report, ServletRamlRequest request, ServletRamlResponse response) {\n this.report = report;\n this.request = new SavableServletRamlRequest(request);\n this.response = new SavableServletRamlResponse(response);\n }\n\n public RamlReport getReport() {\n return report;\n }\n\n public ServletRamlRequest getRequest() {\n return request;\n }\n\n public ServletRamlResponse getResponse() {\n return response;\n }\n }\n\n private static class SavableServletRamlRequest extends ServletRamlRequest {\n private final StringBuffer requestURL;\n private final String queryString;\n private final Values headerValues;\n private final String method;\n\n public SavableServletRamlRequest(ServletRamlRequest delegate) {\n super(delegate);\n requestURL = delegate.getRequestURL();\n queryString = delegate.getQueryString();\n headerValues = delegate.getHeaderValues();\n method = delegate.getMethod();\n }\n\n @Override\n public StringBuffer getRequestURL() {\n return requestURL;\n }\n\n @Override\n public String getQueryString() {\n return queryString;\n }\n\n @Override\n public Values getHeaderValues() {\n return headerValues;\n }\n\n @Override\n public String getMethod() {\n return method;\n }\n }\n\n private static class SavableServletRamlResponse extends ServletRamlResponse {\n private final byte[] content;\n private final Values headerValues;\n\n public SavableServletRamlResponse(ServletRamlResponse delegate) {\n super(delegate);\n content = delegate.getContent();\n headerValues = delegate.getHeaderValues();\n }\n\n @Override\n public byte[] getContent() {\n return content;\n }\n\n @Override\n public Values getHeaderValues() {\n return headerValues;\n }\n }\n}", "public static class ReportInfo {\n private final RamlReport report;\n private final SavableServletRamlRequest request;\n private final SavableServletRamlResponse response;\n\n public ReportInfo(RamlReport report, ServletRamlRequest request, ServletRamlResponse response) {\n this.report = report;\n this.request = new SavableServletRamlRequest(request);\n this.response = new SavableServletRamlResponse(response);\n }\n\n public RamlReport getReport() {\n return report;\n }\n\n public ServletRamlRequest getRequest() {\n return request;\n }\n\n public ServletRamlResponse getResponse() {\n return response;\n }\n}", "public static String content(HttpResponse response) throws IOException {\n return EntityUtils.toString(response.getEntity());\n}" ]
import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.*; import guru.nidi.ramlproxy.core.RamlProxyServer; import guru.nidi.ramlproxy.core.ServerOptions; import guru.nidi.ramlproxy.report.ReportSaver; import guru.nidi.ramlproxy.report.ReportSaver.ReportInfo; import guru.nidi.ramltester.core.RamlReport; import guru.nidi.ramltester.core.RamlViolationMessage; import org.apache.http.HttpResponse; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.Iterator; import java.util.List; import static guru.nidi.ramlproxy.core.CommandSender.content;
/* * Copyright © 2014 Stefan Niederhauser ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package guru.nidi.ramlproxy; public class MockTest { private HttpSender sender = new HttpSender(8090); private RamlProxyServer proxy; @Before public void init() throws Exception { final ServerOptions options = new ServerOptions(sender.getPort(), Ramls.MOCK_DIR, Ramls.SIMPLE, "http://nidi.guru/raml", null, null, true); proxy = RamlProxy.startServerSync(options, new ReportSaver()); } @After public void stop() throws Exception { proxy.close(); } @Test public void simpleOk() throws Exception { final HttpResponse res = sender.get("v1/data"); Thread.sleep(20); assertEquals("42", content(res)); assertEquals(202, res.getStatusLine().getStatusCode()); assertEquals("get!", res.getFirstHeader("X-meta").getValue()); final RamlReport report = assertOneReport(); final Iterator<RamlViolationMessage> iter = report.getResponseViolations().iterator(); assertEquals("Response(202) is not defined on action(GET /data)", iter.next().getMessage()); assertTrue(report.getRequestViolations().isEmpty()); } @Test public void multipleFiles() throws Exception { final HttpResponse res = sender.get("v1/multi"); Thread.sleep(20); assertEquals(404, res.getStatusLine().getStatusCode()); final String content = content(res); assertThat(content, containsString("No or multiple file &apos;multi&apos; found in directory")); assertThat(content, containsString("src/test/resources/guru/nidi/ramlproxy/v1")); final RamlReport report = assertOneReport(); final Iterator<RamlViolationMessage> iter = report.getRequestViolations().iterator(); assertEquals("Resource '/multi' is not defined", iter.next().getMessage()); assertTrue(report.getResponseViolations().isEmpty()); } @Test public void noFile() throws Exception { final HttpResponse res = sender.get("v1/notExisting"); Thread.sleep(20); assertEquals(404, res.getStatusLine().getStatusCode()); final String content = content(res); assertThat(content, containsString("No or multiple file &apos;notExisting&apos; found in directory")); assertThat(content, containsString("src/test/resources/guru/nidi/ramlproxy/v1")); final RamlReport report = assertOneReport(); final Iterator<RamlViolationMessage> iter = report.getRequestViolations().iterator(); assertEquals("Resource '/notExisting' is not defined", iter.next().getMessage()); assertTrue(report.getResponseViolations().isEmpty()); } @Test public void withMethod() throws Exception { final HttpResponse res = sender.post("v1/data", null); Thread.sleep(20); assertEquals("666", content(res)); assertEquals(201, res.getStatusLine().getStatusCode()); assertEquals("yes!", res.getFirstHeader("X-meta").getValue()); assertEquals("5", res.getLastHeader("X-meta").getValue()); final RamlReport report = assertOneReport(); assertTrue(report.getRequestViolations().isEmpty()); assertTrue(report.getResponseViolations().isEmpty()); } @Test public void nested() throws Exception { final HttpResponse res = sender.post("v1/super/sub", null); Thread.sleep(20); assertEquals("163", content(res)); assertEquals("true", res.getFirstHeader("X-meta").getValue()); final RamlReport report = assertOneReport(); final Iterator<RamlViolationMessage> iter = report.getRequestViolations().iterator(); assertEquals("Action POST is not defined on resource(/super/sub)", iter.next().getMessage()); assertTrue(report.getResponseViolations().isEmpty()); } private RamlReport assertOneReport() {
final List<ReportInfo> reports = proxy.getSaver().getReports("simple");
3
idega/is.idega.idegaweb.egov.course
src/java/is/idega/idegaweb/egov/course/presentation/CourseList.java
[ "public class CourseConstants {\n\n\tpublic static final String CASE_CODE_KEY = \"COURSEA\";\n\n\tpublic static final String IW_BUNDLE_IDENTIFIER = \"is.idega.idegaweb.egov.course\";\n\n\tpublic static final String ADMINISTRATOR_ROLE_KEY = \"afterSchoolCareAdministrator\";\n\tpublic static final String SUPER_ADMINISTRATOR_ROLE_KEY = \"superAfterSchoolCareAdministrator\";\n\tpublic static final String COURSE_ACCOUNTING_ROLE_KEY = \"courseAccounting\";\n\n\tpublic static final int DAY_CARE_NONE = 0;\n\tpublic static final int DAY_CARE_PRE = 1;\n\tpublic static final int DAY_CARE_POST = 2;\n\tpublic static final int DAY_CARE_PRE_AND_POST = 3;\n\n\tpublic static final String PROPERTY_REGISTRATION_EMAIL = \"egov.course.registration.email\";\n\tpublic static final String PROPERTY_BCC_EMAIL = \"egov.course.bcc.email\";\n\tpublic static final String PROPERTY_REFUND_EMAIL = \"egov.course.refund.email\";\n\tpublic static final String PROPERTY_HIDDEN_SCHOOL_TYPE = \"egov.course.hidden.type\";\n\tpublic static final String PROPERTY_MERCHANT_PK = \"egov.course.merchant.pk\";\n\tpublic static final String PROPERTY_MERCHANT_TYPE = \"egov.course.merchant.type\";\n\tpublic static final String PROPERTY_INVALIDATE_INTERVAL = \"egov.course.invalidate.interval\";\n\tpublic static final String PROPERTY_USE_DWR = \"egov.course.use.dwr\";\n\tpublic static final String PROPERTY_USE_FIXED_PRICES = \"egov.course.use.fixed.prices\";\n\tpublic static final String PROPERTY_USE_BIRTHYEARS = \"egov.course.use.birthyears\";\n\tpublic static final String PROPERTY_ACCOUNTING_TYPE_PK = \"egov.course.accounting.type\";\n\tpublic static final String PROPERTY_SHOW_ID_IN_NAME = \"egov.course.show.id.in.name\";\n\tpublic static final String PROPERTY_SHOW_PROVIDER = \"egov.course.show.provider\";\n\tpublic static final String PROPERTY_INCEPTION_YEAR = \"egov.course.inception.year\";\n\tpublic static final String PROPERTY_SHOW_ALL_COURSES = \"egov.course.show.all.courses\";\n\tpublic static final String PROPERTY_SHOW_CERTIFICATES = \"egov.course.show.certificates\";\n\tpublic static final String PROPERTY_SHOW_NO_PAYMENT = \"egov.course.show.no.payment\";\n\tpublic static final String PROPERTY_BACK_MONTHS = \"egov.course.back.months\";\n\tpublic static final String PROPERTY_USE_WAITING_LIST = \"egov.course.use.waiting.list\";\n\tpublic static final String PROPERTY_USE_DIRECT_PAYMENT = \"egov.course.use.direct.payment\";\n\tpublic static final String PROPERTY_SEND_REMINDERS = \"egov.course.send.reminders\";\n\tpublic static final String PROPERTY_PUBLIC_HOLIDAYS = \"egov.course.public.holidays\";\n\tpublic static final String PROPERTY_MANUALLY_OPEN_COURSES = \"egov.course.manually.open\";\n\tpublic static final String PROPERTY_ACCEPT_URL = \"egov.course.accept.url\";\n\tpublic static final String PROPERTY_SHOW_CARE_OPTIONS = \"egov.course.show.care.options\";\n\tpublic static final String PROPERTY_SHOW_PROVIDER_INFORMATION = \"egov.course.show.provider.info\";\n\tpublic static final String PROPERTY_SHOW_PERSON_INFORMATION = \"egov.course.show.person.info\";\n\n\tpublic static final String PROPERTY_TIMEOUT_DAY_OF_WEEK = \"egov.course.timeout.day\";\n\tpublic static final String PROPERTY_TIMEOUT_HOUR = \"egov.course.timeout.hour\";\n\n\tpublic static final String APPLICATION_PROPERTY_COURSE_MAP = \"egov.course.map\";\n\n\tpublic static final String CARD_TYPE_EUROCARD = \"eurocard\";\n\tpublic static final String CARD_TYPE_VISA = \"visa\";\n\n\tpublic static final String PAYMENT_TYPE_CARD = \"credit_card\";\n\tpublic static final String PAYMENT_TYPE_GIRO = \"giro\";\n\tpublic static final String PAYMENT_TYPE_BANK_TRANSFER = \"bank_transfer\";\n\n\tpublic static final String PRODUCT_CODE_CARE = \"CARE\";\n\tpublic static final String PRODUCT_CODE_COURSE = \"COURSE\";\n\n\tpublic static final String DISCOUNT_SIBLING = \"sibling\";\n\tpublic static final String DISCOUNT_QUANTITY = \"quantity\";\n\tpublic static final String DISCOUNT_SPOUSE = \"spouse\";\n\n\tpublic static final String COURSE_PREFIX = \"course_\";\n\t\n\tpublic static final String DEFAULT_COURSE_CERTIFICATE_FEE = \"defaultCourseCertificateFee\";\n\n\tpublic static final String PROPERTY_TIMER_HOUR = \"egov.course.timer.hour\";\n\tpublic static final String PROPERTY_TIMER_DAYOFWEEK = \"egov.course.timer.dayofweek\";\n\tpublic static final String PROPERTY_TIMER_MINUTE = \"egov.course.timer.minute\";\n\n}", "public class CourseComparator implements Comparator {\n\n\tpublic static final int NAME_SORT = 1;\n\tpublic static final int REVERSE_NAME_SORT = 8;\n\tpublic static final int TYPE_SORT = 2;\n\tpublic static final int YEAR_SORT = 3;\n\tpublic static final int DATE_SORT = 4;\n\tpublic static final int PLACES_SORT = 5;\n\tpublic static final int FREE_PLACES_SORT = 6;\n\tpublic static final int ID_SORT = 7;\n\tpublic static final int REVERSE_ID_SORT = 9;\n\n\tprivate Locale locale;\n\tprivate int compareBy = NAME_SORT;\n\tprivate Collator collator;\n\n\tpublic CourseComparator(Locale locale, int compareBy) {\n\t\tthis.locale = locale;\n\t\tthis.compareBy = compareBy;\n\t}\n\n\tpublic int compare(Object arg0, Object arg1) {\n\t\tCourse course1 = (Course) arg0;\n\t\tCourse course2 = (Course) arg1;\n\t\tcollator = Collator.getInstance(locale);\n\n\t\tint returner = 0;\n\t\tswitch (this.compareBy) {\n\t\t\tcase ID_SORT:\n\t\t\t\treturner = idSort(course1, course2);\n\t\t\t\tbreak;\n\n\t\t\tcase REVERSE_ID_SORT:\n\t\t\t\treturner = -idSort(course1, course2);\n\t\t\t\tbreak;\n\t\t\t\t\n\t\t\tcase NAME_SORT:\n\t\t\t\treturner = nameSort(course1, course2);\n\t\t\t\tbreak;\n\n\t\t\tcase TYPE_SORT:\n\t\t\t\treturner = typeSort(course1, course2);\n\t\t\t\tbreak;\n\n\t\t\tcase YEAR_SORT:\n\t\t\t\treturner = yearSort(course1, course2);\n\t\t\t\tbreak;\n\n\t\t\tcase DATE_SORT:\n\t\t\t\treturner = dateSort(course1, course2);\n\t\t\t\tbreak;\n\n\t\t\tcase PLACES_SORT:\n\t\t\t\treturner = placesSort(course1, course2);\n\t\t\t\tbreak;\n\n\t\t\tcase FREE_PLACES_SORT:\n\t\t\t\treturner = freePlacesSort(course1, course2);\n\t\t\t\tbreak;\n\n\t\t\tcase REVERSE_NAME_SORT:\n\t\t\t\treturner = -nameSort(course1, course2);\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\treturner = nameSort(course1, course2);\n\t\t\t\tbreak;\n\t\t}\n\n\t\tif (returner == 0) {\n\t\t\treturner = compareBy == REVERSE_NAME_SORT ? -idSort(course1, course2) : idSort(course1, course2);\n\t\t}\n\n\t\treturn returner;\n\t}\n\n\tprivate int idSort(Course course1, Course course2) {\n\t\treturn course1.getCourseNumber() - course2.getCourseNumber();\n\t}\n\n\tprivate int nameSort(Course course1, Course course2) {\n\t\treturn collator.compare(course1.getName(), course2.getName());\n\t}\n\n\tprivate int typeSort(Course course1, Course course2) {\n\t\treturn collator.compare(course1.getCourseType().getName(), course2.getCourseType().getName());\n\t}\n\n\tprivate int yearSort(Course course1, Course course2) {\n\t\treturn course1.getBirthyearFrom() - course2.getBirthyearFrom();\n\t}\n\n\tprivate int dateSort(Course course1, Course course2) {\n\t\tIWTimestamp start1 = new IWTimestamp(course1.getStartDate());\n\t\tIWTimestamp start2 = new IWTimestamp(course2.getStartDate());\n\n\t\tif (start1.isEarlierThan(start2)) {\n\t\t\treturn -1;\n\t\t}\n\t\telse if (start2.isEarlierThan(start1)) {\n\t\t\treturn 1;\n\t\t}\n\t\treturn 0;\n\t}\n\n\tprivate int placesSort(Course course1, Course course2) {\n\t\treturn -(course1.getMax() - course2.getMax());\n\t}\n\n\tprivate int freePlacesSort(Course course1, Course course2) {\n\t\treturn -(course1.getFreePlaces() - course2.getFreePlaces());\n\t}\n}", "public class CourseWriter extends DownloadWriter implements MediaWritable {\n\n\tprivate MemoryFileBuffer buffer = null;\n\tprivate CourseBusiness business;\n\tprivate Locale locale;\n\tprivate IWResourceBundle iwrb;\n\n\tprivate String schoolTypeName;\n\n\tpublic final static String PARAMETER_PROVIDER_ID = \"provider_id\";\n\tpublic final static String PARAMETER_GROUP_ID = \"group_id\";\n\tpublic final static String PARAMETER_SHOW_NOT_YET_ACTIVE = \"show_not_yet_active\";\n\n\tpublic CourseWriter() {\n\t}\n\n\t@Override\n\tpublic void init(HttpServletRequest req, IWContext iwc) {\n\t\ttry {\n\t\t\tthis.locale = iwc.getApplicationSettings().getApplicationLocale();\n\t\t\tthis.business = getCourseBusiness(iwc);\n\t\t\tthis.iwrb = iwc.getIWMainApplication().getBundle(CourseConstants.IW_BUNDLE_IDENTIFIER).getResourceBundle(this.locale);\n\n\t\t\tif (getCourseSession(iwc).getProvider() != null && iwc.isParameterSet(CourseBlock.PARAMETER_SCHOOL_TYPE_PK)) {\n\t\t\t\tSchoolType type = getSchoolBusiness(iwc).getSchoolType(iwc.getParameter(CourseBlock.PARAMETER_SCHOOL_TYPE_PK));\n\t\t\t\tschoolTypeName = type.getSchoolTypeName();\n\n\t\t\t\tDate fromDate = iwc.isParameterSet(CourseBlock.PARAMETER_FROM_DATE) ? new IWTimestamp(iwc.getParameter(CourseBlock.PARAMETER_FROM_DATE)).getDate() : null;\n\t\t\t\tDate toDate = iwc.isParameterSet(CourseBlock.PARAMETER_TO_DATE) ? new IWTimestamp(iwc.getParameter(CourseBlock.PARAMETER_TO_DATE)).getDate() : null;\n\n\t\t\t\tCollection courses = business.getCourses(-1, getCourseSession(iwc).getProvider().getPrimaryKey(), iwc.getParameter(CourseBlock.PARAMETER_SCHOOL_TYPE_PK), iwc.getParameter(CourseBlock.PARAMETER_COURSE_TYPE_PK), fromDate, toDate);\n\n\t\t\t\tthis.buffer = writeXLS(iwc, courses);\n\t\t\t\tsetAsDownload(iwc, \"students.xls\", this.buffer.length());\n\n\t\t\t}\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t@Override\n\tpublic String getMimeType() {\n\t\tif (this.buffer != null) {\n\t\t\treturn this.buffer.getMimeType();\n\t\t}\n\t\treturn super.getMimeType();\n\t}\n\n\t@Override\n\tpublic void writeTo(OutputStream out) throws IOException {\n\t\tif (this.buffer != null) {\n\t\t\tMemoryInputStream mis = new MemoryInputStream(this.buffer);\n\t\t\tByteArrayOutputStream baos = new ByteArrayOutputStream();\n\t\t\twhile (mis.available() > 0) {\n\t\t\t\tbaos.write(mis.read());\n\t\t\t}\n\t\t\tbaos.writeTo(out);\n\t\t}\n\t\telse {\n\t\t\tSystem.err.println(\"buffer is null\");\n\t\t}\n\t}\n\n\tpublic MemoryFileBuffer writeXLS(IWContext iwc, Collection courses) throws Exception {\n\t\tMemoryFileBuffer buffer = new MemoryFileBuffer();\n\t\tMemoryOutputStream mos = new MemoryOutputStream(buffer);\n\t\tif (!courses.isEmpty()) {\n\t\t\tHSSFWorkbook wb = new HSSFWorkbook();\n\t\t\tHSSFSheet sheet = wb.createSheet(StringHandler.shortenToLength(this.schoolTypeName, 30));\n\t\t\tsheet.setColumnWidth((short) 0, (short) (24 * 256));\n\t\t\tsheet.setColumnWidth((short) 1, (short) (24 * 256));\n\t\t\tsheet.setColumnWidth((short) 2, (short) (8 * 256));\n\t\t\tsheet.setColumnWidth((short) 3, (short) (8 * 256));\n\t\t\tsheet.setColumnWidth((short) 4, (short) (12 * 256));\n\t\t\tsheet.setColumnWidth((short) 5, (short) (12 * 256));\n\t\t\tsheet.setColumnWidth((short) 6, (short) (8 * 256));\n\t\t\tsheet.setColumnWidth((short) 7, (short) (8 * 256));\n\t\t\tsheet.setColumnWidth((short) 8, (short) (20 * 256));\n\t\t\tHSSFFont font = wb.createFont();\n\t\t\tfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);\n\t\t\tfont.setFontHeightInPoints((short) 12);\n\t\t\tHSSFCellStyle style = wb.createCellStyle();\n\t\t\tstyle.setFont(font);\n\n\t\t\tHSSFFont bigFont = wb.createFont();\n\t\t\tbigFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);\n\t\t\tbigFont.setFontHeightInPoints((short) 13);\n\t\t\tHSSFCellStyle bigStyle = wb.createCellStyle();\n\t\t\tbigStyle.setFont(bigFont);\n\n\t\t\tint cellRow = 0;\n\t\t\tHSSFRow row = sheet.createRow(cellRow++);\n\t\t\tHSSFCell cell = row.createCell((short) 0);\n\t\t\tcell.setCellValue(this.schoolTypeName);\n\t\t\tcell.setCellStyle(bigStyle);\n\t\t\tcell = row.createCell((short) 1);\n\n\t\t\trow = sheet.createRow(cellRow++);\n\n\t\t\tshort iCell = 0;\n\t\t\trow = sheet.createRow(cellRow++);\n\t\t\tcell = row.createCell(iCell++);\n\t\t\tcell.setCellValue(this.iwrb.getLocalizedString(\"type\", \"Type\"));\n\t\t\tcell.setCellStyle(style);\n\t\t\tcell = row.createCell(iCell++);\n\t\t\tcell.setCellValue(this.iwrb.getLocalizedString(\"course\", \"Course\"));\n\t\t\tcell.setCellStyle(style);\n\t\t\tcell = row.createCell(iCell++);\n\t\t\tcell.setCellValue(this.iwrb.getLocalizedString(\"from\", \"From\"));\n\t\t\tcell.setCellStyle(style);\n\t\t\tcell = row.createCell(iCell++);\n\t\t\tcell.setCellValue(this.iwrb.getLocalizedString(\"to\", \"To\"));\n\t\t\tcell.setCellStyle(style);\n\t\t\tcell = row.createCell(iCell++);\n\t\t\tcell.setCellValue(this.iwrb.getLocalizedString(\"date_from\", \"Date from\"));\n\t\t\tcell.setCellStyle(style);\n\t\t\tcell = row.createCell(iCell++);\n\t\t\tcell.setCellValue(this.iwrb.getLocalizedString(\"date_to\", \"Date to\"));\n\t\t\tcell.setCellStyle(style);\n\t\t\tcell = row.createCell(iCell++);\n\t\t\tcell.setCellValue(this.iwrb.getLocalizedString(\"max\", \"Max\"));\n\t\t\tcell.setCellStyle(style);\n\t\t\tcell = row.createCell(iCell++);\n\t\t\tcell.setCellValue(this.iwrb.getLocalizedString(\"free_places\", \"Free places\"));\n\t\t\tcell.setCellStyle(style);\n\t\t\tcell = row.createCell(iCell++);\n\t\t\tcell.setCellValue(this.iwrb.getLocalizedString(\"employee\", \"Employee\"));\n\t\t\tcell.setCellStyle(style);\n\n\t\t\tIterator iter = courses.iterator();\n\t\t\twhile (iter.hasNext()) {\n\t\t\t\trow = sheet.createRow(cellRow++);\n\t\t\t\tiCell = 0;\n\n\t\t\t\tCourse course = (Course) iter.next();\n\t\t\t\tCourseType type = course.getCourseType();\n\t\t\t\tCoursePrice price = course.getPrice();\n\t\t\t\tIWTimestamp dateFrom = new IWTimestamp(course.getStartDate());\n\t\t\t\tIWTimestamp dateTo = new IWTimestamp(course.getStartDate());\n\t\t\t\tdateTo.addDays(price.getNumberOfDays());\n\n\t\t\t\trow.createCell(iCell++).setCellValue(type.getName());\n\t\t\t\trow.createCell(iCell++).setCellValue(course.getName());\n\t\t\t\trow.createCell(iCell++).setCellValue(String.valueOf(course.getBirthyearFrom()));\n\t\t\t\trow.createCell(iCell++).setCellValue(String.valueOf(course.getBirthyearTo()));\n\t\t\t\trow.createCell(iCell++).setCellValue(dateFrom.getLocaleDate(iwc.getCurrentLocale(), IWTimestamp.SHORT));\n\t\t\t\trow.createCell(iCell++).setCellValue(dateTo.getLocaleDate(iwc.getCurrentLocale(), IWTimestamp.SHORT));\n\t\t\t\trow.createCell(iCell++).setCellValue(String.valueOf(course.getMax()));\n\t\t\t\trow.createCell(iCell++).setCellValue(String.valueOf(business.getNumberOfFreePlaces(course)));\n\t\t\t\trow.createCell(iCell++).setCellValue(\"-\");\n\t\t\t}\n\t\t\twb.write(mos);\n\t\t}\n\t\tbuffer.setMimeType(MimeTypeUtil.MIME_TYPE_EXCEL_2);\n\t\treturn buffer;\n\t}\n\n\tprivate CourseBusiness getCourseBusiness(IWApplicationContext iwc) throws RemoteException {\n\t\treturn (CourseBusiness) IBOLookup.getServiceInstance(iwc, CourseBusiness.class);\n\t}\n\n\tprivate CourseSession getCourseSession(IWUserContext iwc) throws RemoteException {\n\t\treturn (CourseSession) IBOLookup.getSessionInstance(iwc, CourseSession.class);\n\t}\n\n\tprivate SchoolBusiness getSchoolBusiness(IWApplicationContext iwc) throws RemoteException {\n\t\treturn (SchoolBusiness) IBOLookup.getServiceInstance(iwc, SchoolBusiness.class);\n\t}\n}", "public interface Course extends IDOEntity {\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getName\n\t */\n\tpublic String getName();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getUser\n\t */\n\tpublic String getUser();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getDescription\n\t */\n\tpublic String getDescription();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getProvider\n\t */\n\tpublic School getProvider();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getCourseType\n\t */\n\tpublic CourseType getCourseType();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getPrice\n\t */\n\tpublic CoursePrice getPrice();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getCoursePrice\n\t */\n\tpublic float getCoursePrice();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getCourseCost\n\t */\n\tpublic float getCourseCost();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getAccountingKey\n\t */\n\tpublic String getAccountingKey();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getStartDate\n\t */\n\tpublic Timestamp getStartDate();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getEndDate\n\t */\n\tpublic Timestamp getEndDate();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getRegistrationEnd\n\t */\n\tpublic Timestamp getRegistrationEnd();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getBirthyearFrom\n\t */\n\tpublic int getBirthyearFrom();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getBirthyearTo\n\t */\n\tpublic int getBirthyearTo();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getMax\n\t */\n\tpublic int getMax();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getFreePlaces\n\t */\n\tpublic int getFreePlaces();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getFreePlaces\n\t */\n\tpublic int getFreePlaces(boolean countOffers);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#getCourseNumber\n\t */\n\tpublic int getCourseNumber();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#isOpenForRegistration\n\t */\n\tpublic boolean isOpenForRegistration();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#hasPreCare\n\t */\n\tpublic boolean hasPreCare();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#hasPostCare\n\t */\n\tpublic boolean hasPostCare();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#hasPreAndPostCarehasPreAndPostCare\n\t */\n\tpublic boolean hasPreAndPostCare();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setName\n\t */\n\tpublic void setName(String name);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setUser\n\t */\n\tpublic void setUser(String user);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setDescription\n\t */\n\tpublic void setDescription(String description);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setProvider\n\t */\n\tpublic void setProvider(School provider);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setCourseType\n\t */\n\tpublic void setCourseType(CourseType courseType);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setPrice\n\t */\n\tpublic void setPrice(CoursePrice price);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setCoursePrice\n\t */\n\tpublic void setCoursePrice(float price);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setCourseCost\n\t */\n\tpublic void setCourseCost(float cost);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setAccountingKey\n\t */\n\tpublic void setAccountingKey(String key);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setStartDate\n\t */\n\tpublic void setStartDate(Timestamp startDate);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setEndDate\n\t */\n\tpublic void setEndDate(Timestamp endDate);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setRegistrationEnd\n\t */\n\tpublic void setRegistrationEnd(Timestamp registrationEnd);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setBirthyearFrom\n\t */\n\tpublic void setBirthyearFrom(int from);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setBirthyearTo\n\t */\n\tpublic void setBirthyearTo(int to);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setMax\n\t */\n\tpublic void setMax(int max);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setCourseNumber\n\t */\n\tpublic void setCourseNumber(int number);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setOpenForRegistration\n\t */\n\tpublic void setOpenForRegistration(boolean openForRegistration);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setHasPreCare\n\t */\n\tpublic void setHasPreCare(boolean hasPreCare);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseBMPBean#setHasPostCare\n\t */\n\tpublic void setHasPostCare(boolean hasPostCare);\n\n\tpublic void setRentableItems(Collection<? extends RentableItem> items) throws IDOAddRelationshipException;\n\tpublic Collection<? extends RentableItem> getRentableItems(Class<? extends RentableItem> itemClass);\n\tpublic void addRentableItem(RentableItem item) throws IDOAddRelationshipException;\n\tpublic void removeRentableItem(RentableItem item) throws IDORemoveRelationshipException;\n\tpublic void removeAllRentableItems(Class<? extends RentableItem> itemClass) throws IDORemoveRelationshipException;\n\n\tpublic void addPrice(CoursePrice price) throws IDOAddRelationshipException;\n\tpublic Collection<CoursePrice> getAllPrices();\n\tpublic void removePrice(CoursePrice price) throws IDORemoveRelationshipException;\n\tpublic void removeAllPrices() throws IDORemoveRelationshipException;\n\n\tpublic void addSeason(SchoolSeason season) throws IDOAddRelationshipException;\n\tpublic Collection<SchoolSeason> getSeasons();\n\tpublic void removeSeason(SchoolSeason season) throws IDORemoveRelationshipException;\n\tpublic void removeAllSeasons() throws IDORemoveRelationshipException;\n\n}", "public interface CourseCategory extends IDOEntity, SchoolType {\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseCategoryBMPBean#allowsAllChildren\n\t */\n\tpublic boolean allowsAllChildren();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseCategoryBMPBean#hasCare\n\t */\n\tpublic boolean hasCare();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseCategoryBMPBean#useFixedPricing\n\t */\n\tpublic boolean useFixedPricing();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseCategoryBMPBean#sendReminderEmail\n\t */\n\tpublic boolean sendReminderEmail();\n\t\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseCategoryBMPBean#setAllowsAllChildren\n\t */\n\tpublic void setAllowsAllChildren(boolean allowAll);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseCategoryBMPBean#setHasCare\n\t */\n\tpublic void setHasCare(boolean hasCare);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseCategoryBMPBean#setUseFixedPricing\n\t */\n\tpublic void setUseFixedPricing(boolean useFixedPricing);\n\t\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseCategoryBMPBean#setSendReminderEmail\n\t */\n\tpublic void setSendReminderEmail(boolean sendReminderEmail);\n}", "public interface CoursePrice extends IDOEntity {\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getName\n\t */\n\tpublic String getName();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getSchoolArea\n\t */\n\tpublic SchoolArea getSchoolArea();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getCourseType\n\t */\n\tpublic CourseType getCourseType();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getValidFrom\n\t */\n\tpublic Timestamp getValidFrom();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getValidTo\n\t */\n\tpublic Timestamp getValidTo();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getNumberOfDays\n\t */\n\tpublic int getNumberOfDays();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getPrice\n\t */\n\tpublic int getPrice();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getPreCarePrice\n\t */\n\tpublic int getPreCarePrice();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#getPostCarePrice\n\t */\n\tpublic int getPostCarePrice();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setName\n\t */\n\tpublic void setName(String name);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setSchoolArea\n\t */\n\tpublic void setSchoolArea(SchoolArea area);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setCourseType\n\t */\n\tpublic void setCourseType(CourseType type);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setValidFrom\n\t */\n\tpublic void setValidFrom(Timestamp stamp);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setValidTo\n\t */\n\tpublic void setValidTo(Timestamp stamp);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setValid\n\t */\n\tpublic void setValid(boolean valid);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setNumberOfDays\n\t */\n\tpublic void setNumberOfDays(int noDays);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setPrice\n\t */\n\tpublic void setPrice(int price);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setPreCarePrice\n\t */\n\tpublic void setPreCarePrice(int price);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CoursePriceBMPBean#setPostCarePrice\n\t */\n\tpublic void setPostCarePrice(int price);\n\n\tpublic SchoolType getSchoolType();\n\tpublic void setSchoolType(SchoolType schoolType);\n\n\tpublic SchoolSeason getSchoolSeason();\n\tpublic void setSchoolSeason(SchoolSeason season);\n}", "public interface CourseType extends IDOEntity {\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseTypeBMPBean#getName\n\t */\n\tpublic String getName();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseTypeBMPBean#getDescription\n\t */\n\tpublic String getDescription();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseTypeBMPBean#getLocalizationKey\n\t */\n\tpublic String getLocalizationKey();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseTypeBMPBean#getCourseCategory\n\t */\n\tpublic CourseCategory getCourseCategory();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseTypeBMPBean#getAccountingKey\n\t */\n\tpublic String getAccountingKey();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseTypeBMPBean#getAbbreviation\n\t */\n\tpublic String getAbbreviation();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseTypeBMPBean#getOrder\n\t */\n\tpublic int getOrder();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseTypeBMPBean#showAbbreviation\n\t */\n\tpublic boolean showAbbreviation();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseTypeBMPBean#isDisabled\n\t */\n\tpublic boolean isDisabled();\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseTypeBMPBean#setName\n\t */\n\tpublic void setName(String name);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseTypeBMPBean#setDescription\n\t */\n\tpublic void setDescription(String description);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseTypeBMPBean#setLocalizationKey\n\t */\n\tpublic void setLocalizationKey(String localizationKey);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseTypeBMPBean#setCourseCategory\n\t */\n\tpublic void setCourseCategory(CourseCategory category);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseTypeBMPBean#setAccountingKey\n\t */\n\tpublic void setAccountingKey(String key);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseTypeBMPBean#setAbbreviation\n\t */\n\tpublic void setAbbreviation(String abbreviation);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseTypeBMPBean#setOrder\n\t */\n\tpublic void setOrder(int order);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseTypeBMPBean#setShowAbbreviation\n\t */\n\tpublic void setShowAbbreviation(boolean showAbbreviation);\n\n\t/**\n\t * @see is.idega.idegaweb.egov.course.data.CourseTypeBMPBean#setDisabled\n\t */\n\tpublic void setDisabled(boolean disabled);\n}" ]
import is.idega.idegaweb.egov.course.CourseConstants; import is.idega.idegaweb.egov.course.business.CourseComparator; import is.idega.idegaweb.egov.course.business.CourseWriter; import is.idega.idegaweb.egov.course.data.Course; import is.idega.idegaweb.egov.course.data.CourseCategory; import is.idega.idegaweb.egov.course.data.CoursePrice; import is.idega.idegaweb.egov.course.data.CourseType; import java.rmi.RemoteException; import java.sql.Date; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import com.idega.block.school.data.School; import com.idega.block.school.data.SchoolType; import com.idega.business.IBORuntimeException; import com.idega.presentation.IWContext; import com.idega.presentation.Layer; import com.idega.presentation.Table2; import com.idega.presentation.TableCell2; import com.idega.presentation.TableRow; import com.idega.presentation.TableRowGroup; import com.idega.presentation.text.DownloadLink; import com.idega.presentation.text.Link; import com.idega.presentation.text.Text; import com.idega.presentation.ui.DropdownMenu; import com.idega.presentation.ui.Form; import com.idega.presentation.ui.GenericButton; import com.idega.presentation.ui.HiddenInput; import com.idega.presentation.ui.IWDatePicker; import com.idega.presentation.ui.Label; import com.idega.presentation.ui.SubmitButton; import com.idega.presentation.ui.handlers.IWDatePickerHandler; import com.idega.util.IWTimestamp; import com.idega.util.PresentationUtil;
else if (type != null) { Collection courseTypes = getBusiness().getCourseTypes(new Integer(type.getPrimaryKey().toString()), true); courseType.addMenuElements(courseTypes); } boolean useBirthYears = iwc.getApplicationSettings().getBoolean(CourseConstants.PROPERTY_USE_BIRTHYEARS, true); int inceptionYear = Integer.parseInt(iwc.getApplicationSettings().getProperty(CourseConstants.PROPERTY_INCEPTION_YEAR, "-1")); DropdownMenu sorting = new DropdownMenu(PARAMETER_SORTING); sorting.addMenuElement(CourseComparator.ID_SORT, getResourceBundle().getLocalizedString("sort.id", "ID")); sorting.addMenuElement(CourseComparator.REVERSE_ID_SORT, getResourceBundle().getLocalizedString("sort.reverse_id", "reverse ID")); sorting.addMenuElement(CourseComparator.NAME_SORT, getResourceBundle().getLocalizedString("sort.name", "Name (A-Z)")); sorting.addMenuElement(CourseComparator.REVERSE_NAME_SORT, getResourceBundle().getLocalizedString("sort.reverse_name", "Name (Z-A)")); sorting.addMenuElement(CourseComparator.TYPE_SORT, getResourceBundle().getLocalizedString("sort.type", "Type")); sorting.addMenuElement(CourseComparator.DATE_SORT, getResourceBundle().getLocalizedString("sort.date", "Date")); if (useBirthYears) { sorting.addMenuElement(CourseComparator.YEAR_SORT, getResourceBundle().getLocalizedString("sort.year", "Year")); } sorting.addMenuElement(CourseComparator.PLACES_SORT, getResourceBundle().getLocalizedString("sort.places", "Places")); sorting.addMenuElement(CourseComparator.FREE_PLACES_SORT, getResourceBundle().getLocalizedString("sort.free_places", "Free places")); sorting.keepStatusOnAction(true); IWTimestamp stamp = new IWTimestamp(); stamp.addYears(1); IWDatePicker fromDate = new IWDatePicker(PARAMETER_FROM_DATE); fromDate.setShowYearChange(true); fromDate.setStyleClass("dateInput"); fromDate.keepStatusOnAction(true); IWDatePicker toDate = new IWDatePicker(PARAMETER_TO_DATE); toDate.setShowYearChange(true); toDate.setStyleClass("dateInput"); toDate.keepStatusOnAction(true); toDate.setDate(stamp.getDate()); if (inceptionYear > 0) { IWTimestamp fromStamp = new IWTimestamp(1, 1, inceptionYear); fromDate.setDate(fromStamp.getDate()); } else { stamp.addMonths(-1); stamp.addYears(-1); fromDate.setDate(stamp.getDate()); } if (showTypes) { Layer formItem = new Layer(Layer.DIV); formItem.setStyleClass("formItem"); Label label = new Label(getResourceBundle().getLocalizedString("category", "Category"), schoolType); formItem.add(label); formItem.add(schoolType); layer.add(formItem); } else if (type != null) { layer.add(new HiddenInput(PARAMETER_SCHOOL_TYPE_PK, type.getPrimaryKey().toString())); } Layer formItem = new Layer(Layer.DIV); formItem.setStyleClass("formItem"); Label label = new Label(getResourceBundle().getLocalizedString("type", "Type"), courseType); formItem.add(label); formItem.add(courseType); layer.add(formItem); formItem = new Layer(Layer.DIV); formItem.setStyleClass("formItem"); label = new Label(); label.setLabel(getResourceBundle().getLocalizedString("from", "From")); formItem.add(label); formItem.add(fromDate); layer.add(formItem); formItem = new Layer(Layer.DIV); formItem.setStyleClass("formItem"); label = new Label(); label.setLabel(getResourceBundle().getLocalizedString("to", "To")); formItem.add(label); formItem.add(toDate); layer.add(formItem); formItem = new Layer(Layer.DIV); formItem.setStyleClass("formItem"); label = new Label(getResourceBundle().getLocalizedString("sorting", "Sorting"), sorting); formItem.add(label); formItem.add(sorting); layer.add(formItem); SubmitButton fetch = new SubmitButton(getResourceBundle().getLocalizedString("get", "Get")); fetch.setStyleClass("indentedButton"); fetch.setStyleClass("button"); formItem = new Layer(Layer.DIV); formItem.setStyleClass("formItem"); formItem.add(fetch); layer.add(formItem); Layer clearLayer = new Layer(Layer.DIV); clearLayer.setStyleClass("Clear"); layer.add(clearLayer); return layer; } public Layer getPrintouts(IWContext iwc) { Layer layer = new Layer(Layer.DIV); layer.setStyleClass("printIcons"); layer.add(getXLSLink(iwc)); return layer; } protected Link getXLSLink(IWContext iwc) { DownloadLink link = new DownloadLink(getBundle().getImage("xls.gif")); link.setStyleClass("xls"); link.setTarget(Link.TARGET_NEW_WINDOW); link.maintainParameter(PARAMETER_SCHOOL_TYPE_PK, iwc); link.maintainParameter(PARAMETER_COURSE_TYPE_PK, iwc); link.maintainParameter(PARAMETER_FROM_DATE, iwc); link.maintainParameter(PARAMETER_TO_DATE, iwc);
link.setMediaWriterClass(CourseWriter.class);
2
gjhutchison/pixelhorrorjam2016
core/src/com/kowaisugoi/game/player/Player.java
[ "public class PlacementRectangle extends Rectangle {\n public void draw(ShapeRenderer renderer) {\n renderer.setColor(0.9f, 0.9f, 0.9f, 0.5f);\n renderer.rect(x, y, width, height);\n }\n\n public String getCoordString() {\n float xS = x;\n float yS = y;\n float wS = width;\n float hS = height;\n\n // Ensure rectangles are reported with lower-left origin\n if (wS < 0) {\n xS += wS;\n wS = -wS;\n }\n\n if (hS < 0) {\n yS += hS;\n hS = -hS;\n }\n\n String coordString = \"(\";\n coordString += Math.round(xS) + \",\";\n coordString += Math.round(yS) + \",\";\n coordString += Math.round(wS) + \",\";\n coordString += Math.round(hS) + \")\";\n return coordString;\n }\n}", "public class PlayerInventory implements Disposable {\n\n private static final float OFFSET_X = 5f;\n private static final float OFFSET_Y = 5f;\n\n private static final String INVENTORY_SPRITE_URL = \"ui/inventory.png\";\n private static final String INVENTORY_BUTTON_SPRITE_URL = \"ui/inventory_button.png\";\n private static final String INVENTORY_BUTTON_CLOSED_URL = \"ui/inventory_button_close.png\";\n\n private List<InventorySlot> _inventorySlots;\n private Sprite _inventorySprite;\n private Sprite _buttonOpenSprite;\n private Sprite _buttonCloseSprite;\n\n private boolean _inventoryOpen;\n\n private InventorySlot _selectedSlot;\n\n public PlayerInventory() {\n _inventorySlots = new ArrayList<InventorySlot>();\n _inventorySprite = setupSprite();\n\n _buttonOpenSprite = setupButtonOpenSprite();\n _buttonCloseSprite = setupButtonCloseSprite();\n\n _inventoryOpen = false;\n }\n\n public void toggleInventory() {\n _inventoryOpen = !_inventoryOpen;\n\n if (_inventoryOpen) {\n positionSprites();\n }\n }\n\n private void positionSprites() {\n for (int i = 0; i < _inventorySlots.size(); i++) {\n InventorySlot slot = _inventorySlots.get(i);\n\n float x = 19 + (47 * (i - (3 * (i / 3))));\n float y = 47 - (37 * (i / 3));\n\n Sprite sprite = _inventorySlots.get(i).getItem().getInventorySprite();\n sprite.setSize(32, 32);\n sprite.setPosition(x, y);\n\n slot.setInteractionBox(new Rectangle(x, y, 32, 32));\n\n }\n }\n\n private Sprite setupSprite() {\n Sprite sprite = new Sprite(new Texture(INVENTORY_SPRITE_URL));\n sprite.setSize(GAME_WIDTH, GAME_HEIGHT);\n sprite.setPosition(0, 0);\n\n return sprite;\n }\n\n private Sprite setupButtonOpenSprite() {\n Sprite sprite = new Sprite(new Texture(INVENTORY_BUTTON_SPRITE_URL));\n sprite.setSize(8, 8);\n sprite.setPosition(GAME_WIDTH - 8, GAME_HEIGHT - 8);\n\n return sprite;\n }\n\n private Sprite setupButtonCloseSprite() {\n Sprite sprite = new Sprite(new Texture(INVENTORY_BUTTON_CLOSED_URL));\n sprite.setSize(8, 8);\n sprite.setPosition(GAME_WIDTH - 8, GAME_HEIGHT - 8);\n\n return sprite;\n }\n\n public Rectangle getButtonBox() {\n return new Rectangle(_buttonOpenSprite.getX(),\n _buttonOpenSprite.getY(),\n _buttonOpenSprite.getWidth(),\n _buttonOpenSprite.getHeight());\n }\n\n public void drawInventory(SpriteBatch batch) {\n if (!_inventoryOpen || PlayGame.getPlayer().getInteractionMode() != Player.InteractionMode.INVENTORY) {\n _buttonOpenSprite.draw(batch);\n return;\n }\n _buttonCloseSprite.draw(batch);\n _inventorySprite.draw(batch);\n drawItems(batch);\n }\n\n public void drawItems(SpriteBatch batch) {\n for (InventorySlot slot : _inventorySlots) {\n slot.getItem().getInventorySprite().draw(batch);\n }\n }\n\n public void addItem(PickupableItem item) {\n _inventorySlots.add(new InventorySlot(item));\n }\n\n public boolean isInventoryOpen() {\n return _inventoryOpen;\n }\n\n public boolean click(float curX, float curY) {\n for (InventorySlot slot : _inventorySlots) {\n if (slot.interact(curX, curY)) {\n _selectedSlot = slot;\n _inventoryOpen = false;\n return true;\n }\n }\n return false;\n }\n\n public void drawSelectedItemSprite(SpriteBatch batch) {\n Sprite sprite = _selectedSlot.getItem().getInventorySprite();\n sprite.draw(batch);\n }\n\n public void moveSelectedItemSprite(float curX, float curY) {\n Sprite sprite = _selectedSlot.getItem().getInventorySprite();\n sprite.setSize(16, 16);\n\n float xLocation = curX - OFFSET_X;\n float yLocation = curY - OFFSET_Y;\n\n sprite.setPosition(xLocation, yLocation);\n }\n\n public ItemId getSelectedItemId() {\n return _selectedSlot.getItem().getItemId();\n }\n\n public void removeItem(ItemId id) {\n for (int i = 0; i < _inventorySlots.size(); i++) {\n InventorySlot slot = _inventorySlots.get(i);\n if (slot.getItem().getItemId() == id) {\n _inventorySlots.remove(i);\n return;\n }\n }\n }\n\n @Override\n public void dispose() {\n _inventorySprite.getTexture().dispose();\n _buttonOpenSprite.getTexture().dispose();\n _buttonCloseSprite.getTexture().dispose();\n }\n}", "public class ThoughtBox implements Disposable {\n private float _holdDuration = 0;\n private float _displayedFor;\n private float _fadeInDuration;\n private float _fadeOutDuration;\n private float _opacity;\n private GlyphLayout _layout;\n private String _text;\n private BitmapFont _thoughtFont;\n private float THOUGHT_X = 0;\n private float THOUGHT_Y = 0;\n private float THOUGHT_WIDTH = PlayGame.GAME_WIDTH;\n private float THOUGHT_HEIGHT = 10;\n private Color _color = new Color(1f, 1f, 1f, 1f);\n private float OPACITY_MAX = 0.8f;\n \n public ThoughtBox(String text, float holdDuration) {\n _holdDuration = holdDuration;\n _fadeOutDuration = 1.1f;\n _fadeInDuration = 0.5f;\n\n // TODO: Move this somewhere universal\n FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal(\"font/raleway/Raleway-Medium.ttf\"));\n FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();\n parameter.size = 32;\n\n _thoughtFont = generator.generateFont(parameter);\n _thoughtFont.getData().setScale(0.12f, 0.12f);\n _text = text;\n _layout = new GlyphLayout();\n }\n\n public void update(float delta) {\n _displayedFor += delta;\n\n if (_displayedFor < _fadeInDuration) {\n _opacity = ((_displayedFor) / _fadeInDuration) * OPACITY_MAX;\n } else if (_displayedFor < _fadeInDuration + _holdDuration) {\n _opacity = OPACITY_MAX;\n } else {\n _opacity = (1.0f - (_displayedFor - _fadeInDuration - _holdDuration) / _fadeOutDuration) * OPACITY_MAX;\n }\n\n // Just in case\n if (_opacity < 0) {\n _opacity = 0;\n } else if (_opacity > OPACITY_MAX) {\n _opacity = OPACITY_MAX;\n }\n }\n\n public void draw(SpriteBatch batch) {\n float x_pos = (THOUGHT_X + THOUGHT_WIDTH) / 2;\n float y_pos = (THOUGHT_Y + THOUGHT_HEIGHT) / 2;\n\n _color.set(_color.r, _color.g, _color.b, _opacity);\n _thoughtFont.setColor(_color);\n _layout.setText(_thoughtFont, _text);\n x_pos -= _layout.width / 2;\n y_pos += _layout.height / 2;\n\n _thoughtFont.draw(batch, _layout, x_pos, y_pos);\n }\n\n public void draw(ShapeRenderer renderer) {\n renderer.setColor(0.05f, 0.05f, 0.05f, _opacity);\n renderer.rect(THOUGHT_X, THOUGHT_Y, THOUGHT_WIDTH, THOUGHT_HEIGHT);\n }\n\n @Override\n public void dispose() {\n _thoughtFont.dispose();\n }\n}", "public interface Room extends Disposable {\n public void drawFx(SpriteBatch batch);\n\n public void draw(SpriteBatch batch);\n\n public void draw(ShapeRenderer batch);\n\n public boolean click(float curX, float curY);\n\n public boolean click(float curX, float curY, ItemId itemId);\n\n public void beautifyCursor(float curX, float curY);\n\n public void update(float delta);\n\n public void enter();\n\n public void pushEnterRemark(String textId);\n\n public void flagUpdate();\n}", "public enum RoomId {\n MAIN_HALL,\n HALLWAY,\n FRONT_DOOR_INTERIOR,\n BEDROOM,\n BATHROOM,\n BATHROOM_CABINET,\n BACKYARD,\n CRAWLSPACE,\n FRONTYARD,\n KITCHEN,\n SHED,\n SHED_INTERIOR,\n SHRINE,\n ROAD,\n PARKING_AREA,\n CAR\n}", "public final class RoomManager {\n private HashMap<RoomId, Room> _roomMap = new HashMap<RoomId, Room>();\n\n public RoomManager() {\n _roomMap.put(RoomId.MAIN_HALL, new RoomMainHall());\n _roomMap.put(RoomId.HALLWAY, new RoomHallway());\n _roomMap.put(RoomId.FRONTYARD, new RoomFrontYard());\n _roomMap.put(RoomId.CAR, new RoomCar());\n _roomMap.put(RoomId.ROAD, new RoomForestPath());\n _roomMap.put(RoomId.BEDROOM, new RoomBedroom());\n _roomMap.put(RoomId.BATHROOM, new RoomBathroomEntrance());\n _roomMap.put(RoomId.KITCHEN, new RoomKitchen());\n _roomMap.put(RoomId.CRAWLSPACE, new RoomCrawlspace());\n _roomMap.put(RoomId.PARKING_AREA, new RoomCarPark());\n _roomMap.put(RoomId.SHED, new RoomShed());\n _roomMap.put(RoomId.SHED_INTERIOR, new RoomShedInterior());\n _roomMap.put(RoomId.BATHROOM_CABINET, new RoomBathroomCabinet());\n }\n\n public Room getRoomFromId(RoomId roomId) {\n return _roomMap.get(roomId);\n }\n\n public void flagUpdate() {\n for (RoomId id : _roomMap.keySet()) {\n _roomMap.get(id).flagUpdate();\n }\n }\n\n // Clean up all rooms, theoretically on closing the game\n public void cleanUp() {\n for (Room room : _roomMap.values()) {\n room.dispose();\n }\n }\n}", "public class PlayGame implements Screen {\n // 640x360\n public static final float GAME_WIDTH = 160;\n public static final float GAME_HEIGHT = 90;\n\n private OrthographicCamera _camera;\n private Viewport _viewport;\n private SpriteBatch _batch;\n private ShapeRenderer _shapeRenderer;\n private static boolean _debug = false;\n private static boolean _placing = false;\n private static Transition _transition;\n\n // Global state\n private static Player _player;\n private static RoomManager _roomManager;\n private static FlagManager _flagManager;\n private static boolean _paused;\n\n public static Player getPlayer() {\n return _player;\n }\n\n public static RoomManager getRoomManager() {\n return _roomManager;\n }\n\n public static FlagManager getFlagManager() {\n return _flagManager;\n }\n\n @Override\n public void show() {\n _roomManager = new RoomManager();\n _flagManager = new FlagManager();\n\n SlideTransition.setTransitionSpeed(SlideTransition.DEFAULT_SPEED);\n\n PlayerInventory inventory = new PlayerInventory();\n\n _batch = new SpriteBatch();\n _shapeRenderer = new ShapeRenderer();\n _camera = new OrthographicCamera();\n _camera.translate(GAME_WIDTH / 2, GAME_HEIGHT / 2);\n _viewport = new StretchViewport(GAME_WIDTH, GAME_HEIGHT, _camera);\n\n _player = new Player(this, inventory);\n _player.startGame(RoomId.CAR);\n\n Gdx.input.setInputProcessor(_player);\n }\n\n public static void setPaused(boolean paused) {\n _paused = paused;\n }\n\n public static boolean getPaused() {\n return _paused;\n }\n\n public void renderPauseDialog() {\n // Fade to black\n Gdx.gl.glEnable(GL20.GL_BLEND);\n Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);\n _shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);\n _shapeRenderer.setColor(0.05f, 0.05f, 0.05f, 0.5f);\n _shapeRenderer.rect(0, 0, GAME_WIDTH, GAME_HEIGHT);\n _shapeRenderer.end();\n Gdx.gl.glDisable(GL20.GL_BLEND);\n\n _batch.begin();\n // TODO: Factor this out (at the very least)\n FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal(\"font/raleway/Raleway-Medium.ttf\"));\n FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();\n parameter.size = 32;\n BitmapFont bfont = generator.generateFont(parameter);\n GlyphLayout layout = new GlyphLayout();\n bfont.getData().setScale(0.12f, 0.12f);\n\n float x_pos = GAME_WIDTH / 2;\n float y_pos = 20 / 2;\n\n bfont.setColor(1.0f, 1.0f, 1.0f, 0.5f);\n\n layout.setText(bfont, Messages.getText(\"system.exit\"));\n\n x_pos -= layout.width / 2;\n y_pos += layout.height / 2;\n\n bfont.draw(_batch, layout, x_pos, y_pos);\n _batch.end();\n }\n\n @Override\n public void render(float delta) {\n _camera.update();\n _batch.setProjectionMatrix(_camera.combined);\n _shapeRenderer.setProjectionMatrix(_camera.combined);\n\n if (_paused) {\n renderPauseDialog();\n return;\n }\n\n updateGame(delta);\n renderGame();\n }\n\n private void updateGame(float delta) {\n Vector3 position = screenToWorldPosition(Gdx.input.getX(), Gdx.input.getY());\n getPlayer().updateCursor(position);\n getPlayer().update(delta);\n\n if (_transition != null) {\n _transition.update(delta);\n }\n }\n\n private void renderCurrentRoom() {\n Gdx.gl.glClearColor(1, 0, 0, 1);\n Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);\n Gdx.gl.glEnable(GL20.GL_BLEND);\n Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);\n\n // Draw room sprites\n _batch.begin();\n getPlayer().getCurrentRoom().draw(_batch);\n _batch.end();\n Gdx.gl.glDisable(GL20.GL_BLEND);\n\n // Draw room shapes\n Gdx.gl.glEnable(GL20.GL_BLEND);\n Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);\n _shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);\n getPlayer().getCurrentRoom().draw(_shapeRenderer);\n _shapeRenderer.end();\n Gdx.gl.glDisable(GL20.GL_BLEND);\n }\n\n private void renderFX() {\n // Draw room FX\n Gdx.gl.glEnable(GL20.GL_BLEND);\n Gdx.gl.glBlendFunc(GL20.GL_DST_COLOR, GL20.GL_ONE);\n _batch.begin();\n getPlayer().getCurrentRoom().drawFx(_batch);\n _batch.end();\n Gdx.gl.glDisable(GL20.GL_BLEND);\n }\n\n private void renderInventory() {\n Gdx.gl.glEnable(GL20.GL_BLEND);\n Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);\n\n // Draw inventory bag\n _batch.begin();\n getPlayer().getInventory().drawInventory(_batch);\n _batch.end();\n Gdx.gl.glDisable(GL20.GL_BLEND);\n }\n\n private void renderSelectedItem() {\n _batch.begin();\n getPlayer().getInventory().drawSelectedItemSprite(_batch);\n _batch.end();\n }\n\n private void renderTransitions() {\n // Draw transitions, if applicable\n if (_transition == null) {\n return;\n }\n\n Gdx.gl.glEnable(GL20.GL_BLEND);\n Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);\n _shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);\n _transition.draw(_shapeRenderer);\n _shapeRenderer.end();\n _batch.begin();\n _transition.draw(_batch);\n _batch.end();\n Gdx.gl.glDisable(GL20.GL_BLEND);\n }\n\n private void renderHUD() {\n // Draw player thoughts over everything\n Gdx.gl.glEnable(GL20.GL_BLEND);\n Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);\n _shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);\n getPlayer().getThought().draw(_shapeRenderer);\n _shapeRenderer.end();\n _batch.begin();\n getPlayer().getThought().draw(_batch);\n _batch.end();\n Gdx.gl.glDisable(GL20.GL_BLEND);\n }\n\n private void renderPlacementHelper() {\n Gdx.gl.glEnable(GL20.GL_BLEND);\n Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);\n _shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);\n _player.getPlacementRectangle().draw(_shapeRenderer);\n _shapeRenderer.end();\n Gdx.gl.glDisable(GL20.GL_BLEND);\n }\n\n /**\n * Breaks down rendering of game world into different layers\n */\n private void renderGame() {\n renderCurrentRoom();\n renderFX();\n renderInventory();\n renderPlacementHelper();\n\n // Draw inventory, if applicable\n if (getPlayer().getInteractionMode() == ITEM_INTERACTION) {\n renderSelectedItem();\n }\n\n renderTransitions();\n renderHUD();\n }\n\n @Override\n public void resize(int width, int height) {\n _viewport.update(width, height);\n }\n\n @Override\n public void pause() {\n // TODO Auto-generated method stub\n\n }\n\n @Override\n public void resume() {\n // TODO Auto-generated method stub\n\n }\n\n @Override\n public void hide() {\n // TODO Auto-generated method stub\n }\n\n @Override\n public void dispose() {\n }\n\n public Vector3 screenToWorldPosition(int screenX, int screenY) {\n Vector3 vecCursorPos = new Vector3(screenX, screenY, 0);\n _camera.unproject(vecCursorPos);\n return vecCursorPos;\n }\n\n /**\n * Play transition animation on transition layer\n *\n * @param t The transition animation to play\n */\n public static void playTransition(Transition t) {\n _transition = t;\n _transition.play();\n }\n\n public static void setDebug(boolean debug) {\n _debug = debug;\n }\n\n public static boolean getDebug() {\n return _debug;\n }\n\n public static void setPlacementMode(boolean mode) {\n _player.think(\"Placement mode: \" + (mode ? \"ON\" : \"OFF\"));\n _placing = mode;\n }\n\n public static boolean getPlacementMode() {\n return _placing;\n }\n}", "public final class GlobalKeyHandler {\n static final int FULLSCREEN_KEY = Input.Keys.F4;\n static final int DEBUG_KEY = Input.Keys.F8;\n static final int PLACEMENT_HELPER = Input.Keys.F9;\n static final int EXIT_KEY = Input.Keys.ESCAPE;\n static final int YES_KEY = Input.Keys.Y;\n static final int NO_KEY = Input.Keys.N;\n static final int SHED_INTERIOR_KEY = Input.Keys.S;\n static final int TORCH_KEY = Input.Keys.T;\n static final int CABINET_KEY = Input.Keys.C;\n static final int ENDGAME_KEY = Input.Keys.E;\n static final int CREDITS_KEY = Input.Keys.X;\n\n public static boolean keyUp(int keycode) {\n if (keycode == FULLSCREEN_KEY) {\n if (!Gdx.graphics.isFullscreen()) {\n Gdx.graphics.setDisplayMode(\n Gdx.graphics.getDesktopDisplayMode().width,\n Gdx.graphics.getDesktopDisplayMode().height,\n true);\n } else {\n Gdx.graphics.setDisplayMode(\n 800,\n 450,\n false);\n }\n return true;\n }\n\n if (keycode == EXIT_KEY) {\n if (PlayGame.getPaused()) {\n PlayGame.setPaused(false);\n } else {\n PlayGame.setPaused(true);\n }\n }\n\n if (keycode == YES_KEY) {\n if (PlayGame.getPaused()) {\n Gdx.app.exit();\n }\n }\n\n if (keycode == NO_KEY) {\n if (PlayGame.getPaused()) {\n PlayGame.setPaused(false);\n }\n }\n\n if (keycode == DEBUG_KEY) {\n if (PlayGame.getDebug()) {\n PlayGame.setDebug(false);\n } else {\n //PlayGame.setDebug(true);\n }\n }\n\n if (keycode == ENDGAME_KEY) {\n if (PlayGame.getDebug()) {\n PlayGame.getFlagManager().setFlag(FlagId.FLAG_BODY_FOUND, true);\n PlayGame.getFlagManager().setFlag(FlagId.FLAG_KEYS_MISSING, true);\n PlayGame.getFlagManager().setFlag(FlagId.FLAG_BOARDS_REMOVED, true);\n PlayGame.getFlagManager().setFlag(FlagId.FLAG_CAR_FOUND, true);\n PlayGame.getFlagManager().setFlag(FlagId.FLAG_CAR_SNOWREMOVED, true);\n PlayGame.getFlagManager().setFlag(FlagId.FLAG_NIGHT_TIME, true);\n PlayGame.getFlagManager().setFlag(FlagId.FLAG_SHED_OPENED, true);\n PlayGame.getFlagManager().setFlag(FlagId.FLAG_ENTERED_BATHROOM, true);\n PlayGame.getFlagManager().setFlag(FlagId.FLAG_TORCH_PLACED, true);\n }\n }\n\n if (keycode == CREDITS_KEY) {\n if (PlayGame.getDebug()) {\n PlayGame.getFlagManager().setFlag(FlagId.FLAG_BODY_FOUND, true);\n PlayGame.getFlagManager().setFlag(FlagId.FLAG_KEYS_MISSING, true);\n PlayGame.getFlagManager().setFlag(FlagId.FLAG_BOARDS_REMOVED, true);\n PlayGame.getFlagManager().setFlag(FlagId.FLAG_CAR_FOUND, true);\n PlayGame.getFlagManager().setFlag(FlagId.FLAG_CAR_SNOWREMOVED, true);\n PlayGame.getFlagManager().setFlag(FlagId.FLAG_NIGHT_TIME, true);\n PlayGame.getFlagManager().setFlag(FlagId.FLAG_SHED_OPENED, true);\n PlayGame.getFlagManager().setFlag(FlagId.FLAG_ENTERED_BATHROOM, true);\n PlayGame.getFlagManager().setFlag(FlagId.FLAG_TORCH_PLACED, true);\n PlayGame.getFlagManager().setFlag(FlagId.FLAG_KEYS_APPEARED, true);\n PlayGame.getFlagManager().setFlag(FlagId.FLAG_KEYS_FOUND, true);\n }\n }\n\n if (keycode == PLACEMENT_HELPER) {\n if (PlayGame.getDebug()) {\n if (!PlayGame.getPlacementMode()) {\n PlayGame.setPlacementMode(true);\n } else {\n PlayGame.setPlacementMode(false);\n }\n }\n }\n\n if (keycode == SHED_INTERIOR_KEY) {\n if (PlayGame.getDebug()) {\n PickupableItem glassWater = new PickupableItem(new Sprite(new Texture(\"items/glass_water.png\")),\n new Rectangle(0, 0, 0, 0),\n ItemId.GLASS_WATER);\n PlayGame.getPlayer().getInventory().addItem(glassWater);\n PlayGame.getPlayer().enterRoom(RoomId.SHED_INTERIOR);\n }\n }\n\n if (keycode == CABINET_KEY) {\n if (PlayGame.getDebug()) {\n PlayGame.getPlayer().enterRoom(RoomId.BATHROOM_CABINET);\n }\n }\n\n if (keycode == TORCH_KEY) {\n PickupableItem torch = new PickupableItem(new Sprite(new Texture(\"items/stickicon_fire.png\")),\n new Rectangle(0, 0, 0, 0),\n ItemId.TORCH);\n if (PlayGame.getDebug()) {\n PlayGame.getPlayer().getInventory().addItem(torch);\n }\n\n }\n\n return false;\n }\n}", "public enum InteractionMode {\n NORMAL,\n INVENTORY,\n ITEM_INTERACTION,\n NONE\n}" ]
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.InputProcessor; import com.badlogic.gdx.graphics.Cursor; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Disposable; import com.kowaisugoi.game.graphics.PlacementRectangle; import com.kowaisugoi.game.player.inventory.PlayerInventory; import com.kowaisugoi.game.player.thought.ThoughtBox; import com.kowaisugoi.game.rooms.Room; import com.kowaisugoi.game.rooms.RoomId; import com.kowaisugoi.game.rooms.RoomManager; import com.kowaisugoi.game.screens.PlayGame; import com.kowaisugoi.game.system.GlobalKeyHandler; import static com.kowaisugoi.game.player.Player.InteractionMode.*;
package com.kowaisugoi.game.player; public final class Player implements Disposable, InputProcessor { private PlayGame _world; private RoomId _currentRoom; // TODO: could/should separate this from Player private RoomManager _manager; private PlayerInventory _inventory; private static PlacementRectangle _placement = new PlacementRectangle(); private CursorType _cursorFlavor = CursorType.REGULAR; private CursorType _currentCursorFlavor = null;
private InteractionMode _interactionMode = InteractionMode.NORMAL;
8
MX-Futhark/hook-any-text
src/main/java/hexcapture/HexOptions.java
[ "public abstract class Options {\n\n\t// used to format usage message\n\tprivate static final int INDENT_LENGTH = 4;\n\tprivate static final int DESC_LINE_LENGTH = 80 - INDENT_LENGTH;\n\n\tpublic static final String SERIALIAZATION_FILENAME = \"config.data\";\n\n\tprotected interface SerializingFallback<T> {\n\t\tCharset read(ObjectInputStream in) throws IOException;\n\t\tvoid write(Object t, ObjectOutputStream out) throws IOException;\n\t}\n\n\tpublic static final SerializingFallback<Charset> CHARSET_IO =\n\t\tnew SerializingFallback<Charset>() {\n\n\t\t@Override\n\t\tpublic Charset read(ObjectInputStream in) throws IOException {\n\t\t\treturn Charsets.getValidCharset(in.readUTF());\n\t\t}\n\n\t\t@Override\n\t\tpublic void write(Object t, ObjectOutputStream out)\n\t\t\tthrows IOException {\n\n\t\t\tout.writeUTF(((Charset) t).name());\n\t\t}\n\t};\n\n\t/**\n\t * Defines how to use command line options.\n\t *\n\t * @param message\n\t * \t\t\tThe reason why the usage message is printed. May be null.\n\t * @return The usage message.\n\t */\n\tpublic static String usage(String message, Set<Options> subOptions) {\n\t\tStringBuilder usage = new StringBuilder();\n\t\tif(message != null && !message.isEmpty()) {\n\t\t\tusage.append(message);\n\t\t\tusage.append(\"\\n\\nPlease use the following options:\\n\\n\");\n\t\t}\n\t\ttry {\n\t\t\tusage.append(generateUsageMessage(subOptions));\n\t\t} catch (IllegalArgumentException | IllegalAccessException\n\t\t\t| NoSuchFieldException | SecurityException\n\t\t\t| NoSuchMethodException e) {\n\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\treturn usage.toString();\n\t}\n\n\tprivate static String generateUsageMessage(Set<Options> subOptions)\n\t\tthrows IllegalArgumentException, IllegalAccessException,\n\t\tNoSuchFieldException, SecurityException, NoSuchMethodException {\n\n\t\tStringBuilder usage = new StringBuilder();\n\n\t\tCollection<Options> sortedOptions =\n\t\t\tGenericSort.apply(subOptions, null);\n\t\tfor (Options opt : sortedOptions) {\n\t\t\tCollection<Field> sortedFields = GenericSort.apply(\n\t\t\t\tReflectionUtils.getAnnotatedFields(\n\t\t\t\t\topt.getClass(),\n\t\t\t\t\tCommandLineArgument.class\n\t\t\t\t),\n\t\t\t\tnull\n\t\t\t);\n\t\t\tfor (Field argField : sortedFields) {\n\t\t\t\tCommandLineArgument argInfo =\n\t\t\t\t\targField.getAnnotation(CommandLineArgument.class);\n\t\t\t\tusage.append(getCmdUsage(opt, argField, argInfo));\n\t\t\t\tusage.append(\"\\n\" + getCmdDescription(argInfo));\n\t\t\t\tif (!argInfo.usageExample().isEmpty()) {\n\t\t\t\t\tusage.append(\"\\n\" + getCmdExample(argInfo));\n\t\t\t\t}\n\t\t\t\tusage.append(\"\\n\" + getCmdValueTable(opt, argField));\n\t\t\t\tusage.append(\"\\n\\n\");\n\t\t\t}\n\t\t}\n\n\t\tusage.append(getHelpCmdUsage());\n\n\t\treturn usage.toString();\n\t}\n\n\tprivate static String getCmdDescription(CommandLineArgument argInfo) {\n\t\treturn StringUtils.indent(\n\t\t\tStringUtils.breakText(\n\t\t\t\targInfo.description(),\n\t\t\t\tDESC_LINE_LENGTH\n\t\t\t), \" \", INDENT_LENGTH\n\t\t);\n\t}\n\n\tprivate static String getCmdExample(CommandLineArgument argInfo) {\n\t\treturn StringUtils.indent(\n\t\t\t\"example: \" + argInfo.usageExample(), \" \", INDENT_LENGTH\n\t\t);\n\t}\n\n\tprivate static String getCmdUsage(Options opt, Field argField,\n\t\tCommandLineArgument argInfo) throws NoSuchMethodException,\n\t\tSecurityException, IllegalArgumentException, IllegalAccessException,\n\t\tNoSuchFieldException {\n\n\t\tStringBuilder usage = new StringBuilder();\n\n\t\tusage.append(\"--\" + argInfo.command() + \"=\");\n\t\tif (!argInfo.usage().isEmpty()) {\n\t\t\tusage.append(argInfo.usage());\n\t\t\treturn usage.toString();\n\t\t}\n\n\t\tif (argInfo.flags()) {\n\t\t\tusage.append(\" combination of \");\n\t\t}\n\n\t\tDomain<?> argDomain = null;\n\t\ttry {\n\t\t\targDomain = opt.generateArgumentValueDomain(argField);\n\t\t\tif (argDomain == null) {\n\t\t\t\targDomain = opt.getFieldDomain(argField);\n\t\t\t}\n\t\t} catch (NoSuchFieldException e) {}\n\t\tCollection<Field> valFields = opt.getValueFields(argField);\n\n\t\tif (argDomain != null) {\n\t\t\tusage.append(argDomain);\n\t\t} else {\n\t\t\tusage.append(\"<\" + argField.getType().getSimpleName() + \">\");\n\t\t}\n\n\t\tObject argDefault = opt.getFieldDefaultValue(argField);\n\t\tif (argDefault != null) {\n\t\t\tusage.append(\", default=\");\n\t\t\tif (argInfo.flags()) {\n\t\t\t\tString flagsStr = DebuggingFlags.longToCmdFlags(\n\t\t\t\t\t(Long) opt.getFieldDefaultValue(argField)\n\t\t\t\t);\n\t\t\t\tusage.append(flagsStr.isEmpty() ? \"none\" : flagsStr);\n\t\t\t} else if (valFields == null) {\n\t\t\t\tusage.append(argDefault);\n\t\t\t} else {\n\t\t\t\tusage.append(\n\t\t\t\t\tgetDefaultValueString(argDefault, valFields)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\treturn usage.toString();\n\t}\n\n\tprivate static String getCmdValueTable(Options opt, Field argField)\n\t\tthrows NoSuchMethodException, SecurityException,\n\t\tIllegalArgumentException, IllegalAccessException {\n\n\t\tCollection<CommandLineValue> valDescs;\n\t\ttry {\n\t\t\tvalDescs = opt.getValuesDescriptions(\n\t\t\t\topt.getFieldValueClass(argField)\n\t\t\t);\n\t\t\treturn StringUtils.indent(\n\t\t\t\tgenerateValueTable(valDescs),\n\t\t\t\t\" \",\n\t\t\t\tINDENT_LENGTH\n\t\t\t);\n\t\t} catch (NoSuchFieldException e) {}\n\n\t\treturn \"\";\n\t}\n\n\tprivate static String getDefaultValueString(Object defaultValue,\n\t\tCollection<Field> valFields) throws IllegalArgumentException,\n\t\tIllegalAccessException {\n\n\t\tfor (Field valField : valFields) {\n\t\t\tif (valField.get(null).toString().equals(defaultValue.toString())) {\n\t\t\t\treturn valField.getAnnotation(CommandLineValue.class).value();\n\t\t\t}\n\t\t}\n\t\treturn defaultValue.toString();\n\t}\n\n\tprivate static String getHelpCmdUsage() {\n\t\treturn \"--help (cannot be used with other options)\\n\"\n\t\t\t+ StringUtils.indent(\"Displays this message.\", \" \", INDENT_LENGTH);\n\t}\n\n\t/**\n\t * Getter on the possible values of a configurable member.\n\t *\n\t * @param argField\n\t * \t\t\tThe configurable member.\n\t * @return The possible values of the configurable member.\n\t * @throws IllegalArgumentException\n\t * @throws IllegalAccessException\n\t * @throws SecurityException\n\t */\n\tpublic Collection<Field> getValueFields(Field argField)\n\t\tthrows IllegalArgumentException, IllegalAccessException,\n\t\tSecurityException {\n\n\t\tClass<?> argValsClass = null;\n\t\tCollection<Field> valFields;\n\t\ttry {\n\t\t\targValsClass = getFieldValueClass(argField);\n\t\t\tvalFields = ReflectionUtils.getAnnotatedFields(\n\t\t\t\targValsClass,\n\t\t\t\tCommandLineValue.class\n\t\t\t);\n\t\t} catch (NoSuchFieldException e) {\n\t\t\tvalFields = null;\n\t\t}\n\t\treturn valFields;\n\t}\n\n\tprivate Collection<CommandLineValue> getValuesDescriptions(\n\t\tClass<?> valueClass) throws NoSuchMethodException,\n\t\tSecurityException {\n\n\t\treturn valueClass == null\n\t\t\t? null\n\t\t\t: GenericSort.apply(\n\t\t\t\tReflectionUtils.getAnnotations(\n\t\t\t\t\tvalueClass,\n\t\t\t\t\tCommandLineValue.class\n\t\t\t\t),\n\t\t\t\tCommandLineValue.class.getMethod(\"value\")\n\t\t\t);\n\t}\n\n\t/**\n\t * Maps the command line string values to their actual value.\n\t *\n\t * @param argField\n\t * \t\t\tA configurable member with a restricted number of values.\n\t * @return A map of the command line string values to their actual value.\n\t * @throws NoSuchMethodException\n\t * @throws SecurityException\n\t * @throws IllegalArgumentException\n\t * @throws IllegalAccessException\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic <T> Map<String, T> getValueDomainToActualValue(Field argField)\n\t\tthrows NoSuchMethodException, SecurityException,\n\t\tIllegalArgumentException, IllegalAccessException {\n\n\t\tCollection<Field> valFields = getValueFields(argField);\n\t\tif (valFields == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tMap<String, T> res = new HashMap<>();\n\n\t\tfor (Field valField : valFields) {\n\t\t\tCommandLineValue valDesc =\n\t\t\t\tvalField.getAnnotation(CommandLineValue.class);\n\t\t\tString key = valDesc.value().isEmpty()\n\t\t\t\t? valField.get(null).toString()\n\t\t\t\t: valDesc.value();\n\t\t\tres.put(key, (T) valField.get(null));\n\t\t}\n\n\t\treturn res;\n\t}\n\n\tprivate Values<String> generateArgumentValueDomain(Field argField)\n\t\tthrows NoSuchMethodException, SecurityException,\n\t\tIllegalArgumentException, IllegalAccessException {\n\n\t\tMap<String, Object> valuesMap = getValueDomainToActualValue(argField);\n\t\tif (valuesMap == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn new Values<String>(\n\t\t\tvaluesMap.keySet().toArray(new String[valuesMap.keySet().size()])\n\t\t);\n\t}\n\n\tprivate static String generateValueTable(\n\t\tCollection<CommandLineValue> valuesDesc) {\n\n\t\tfinal String VALUE = \"value\";\n\t\tfinal String DESCRIPTION = \"description\";\n\t\tfinal String SHORTCUT = \"shortcut\";\n\t\tfinal String CONDITION = \"condition\";\n\n\t\tfinal String COLUMN_SEPARATOR = \" \";\n\t\tfinal String HEADER_SEPARATOR = \"-\";\n\n\t\tMap<Integer, String> headers = new TreeMap<>();\n\t\theaders.put(0, VALUE);\n\t\tMap<String, Map<String, String>> content = new TreeMap<>();\n\t\tfor (CommandLineValue desc : valuesDesc) {\n\t\t\tMap<String, String> lineContent = new HashMap<>();\n\t\t\tlineContent.put(DESCRIPTION, desc.description());\n\t\t\theaders.put(2, DESCRIPTION);\n\t\t\tif (desc.shortcut().length() > 0) {\n\t\t\t\tlineContent.put(SHORTCUT, \"-\" + desc.shortcut());\n\t\t\t\theaders.put(1, SHORTCUT);\n\t\t\t}\n\t\t\tif (desc.condition().length() > 0) {\n\t\t\t\tlineContent.put(CONDITION, desc.condition());\n\t\t\t\theaders.put(3, CONDITION);\n\t\t\t}\n\t\t\tcontent.put(desc.value(), lineContent);\n\t\t}\n\n\t\tStringBuilder table = new StringBuilder();\n\t\tint[] widths = new int[headers.size()];\n\t\tArrays.fill(widths, 30);\n\t\twidths[0] = 10;\n\t\tif (headers.containsValue(SHORTCUT)) {\n\t\t\twidths[1] = 10;\n\t\t}\n\n\t\tint eltCounter = 0;\n\t\tfor (String title : headers.values()) {\n\t\t\ttable.append(\n\t\t\t\tStringUtils.fillWithSpaces(title, widths[eltCounter++])\n\t\t\t);\n\t\t\ttable.append(COLUMN_SEPARATOR);\n\t\t}\n\t\ttable.append(\"\\n\");\n\t\teltCounter = 0;\n\t\tfor (String title : headers.values()) {\n\t\t\ttable.append(\n\t\t\t\tStringUtils.fillWithSpaces(\n\t\t\t\t\ttitle.replaceAll(\".\", HEADER_SEPARATOR),\n\t\t\t\t\twidths[eltCounter++]\n\t\t\t\t)\n\t\t\t);\n\t\t\ttable.append(COLUMN_SEPARATOR);\n\t\t}\n\t\ttable.append(\"\\n\");\n\t\theaders.remove(0);\n\t\tfor (String value : content.keySet()) {\n\t\t\tString[] paragraphs = new String[headers.values().size() + 1];\n\t\t\tparagraphs[0] = value;\n\t\t\tint columnIndex = 1;\n\t\t\tfor (String title : headers.values()) {\n\t\t\t\tparagraphs[columnIndex++] = content.get(value).get(title);\n\t\t\t}\n\t\t\ttable.append(\n\t\t\t\tStringUtils.putParagraphsSideBySide(\n\t\t\t\t\tparagraphs,\n\t\t\t\t\twidths,\n\t\t\t\t\tCOLUMN_SEPARATOR\n\t\t\t\t)\n\t\t\t);\n\t\t}\n\n\t\treturn table.toString();\n\t}\n\n\t/**\n\t * Getter on the default value of a configurable member.\n\t *\n\t * @param argField\n\t * \t\t\tThe configurable member.\n\t * @return The default value of the configurable member.\n\t * @throws IllegalArgumentException\n\t * @throws IllegalAccessException\n\t * @throws NoSuchFieldException\n\t * @throws SecurityException\n\t */\n\tpublic Object getFieldDefaultValue(Field argField)\n\t\tthrows IllegalArgumentException, IllegalAccessException,\n\t\tNoSuchFieldException, SecurityException {\n\n\t\treturn getFieldAssociatedInformation(\"DEFAULT_\", argField, \"\");\n\t}\n\n\t/**\n\t * Getter on the value domain of a configurable member.\n\t *\n\t * @param @param argField\n\t * \t\t\tThe configurable member.\n\t * @return The value domain of the configurable member.\n\t * @throws IllegalArgumentException\n\t * @throws IllegalAccessException\n\t * @throws NoSuchFieldException\n\t * @throws SecurityException\n\t */\n\tpublic Domain<?> getFieldDomain(Field argField)\n\t\tthrows IllegalArgumentException, IllegalAccessException,\n\t\tNoSuchFieldException, SecurityException {\n\n\t\treturn (Domain<?>)\n\t\t\tgetFieldAssociatedInformation(\"\", argField, \"_DOMAIN\");\n\t}\n\n\t/**\n\t * Getter on the value class of a configurable member.\n\t *\n\t * @param argField\n\t * \t\t\tThe configurable member.\n\t * @return The value class of the configurable member.\n\t * @throws IllegalArgumentException\n\t * @throws IllegalAccessException\n\t * @throws NoSuchFieldException\n\t * @throws SecurityException\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic Class<? extends ValueClass> getFieldValueClass(Field argField)\n\t\tthrows IllegalArgumentException, IllegalAccessException,\n\t\tNoSuchFieldException, SecurityException {\n\n\t\treturn (Class<? extends ValueClass>)\n\t\t\tgetFieldAssociatedInformation(\"\", argField, \"_VALUE_CLASS\");\n\t}\n\n\t/**\n\t * Getter on the value class of a configurable member.\n\t *\n\t * @param argField\n\t * \t\t\tThe configurable member.\n\t * @return\n\t * @throws IllegalArgumentException\n\t * @throws IllegalAccessException\n\t * @throws NoSuchFieldException\n\t * @throws SecurityException\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic Class<? extends ArgumentParser<?>> getFieldParser(Field argField)\n\t\tthrows IllegalArgumentException, IllegalAccessException,\n\t\tNoSuchFieldException, SecurityException {\n\n\t\treturn (Class<? extends ArgumentParser<?>>)\n\t\t\tgetFieldAssociatedInformation(\"\", argField, \"_PARSER\");\n\t}\n\n\tprivate Object getFieldAssociatedInformation(String prefix,\n\t\tField argField, String suffix) throws IllegalArgumentException,\n\t\tIllegalAccessException, NoSuchFieldException, SecurityException {\n\n\t\tField f = getClass().getDeclaredField(\n\t\t\tprefix\n\t\t\t\t+ StringUtils.camelToScreamingSnake(argField.getName())\n\t\t\t\t+ suffix\n\t\t);\n\t\tf.setAccessible(true);\n\t\treturn f.get(this);\n\t}\n\n\tprotected synchronized void serialize(ObjectOutputStream out)\n\t\tthrows IOException {\n\n\t\tout.defaultWriteObject();\n\t\ttry {\n\t\t\tMap<Field, SerializingFallback<?>> fallbacks =\n\t\t\t\tgetSerializingFallbacks();\n\t\t\tfor (Field f : fallbacks.keySet()) {\n\t\t\t\tfallbacks.get(f).write(f.get(this), out);\n\t\t\t}\n\t\t} catch (IllegalArgumentException | IllegalAccessException\n\t\t\t| NoSuchFieldException | SecurityException e) {\n\n\t\t\tthrow new IOException(e);\n\t\t}\n\t}\n\n\tprotected synchronized void deserialize(ObjectInputStream in)\n\t\tthrows IOException, ClassNotFoundException {\n\n\t\tin.defaultReadObject();\n\t\ttry {\n\t\t\tMap<Field, SerializingFallback<?>> fallbacks =\n\t\t\t\tgetSerializingFallbacks();\n\t\t\tfor (Field f : fallbacks.keySet()) {\n\t\t\t\tf.set(this, fallbacks.get(f).read(in));\n\t\t\t}\n\t\t} catch (IllegalArgumentException | IllegalAccessException\n\t\t\t| NoSuchFieldException | SecurityException e) {\n\n\t\t\tthrow new IOException(e);\n\t\t}\n\t}\n\n\tprotected Map<Field, SerializingFallback<?>> getSerializingFallbacks()\n\t\tthrows IllegalArgumentException, IllegalAccessException,\n\t\tNoSuchFieldException, SecurityException {\n\n\t\tList<Field> nonSerializableFields = ReflectionUtils.getModifiedFields(\n\t\t\tthis.getClass(),\n\t\t\tModifier.TRANSIENT\n\t\t);\n\t\tMap<Field, SerializingFallback<?>> fallbacks = new HashMap<>();\n\t\tfor (Field f : nonSerializableFields) {\n\t\t\tf.setAccessible(true);\n\t\t\tString fallbackName = StringUtils.camelToScreamingSnake(\n\t\t\t\tf.getType().getSimpleName()\n\t\t\t) + \"_IO\";\n\t\t\tfallbacks.put(\n\t\t\t\tf,\n\t\t\t\t(SerializingFallback<?>) Options.class.getField(fallbackName)\n\t\t\t\t\t.get(this)\n\t\t\t);\n\t\t}\n\t\treturn fallbacks;\n\t}\n\n}", "public interface ValueClass {}", "public class Bounds<T extends Comparable<T>> implements Domain<T> {\n\n\tprivate T min;\n\tprivate T max;\n\n\tpublic Bounds(T min, T max) {\n\t\tthis.min = min;\n\t\tthis.max = max;\n\t}\n\n\t/**\n\t * Getter on the minimum (inclusive) bound of the domain.\n\t *\n\t * @return The minimum (inclusive) bound of the domain.\n\t */\n\tpublic T getMin() {\n\t\treturn min;\n\t}\n\n\t/**\n\t * Getter on the maximum (inclusive) bound of the domain.\n\t *\n\t * @return The maximum (inclusive) bound of the domain.\n\t */\n\tpublic T getMax() {\n\t\treturn max;\n\t}\n\n\t@Override\n\tpublic boolean inDomain(T value) {\n\t\treturn value.compareTo(min) >= 0 && value.compareTo(max) <= 0;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"[\" + min + \", \" + max + \"]\";\n\t}\n\n}", "public class Values<T> implements Domain<T> {\n\n\tprivate T[] values;\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic Values(T[] values) {\n\t\tSet<T> noDuplicates = new HashSet<>();\n\t\tfor (T value : values){\n\t\t\tnoDuplicates.add(value);\n\t\t}\n\t\tthis.values = (T[]) noDuplicates.toArray();\n\t}\n\n\t/**\n\t * Getter on the possible values.\n\t *\n\t * @return The possible values.\n\t */\n\tpublic T[] getValues() {\n\t\treturn values;\n\t}\n\n\t@Override\n\tpublic boolean inDomain(T value) {\n\t\tfor (T acceptedValue : values) {\n\t\t\tif (value.equals(acceptedValue)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder res = new StringBuilder();\n\t\tres.append(\"{\");\n\t\tint counter = 0;\n\t\tfor (T acceptedValue : values) {\n\t\t\tres.append(acceptedValue);\n\t\t\tif (counter < values.length - 1) {\n\t\t\t\tres.append(\", \");\n\t\t\t}\n\t\t\t++counter;\n\t\t}\n\t\tres.append(\"}\");\n\t\treturn res.toString();\n\t}\n\n}", "public abstract class ArgumentParser<T> {\n\n\tprivate Options affectedOptObject;\n\tprivate Field affectedOptField;\n\tprivate String argument;\n\n\tpublic ArgumentParser(Options opts, Field f, String argument) {\n\t\tthis.affectedOptObject = opts;\n\t\tthis.affectedOptField = f;\n\t\tthis.argument = argument;\n\t}\n\n\t/**\n\t * Sets the configurable member corresponding to the argument to a value.\n\t *\n\t * @param arg\n\t * \t\t\tThe command line argument giving the value to be set.\n\t * @throws IllegalArgumentException\n\t * @throws IllegalAccessException\n\t * @throws SecurityException\n\t * @throws ValueOutOfDomainException\n\t * @throws IncompatibleParserException\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic void parse(String arg) throws IllegalArgumentException,\n\t\tIllegalAccessException, SecurityException, ValueOutOfDomainException,\n\t\tIncompatibleParserException {\n\n\t\tT value = getArgumentValue(arg);\n\t\tDomain<T> fieldDomain = null;\n\t\ttry {\n\t\t\tfieldDomain =\n\t\t\t\t(Domain<T>) affectedOptObject.getFieldDomain(affectedOptField);\n\t\t} catch (NoSuchFieldException e) {}\n\t\tif (fieldDomain == null || fieldDomain.inDomain(value)) {\n\t\t\taffectedOptField.setAccessible(true);\n\t\t\taffectedOptField.set(affectedOptObject, value);\n\t\t} else {\n\t\t\tthrow new ValueOutOfDomainException(\n\t\t\t\t\"Domain error on \" + argument + \", \" + value\n\t\t\t\t\t+ \" not in \" + fieldDomain\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Getter on the argument corresponding to the parser.\n\t *\n\t * @return The argument corresponding to the parser.\n\t */\n\tpublic String getArgument() {\n\t\treturn argument;\n\t}\n\n\tprotected Options getAffectedOptObject() {\n\t\treturn affectedOptObject;\n\t}\n\n\tprotected Field getAffectedOptField() {\n\t\treturn affectedOptField;\n\t}\n\n\tprotected abstract T getArgumentValue(String arg)\n\t\tthrows IncompatibleParserException;\n\n}", "public class HexSelectionsParser extends FullArgumentParser<HexSelections> {\n\n\tpublic HexSelectionsParser(Options opts, Field f, String argument) {\n\t\tsuper(opts, f, argument);\n\t}\n\n\t@Override\n\tprotected HexSelections getArgumentValue(String arg)\n\t\tthrows IncompatibleParserException {\n\n\t\tHexSelections selections = new HexSelections(true);\n\n\t\tString[] parts = checkArgumentAndGetValue(arg).split(\";\");\n\t\tint partCounter = 0, activeSelectionIndex = 0;\n\n\t\tfor (String sel : parts) {\n\t\t\tString[] elts = sel.split(\",\");\n\t\t\tif (elts.length == 2 || elts.length == 3) {\n\t\t\t\tselections.add(new HexSelection(\n\t\t\t\t\tInteger.parseInt(elts[0]),\n\t\t\t\t\tInteger.parseInt(elts[1])\n\t\t\t\t));\n\n\t\t\t\tif (elts.length == 3) {\n\t\t\t\t\tboolean active = Boolean.parseBoolean(elts[2]);\n\t\t\t\t\tif (active) {\n\t\t\t\t\t\tactiveSelectionIndex = partCounter;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow new IllegalArgumentException(\"Unexpected number of \" +\n\t\t\t\t\t\"components in selection representation\");\n\t\t\t}\n\t\t\t++partCounter;\n\t\t}\n\n\t\tselections.setActiveSelectionIndex(activeSelectionIndex);\n\n\t\treturn selections;\n\t}\n}" ]
import java.io.Serializable; import main.options.Options; import main.options.ValueClass; import main.options.annotations.CommandLineArgument; import main.options.domain.Bounds; import main.options.domain.Values; import main.options.parser.ArgumentParser; import main.options.parser.HexSelectionsParser;
package hexcapture; /** * Options for the script capturing the hexadecimal selection in Cheat Engine. * * @author Maxime PIA */ public class HexOptions extends Options implements Serializable { /** * Backward-compatible with 0.7.0 */ private static final long serialVersionUID = 00000000007000000L; public static final double DEFAULT_STABILIZATION_THRESHOLD = 0.005; public static final int DEFAULT_REFRESH_DELAY = 50; public static final int DEFAULT_HISTORY_SIZE = 6; public static final HexUpdateStrategies DEFAULT_UPDATE_STRATEGY = HexUpdateStrategies.COMBINED; public static final HexSelections DEFAULT_HEX_SELECTIONS = new HexSelections(); @CommandLineArgument( command = "stabilization", description = "Determines at which proportion of the size of the " + "selection the number of differences between the current content " + "of the selection and that of the history is deemed low enough " + "to convert the selection." ) private Double stabilizationThreshold = DEFAULT_STABILIZATION_THRESHOLD; public static final Bounds<Double> STABILIZATION_THRESHOLD_DOMAIN = new Bounds<Double>(0d, 1d); @CommandLineArgument( command = "refresh", description = "The number of ms to wait before capturing the selection." ) private Integer refreshDelay = DEFAULT_REFRESH_DELAY; public static final Bounds<Integer> REFRESH_DELAY_DOMAIN = new Bounds<>(10, 400); @CommandLineArgument( command = "history", description = "The length of the array containing the previous " + "selections." ) private Integer historySize = DEFAULT_HISTORY_SIZE; public static final Bounds<Integer> HISTORY_SIZE_DOMAIN = new Bounds<>(1, 20); @CommandLineArgument( command = "strategy", description = "The strategy to use to deem the selection worthy of " + "being converted." ) private HexUpdateStrategies updateStrategy = DEFAULT_UPDATE_STRATEGY;
public static final Values<HexUpdateStrategies> UPDATE_STRATEGY_DOMAIN =
3
researchgate/restler
restler-core/src/test/java/net/researchgate/restdsl/dao/ServiceDaoTest.java
[ "@Entity(value = \"entity\", noClassnameStored = true)\npublic class TestEntity {\n @Id\n Long id;\n String value;\n\n public TestEntity() {\n }\n\n public TestEntity(Long id, String value) {\n this.id = id;\n this.value = value;\n }\n\n public Long getId() {\n return id;\n }\n\n public String getValue() {\n return value;\n }\n}", "public class RestDslException extends RuntimeException {\n //TODO: generialize types, rethink them.\n // TODO: need something like generic conflict state\n public enum Type {\n // DB constraint violation\n DUPLICATE_KEY,\n\n // Entity provided is not valid\n ENTITY_ERROR,\n\n // Unknown or implementation error\n GENERAL_ERROR,\n\n // params supplied via HTTP are invalid\n PARAMS_ERROR,\n\n // Service query contains errors\n QUERY_ERROR\n }\n\n // default type\n private Type type = Type.GENERAL_ERROR;\n\n public RestDslException(String message) {\n super(message);\n }\n\n public RestDslException(String message, Type type) {\n super(message);\n this.type = type;\n }\n\n public RestDslException(String message, Throwable cause, Type type) {\n super(message, cause);\n this.type = type;\n }\n\n public Type getType() {\n return type;\n }\n\n}", "public class NoOpStatsReporter implements StatsReporter {\n public static final NoOpStatsReporter INSTANCE = new NoOpStatsReporter();\n\n private NoOpStatsReporter() {\n }\n\n @Override\n public void timing(String key, long value, double sampleRate) {\n\n }\n\n @Override\n public void increment(String key, int magnitude, double sampleRate) {\n\n }\n\n @Override\n public void gauge(String key, double value) {\n\n }\n}", "public interface StatsReporter {\n\n void timing(String key, long value, double sampleRate);\n\n void increment(String key, int magnitude, double sampleRate);\n\n void gauge(String key, double value);\n\n\n default void timing(String key, long value) {\n timing(key, value, 1.0);\n }\n\n default void decrement(String key) {\n increment(key, -1, 1.0);\n }\n\n default void decrement(String key, int magnitude) {\n decrement(key, magnitude, 1.0);\n }\n\n default void increment(String key) {\n increment(key, 1, 1.0);\n }\n\n default void increment(String key, int magnitude) {\n increment(key, magnitude, 1.0);\n }\n\n default void decrement(String key, int magnitude, double sampleRate) {\n increment(key, -magnitude, sampleRate);\n }\n}", "public final class ServiceQuery<K> {\n private static final int MAX_LIMIT = 10000;\n\n private Integer limit;\n private Integer originalLimit;\n private int offset = 0;\n private boolean countTotalItems = true;\n private String order;\n private Set<String> fields;\n private Collection<K> ids;\n private Multimap<String, Object> criteria;\n private boolean indexValidation = true;\n private String groupBy;\n private Boolean countOnly = false;\n\n // field that ensures that all subelements of these fields must match in \"sync\"\n // it's like $elemMatch in Mongo https://docs.mongodb.com/v3.2/reference/operator/query/elemMatch/\n private Set<String> syncMatch;\n\n // calculated fields\n private String queryShape;\n\n public boolean isCountTotalItems() {\n return countTotalItems;\n }\n\n public int getLimit() {\n return limit;\n }\n\n public int getOffset() {\n return offset;\n }\n\n public String getOrder() {\n return order;\n }\n\n public String getGroupBy() {\n return groupBy;\n }\n\n public Boolean getCountOnly() {\n return countOnly;\n }\n\n public Set<String> getFields() {\n return fields;\n }\n\n public Multimap<String, Object> getCriteria() {\n return criteria;\n }\n\n public boolean isIndexValidation() {\n return indexValidation;\n }\n\n public Set<String> getSyncMatch() {\n return syncMatch;\n }\n\n public String getQueryShape() {\n return queryShape;\n }\n\n public static <K> ServiceQuery<K> all() {\n return new ServiceQueryBuilder<K>().build();\n }\n\n public static <K> ServiceQuery<K> byId(K id) {\n return new ServiceQueryBuilder<K>().ids(Collections.singletonList(id)).build();\n }\n\n public static <K> ServiceQuery<K> byIds(Iterable<K> ids) {\n return new ServiceQueryBuilder<K>().ids(ids).build();\n }\n\n\n @SuppressWarnings(\"unchecked\")\n public static <K> ServiceQuery<K> byCriteria(String key, Object value) throws RestDslException {\n return new ServiceQueryBuilder<K>().withCriteria(key, Collections.singletonList(value)).build();\n }\n\n public Collection<K> getIdList() {\n return ids;\n }\n\n protected ServiceQuery() {\n }\n\n @Override\n public boolean equals(Object o) {\n return o instanceof ServiceQuery<?> && toString().equals(o.toString());\n }\n\n @Override\n public int hashCode() {\n return toString().hashCode();\n }\n\n @Override\n public String toString() {\n return toUrlPart();\n }\n\n\n public static <K> ServiceQueryBuilder<K> builder() {\n return new ServiceQueryBuilder<>();\n }\n\n public static class ServiceQueryBuilder<K> {\n // on purpose in the buider, so that the query is already formed when was built\n private ServiceQueryParams serviceQueryParams = ServiceQueryParams.ALL_QUERY_PARAMS;\n\n private ServiceQueryBuilder() {\n }\n\n private ServiceQuery<K> query = new ServiceQuery<>();\n\n public ServiceQueryBuilder<K> offset(Integer offset) throws RestDslException {\n if (offset != null) {\n if (offset < 0) {\n throw new RestDslException(\"Offset cannot be less than 0\");\n }\n query.offset = offset;\n }\n return this;\n }\n\n public ServiceQueryBuilder<K> limit(Integer limit) throws RestDslException {\n if (limit != null) {\n if (limit < 0) {\n throw new RestDslException(\"Limit cannot be negative\", RestDslException.Type.QUERY_ERROR);\n }\n query.limit = limit;\n }\n query.originalLimit = query.limit;\n return this;\n }\n\n public ServiceQueryBuilder<K> fields(Collection<String> fields) {\n if (fields != null) {\n query.fields = Collections.unmodifiableSet(Sets.newHashSet(fields));\n }\n return this;\n }\n\n public ServiceQueryBuilder<K> syncMatch(Collection<String> syncMatch) {\n if (syncMatch != null) {\n query.syncMatch = Collections.unmodifiableSet(Sets.newHashSet(syncMatch));\n }\n return this;\n }\n\n public ServiceQueryBuilder<K> indexValidation(Boolean indexValidation) {\n if (indexValidation != null) {\n query.indexValidation = indexValidation;\n }\n return this;\n }\n\n\n public ServiceQueryBuilder<K> order(String order) {\n query.order = order;\n return this;\n }\n\n public ServiceQueryBuilder<K> groupBy(String groupBy) {\n query.groupBy = groupBy;\n return this;\n }\n\n public ServiceQueryBuilder<K> id(K id) {\n query.ids = Collections.singletonList(id);\n return this;\n }\n\n public ServiceQueryBuilder<K> ids(Iterable<K> ids) {\n if (ids instanceof Collection) {\n query.ids = (Collection<K>) ids;\n } else {\n query.ids = Lists.newArrayList(ids);\n }\n return this;\n }\n\n public ServiceQueryBuilder<K> countTotalItems(Boolean countTotalItems) {\n if (countTotalItems != null) {\n query.countTotalItems = countTotalItems;\n }\n return this;\n }\n\n public ServiceQueryBuilder<K> withCriterion(String key, Object value) throws RestDslException {\n return withCriteria(key, Collections.singletonList(value));\n }\n\n public ServiceQueryBuilder<K> withCriteria(String key, Collection<?> value) throws RestDslException {\n if (value == null || value.isEmpty()) {\n throw new RestDslException(\"Criteria values for field '\" + key + \"' cannot be empty\",\n RestDslException.Type.QUERY_ERROR);\n }\n if (query.criteria == null) {\n query.criteria = HashMultimap.create();\n }\n\n query.criteria.putAll(key, value);\n return this;\n }\n\n // VZ: varargs are bad!\n// public ServiceQueryBuilder<K> withCriteria(String key, Object ... value) throws RestDslException {\n// return withCriteria(key, Arrays.asList(value));\n// }\n\n public ServiceQueryBuilder<K> withServiceQueryParams(ServiceQueryParams serviceQueryParams) {\n this.serviceQueryParams = serviceQueryParams;\n return this;\n }\n\n public ServiceQuery<K> build() {\n applyServiceQueryParams();\n query.calculateQueryShape();\n return query;\n }\n\n private void applyServiceQueryParams() {\n // CRITERIA\n Multimap<String, Object> defaultCriteria = serviceQueryParams.getDefaultCriteria();\n if (defaultCriteria != null && !defaultCriteria.isEmpty()) {\n Multimap<String, Object> combinedCriteria = query.criteria != null ? LinkedHashMultimap.create(query.criteria) : LinkedHashMultimap.create();\n // Merge defaultCriteria and user defined criteria\n for (String key : defaultCriteria.keys()) {\n if (!combinedCriteria.containsKey(key)) {\n combinedCriteria.putAll(key, defaultCriteria.get(key));\n }\n }\n // ServiceQuery.ANY_VALUE is used as a placeholder for \"$any\" in criteria (see ServiceResource.parseRequest)\n combinedCriteria.keys().stream()\n .filter(key -> combinedCriteria.get(key).size() == 1 &&\n combinedCriteria.get(key).contains(ServiceQueryReservedValue.ANY)\n ).forEach(combinedCriteria::removeAll);\n query.criteria = combinedCriteria;\n }\n\n // FIELDS\n if (query.fields == null) {\n query.fields = serviceQueryParams.getDefaultFields();\n }\n\n // LIMIT\n if (query.limit != null && query.limit == 0) {\n query.countOnly = true;\n }\n int curLimit = query.limit == null ? serviceQueryParams.getDefaultLimit() : query.limit;\n query.limit = curLimit > MAX_LIMIT || curLimit < 0 ? MAX_LIMIT : curLimit;\n\n }\n }\n\n //TODO : make sure that & won't affect toUrl or query shape\n public String toUrlPart() {\n StringBuilder sb = new StringBuilder();\n if (ids != null && !ids.isEmpty()) {\n sb.append(Joiner.on(\",\").join(ids));\n } else {\n sb.append(\"-;\");\n }\n if (criteria != null) {\n for (String c : criteria.keySet()) {\n sb.append(c).append(\"=\");\n sb.append(Joiner.on(',').join(criteria.get(c).stream()\n .map(this::criteriaValToStr)\n .collect(Collectors.toList()))).append(\";\");\n }\n }\n sb.append(\"?\");\n sb.append(\"limit=\").append(getLimit()).append(\"&\");\n if (getOffset() != 0) {\n sb.append(\"offset=\").append(getOffset()).append(\"&\");\n }\n if (fields != null) {\n sb.append(\"fields=\").append(Joiner.on(',').join(getFields())).append(\"&\");\n }\n\n if (syncMatch != null) {\n sb.append(\"syncMatch=\").append(Joiner.on(',').join(getSyncMatch())).append(\"&\");\n }\n\n if (!indexValidation) {\n sb.append(\"indexValidation=false&\");\n }\n\n if (order != null) {\n sb.append(\"order=\").append(getOrder()).append(\"&\");\n }\n\n return sb.toString();\n }\n\n private String criteriaValToStr(Object v) {\n if (v == null) {\n return ServiceQueryReservedValue.NULL.toString();\n }\n if (v instanceof ServiceQueryReservedValue) {\n return ((ServiceQueryReservedValue) v).getStrVal();\n }\n if (v instanceof Date) {\n return new ThreadLocalDateFormat(\"yyyy-MM-dd'T'HH:mm:ss.SSSZ\").format((Date) v);\n }\n return v.toString();\n }\n\n private final static String QS_FIELD_SEP = \"-\";\n private final static String QS_KV_SEP = \"-\";\n private final static String QS_VAL_JOINER = \"_\";\n\n private void calculateQueryShape() {\n StringBuilder sb = new StringBuilder();\n if (!CollectionUtils.isEmpty(ids)) {\n sb.append(\"IDS\").append(QS_FIELD_SEP);\n } else {\n sb.append(QS_FIELD_SEP);\n }\n\n if (criteria != null) {\n sb.append(\"CRITERIA\").append(QS_KV_SEP);\n sb.append(Joiner.on(QS_VAL_JOINER).join(criteria.keySet()));\n }\n\n if (order != null) {\n sb.append(QS_FIELD_SEP).append(\"ORDER\").append(QS_KV_SEP).append(order);\n }\n if (groupBy != null) {\n sb.append(QS_FIELD_SEP).append(\"GROUPBY\").append(QS_KV_SEP).append(groupBy);\n }\n\n if (syncMatch != null) {\n sb.append(QS_FIELD_SEP).append(\"SYNCMATCH\").append(QS_KV_SEP).append(syncMatch);\n }\n\n if (originalLimit != null) {\n sb.append(QS_FIELD_SEP).append(\"LIMIT\");\n }\n\n queryShape = sb.toString();\n }\n\n}" ]
import com.google.common.collect.Lists; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.MongoClient; import com.mongodb.ServerAddress; import de.bwaldvogel.mongo.MongoServer; import de.bwaldvogel.mongo.backend.memory.MemoryBackend; import net.researchgate.restdsl.TestEntity; import net.researchgate.restdsl.exceptions.RestDslException; import net.researchgate.restdsl.metrics.NoOpStatsReporter; import net.researchgate.restdsl.metrics.StatsReporter; import net.researchgate.restdsl.queries.ServiceQuery; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import dev.morphia.Datastore; import dev.morphia.Morphia; import java.net.InetSocketAddress; import static net.researchgate.restdsl.exceptions.RestDslException.Type.QUERY_ERROR; import static org.junit.Assert.fail;
package net.researchgate.restdsl.dao; public class ServiceDaoTest { // This merely allow us to spin up a a dao. private Datastore fakedDatastore; private MongoServer server; private MongoClient client; @Before public void setUp() { server = new MongoServer(new MemoryBackend()); // bind on a random local port InetSocketAddress serverAddress = server.bind(); client = new MongoClient(new ServerAddress(serverAddress)); fakedDatastore = new Morphia().createDatastore(client, "testDatabase"); // insert and remove an item in order to create indexes final DBCollection collection = fakedDatastore.getCollection(TestEntity.class); final Object id = collection.insert(new BasicDBObject()).getUpsertedId(); collection.remove(new BasicDBObject("_id", id)); } @After public void tearDown() throws Exception { client.close(); server.shutdown(); } @Test public void testAllowGroupBy_doNotProvideAllowGroup_allow() { final TestServiceDao dao = new TestServiceDao(fakedDatastore, TestEntity.class); Assert.assertTrue(dao.allowGroupBy); final ServiceQuery<Long> q = ServiceQuery.<Long>builder() .withCriteria("id", Lists.newArrayList(1L, 2L, 3L)) .groupBy("id") .build(); dao.get(q); } @Test public void testAllowGroupBy_explicitlyDisallowGroupBy_doNotAllowQueryWithGroupBy() { final TestServiceDao dao = new TestServiceDao(fakedDatastore, TestEntity.class, NoOpStatsReporter.INSTANCE, false); Assert.assertFalse(dao.allowGroupBy); final ServiceQuery<Long> q = ServiceQuery.<Long>builder() .withCriteria("id", Lists.newArrayList(1L, 2L, 3L)) .groupBy("id") .build(); // get with group by -> fail try { dao.get(q); fail("Group by should not be allowed!, but it was"); } catch (RestDslException e) { Assert.assertEquals(QUERY_ERROR, e.getType()); } // get without groupBy -> successful dao.get(ServiceQuery.byId(1L)); // explicitly allow group by -> successful dao.setAllowGroupBy(); Assert.assertTrue(dao.allowGroupBy); dao.get(q); } static class TestServiceDao extends MongoServiceDao<TestEntity, Long> { public TestServiceDao(Datastore datastore, Class<TestEntity> entityClazz) { super(datastore, entityClazz); }
public TestServiceDao(Datastore datastore, Class<TestEntity> entityClazz, StatsReporter statsReporter, boolean allowGroupBy) {
3
alberto234/schedule-alarm-manager
android/ScheduleAlarmManager/ScheduleAlarmManager/src/main/java/com/scalior/schedulealarmmanager/SAManager.java
[ "public class SAMSQLiteHelper extends SQLiteOpenHelper {\n\n // Singleton\n private static SAMSQLiteHelper m_instance;\n\n public static SAMSQLiteHelper getInstance(Context context) {\n if (m_instance == null) {\n m_instance = new SAMSQLiteHelper(context);\n }\n\n return m_instance;\n }\n\n // Database information\n private static final String DATABASE_NAME = \"scheduleeventmanager.db\";\n private static final int DATABASE_VERSION = 6;\n\n // Tables:\n //\t\tDatabase Creation ID:\n //\t\t\tThis serves as a unique device id for the client. It is based on the database\n //\t\t\tsuch that the database re-creation represents a new client configuration\n public static final String TABLE_DBCREATION = \"dbcreation\";\n public static final String DBCREATION_UUID = \"uuid\";\n private static final String TABLE_DBCREATION_CREATE = \"create table \" +\n TABLE_DBCREATION + \" (\" +\n DBCREATION_UUID + \" text not null);\";\n\n //\t\tSchedule group\n public static final String TABLE_SCHEDULEGROUP = \"schedulegroup\";\n public static final String SCHEDULEGROUP_ID = \"_id\";\n public static final String SCHEDULEGROUP_TAG = \"tag\";\n public static final String SCHEDULEGROUP_ENABLED_FL = \"enabled\";\n public static final String SCHEDULEGROUP_OVERALL_STATE = \"overallstate\";\n private static final String TABLE_SCHEDULEGROUP_CREATE = \"create table \" +\n TABLE_SCHEDULEGROUP + \" (\" +\n SCHEDULEGROUP_ID + \" integer primary key autoincrement, \" +\n SCHEDULEGROUP_TAG + \" text not null, \" +\n SCHEDULEGROUP_ENABLED_FL + \" boolean not null, \" +\n SCHEDULEGROUP_OVERALL_STATE + \" text );\";\n\n //\t\tSchedule\n public static final String TABLE_SCHEDULE = \"schedule\";\n public static final String SCHEDULE_ID = \"_id\";\n public static final String SCHEDULE_START_TIME = \"starttime\";\n public static final String SCHEDULE_REPEAT_TYPE = \"repeattype\";\n public static final String SCHEDULE_DURATION = \"duration\";\n public static final String SCHEDULE_TAG = \"tag\";\n public static final String SCHEDULE_STATE = \"schedule_state\";\n public static final String SCHEDULE_DISABLE_FL = \"disabled\";\n public static final String SCHEDULE_GROUP_ID = \"groupid\";\n private static final String TABLE_SCHEDULE_CREATE = \"create table \" +\n TABLE_SCHEDULE + \" (\" +\n SCHEDULE_ID + \" integer primary key autoincrement, \" +\n SCHEDULE_START_TIME + \" datetime not null, \" +\n SCHEDULE_REPEAT_TYPE + \" integer not null, \" +\n SCHEDULE_DURATION + \" integer not null, \" +\n SCHEDULE_TAG + \" text not null, \" +\n SCHEDULE_STATE + \" text, \" +\n SCHEDULE_DISABLE_FL + \" boolean, \" +\n SCHEDULE_GROUP_ID + \" integer);\";\n\n //\t\tEvent\n public static final String TABLE_EVENT = \"event\";\n public static final String EVENT_ID = \"_id\";\n public static final String EVENT_SCHEDULE_ID = \"scheduleid\";\n public static final String EVENT_ALARM_TIME = \"alarmtime\";\n public static final String EVENT_STATE = \"state\";\n private static final String TABLE_EVENT_CREATE = \"create table \" +\n TABLE_EVENT + \" (\" +\n EVENT_ID + \" integer primary key autoincrement, \" +\n EVENT_SCHEDULE_ID + \" integer references \" + TABLE_SCHEDULE + \" on delete cascade, \" +\n EVENT_ALARM_TIME + \" datetime not null, \" +\n EVENT_STATE + \" text not null);\";\n\n // Constructor\n private SAMSQLiteHelper(Context context) {\n super(context, DATABASE_NAME, null, DATABASE_VERSION);\n }\n\n @Override\n public void onCreate(SQLiteDatabase database) {\n database.execSQL(TABLE_DBCREATION_CREATE);\n database.execSQL(TABLE_SCHEDULEGROUP_CREATE);\n database.execSQL(TABLE_SCHEDULE_CREATE);\n database.execSQL(TABLE_EVENT_CREATE);\n\n // Get the unique database creation id.\n // This id should factor in the device id.\n ContentValues values = new ContentValues();\n values.put(DBCREATION_UUID, UUID.randomUUID().toString());\n database.insert(TABLE_DBCREATION, null, values);\n\n }\n\n @Override\n public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldversion, int newversion) {\n sqLiteDatabase.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_EVENT);\n sqLiteDatabase.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_SCHEDULE);\n sqLiteDatabase.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_SCHEDULEGROUP);\n sqLiteDatabase.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_DBCREATION);\n\n onCreate(sqLiteDatabase);\n }\n\n @Override\n public void onOpen(SQLiteDatabase db) {\n super.onOpen(db);\n if (!db.isReadOnly()) {\n // Enable foreign key constraints\n db.execSQL(\"PRAGMA foreign_keys=ON;\");\n }\n }\n\n\n /**\n * Description:\n * Method to get the list of events that are due\n *\n * @param cutoffTime All events that happen at or before this time will be returned\n * @return The list of events that have are due, or null if none is due\n */\n public List<ScheduleEvent> getExpiredEvents(Calendar cutoffTime) {\n\n String rawSQL = \"SELECT \" + TABLE_EVENT + \".\" + EVENT_ID + \" , \" + EVENT_SCHEDULE_ID +\n \", \" + EVENT_ALARM_TIME + \", \" + EVENT_STATE + \", \" + SCHEDULE_START_TIME +\n \", \" + SCHEDULE_DURATION + \", \" + SCHEDULE_REPEAT_TYPE + \", \" + SCHEDULE_TAG +\n \", \" + SCHEDULE_STATE + \", \" + SCHEDULE_DISABLE_FL + \", \" + SCHEDULE_GROUP_ID +\n \" FROM \" + TABLE_EVENT + \" INNER JOIN \" + TABLE_SCHEDULE +\n \" ON \" + EVENT_SCHEDULE_ID + \" = \" + TABLE_SCHEDULE + \".\" + SCHEDULE_ID +\n \" WHERE \" + EVENT_ALARM_TIME + \" <= \" + (cutoffTime.getTimeInMillis() / 1000);\n\n // Note on the where clause:\n // Given that the Android adjusts alarm triggers so that they are more efficient\n // alarms are not going to be exact. We need to account for drifts.\n\n SQLiteDatabase database = getReadableDatabase();\n Cursor cursor = database.rawQuery(rawSQL, null);\n\n ArrayList<ScheduleEvent> expiredEvents = null;\n\n if (cursor.getCount() > 0) {\n cursor.moveToFirst();\n\n expiredEvents = new ArrayList<ScheduleEvent>();\n\n while (!cursor.isAfterLast()) {\n // Create the event\n Calendar alarmTime = Calendar.getInstance();\n alarmTime.setTimeInMillis(cursor.getLong(cursor.getColumnIndex(EVENT_ALARM_TIME)) * 1000);\n Event event = new Event(cursor.getLong(cursor.getColumnIndex(EVENT_SCHEDULE_ID)),\n alarmTime,\n cursor.getString(cursor.getColumnIndex(EVENT_STATE)));\n event.setId(cursor.getLong(cursor.getColumnIndex(EVENT_ID)));\n\n // Create the schedule\n Calendar startTime = Calendar.getInstance();\n startTime.setTimeInMillis(cursor.getLong(cursor.getColumnIndex(SCHEDULE_START_TIME)) * 1000);\n Schedule schedule = new Schedule(startTime,\n cursor.getInt(cursor.getColumnIndex(SCHEDULE_DURATION)),\n cursor.getInt(cursor.getColumnIndex(SCHEDULE_REPEAT_TYPE)),\n cursor.getString(cursor.getColumnIndex(SCHEDULE_TAG)));\n schedule.setId(cursor.getLong(cursor.getColumnIndex(EVENT_SCHEDULE_ID)));\n schedule.setState(cursor.getString(cursor.getColumnIndex(SCHEDULE_STATE)));\n schedule.setGroupId(cursor.getLong(cursor.getColumnIndex(SCHEDULE_GROUP_ID)));\n\n expiredEvents.add(new ScheduleEvent(schedule, event));\n\n cursor.moveToNext();\n }\n }\n\n cursor.close();\n return expiredEvents;\n }\n\n /**\n * Description:\n * Method to get the list of schedule events\n *\n * @return The list of events that have are due, or null if none is due\n */\n public List<ScheduleEvent> getScheduleEvents() {\n\n String rawSQL = \"SELECT \" + TABLE_EVENT + \".\" + EVENT_ID + \" , \" + EVENT_SCHEDULE_ID +\n \", \" + EVENT_ALARM_TIME + \", \" + EVENT_STATE + \", \" + SCHEDULE_START_TIME +\n \", \" + SCHEDULE_DURATION + \", \" + SCHEDULE_REPEAT_TYPE + \", \" + SCHEDULE_TAG +\n \", \" + SCHEDULE_STATE + \", \" + SCHEDULE_DISABLE_FL + \", \" + SCHEDULE_GROUP_ID +\n \" FROM \" + TABLE_EVENT + \" INNER JOIN \" + TABLE_SCHEDULE +\n \" ON \" + EVENT_SCHEDULE_ID + \" = \" + TABLE_SCHEDULE + \".\" + SCHEDULE_ID;\n\n SQLiteDatabase database = getReadableDatabase();\n Cursor cursor = database.rawQuery(rawSQL, null);\n\n List<ScheduleEvent> scheduleEvents = extractScheduleEventsFromCursor(cursor);\n\n cursor.close();\n return scheduleEvents;\n }\n\n /**\n * Description:\n * This returns the next event to be scheduled given the current time\n *\n * @return One ScheduleEvent, or null if no other event occurs in the future\n */\n public ScheduleEvent getNextEvent() {\n ScheduleEvent scheduleEvent = null;\n\n Calendar currTime = Calendar.getInstance();\n\n String rawSQL = \"SELECT \" + TABLE_EVENT + \".\" + EVENT_ID + \" , \" + EVENT_SCHEDULE_ID +\n \", \" + EVENT_ALARM_TIME + \", \" + EVENT_STATE + \", \" + SCHEDULE_START_TIME +\n \", \" + SCHEDULE_DURATION + \", \" + SCHEDULE_REPEAT_TYPE + \", \" + SCHEDULE_TAG +\n \", \" + SCHEDULE_STATE + \", \" + SCHEDULE_DISABLE_FL + \", \" + SCHEDULE_GROUP_ID +\n \" FROM \" + TABLE_EVENT + \" INNER JOIN \" + TABLE_SCHEDULE +\n \" ON \" + EVENT_SCHEDULE_ID + \" = \" + TABLE_SCHEDULE + \".\" + SCHEDULE_ID +\n \" WHERE \" + EVENT_ALARM_TIME + \" >= \" + (currTime.getTimeInMillis() / 1000) +\n \" ORDER BY \" + EVENT_ALARM_TIME +\n \" LIMIT 1;\";\n\n SQLiteDatabase database = getReadableDatabase();\n Cursor cursor = database.rawQuery(rawSQL, null);\n\n List<ScheduleEvent> scheduleEvents = extractScheduleEventsFromCursor(cursor);\n\n\n if (scheduleEvents != null && scheduleEvents.size() > 0) {\n // There should only be one scheduleEvent\n scheduleEvent = scheduleEvents.get(0);\n }\n\n cursor.close();\n return scheduleEvent;\n }\n\n /**\n * Description:\n * This returns the next event to be scheduled for the group with given tag,\n * based on the current time\n *\n * @return One ScheduleEvent, or null if no other event occurs in the future\n */\n public ScheduleEvent getNextEventForGroup(String groupTag) {\n ScheduleEvent scheduleEvent = null;\n\n if (groupTag == null || groupTag.isEmpty()) {\n return null;\n }\n\n Calendar currTime = Calendar.getInstance();\n\n String rawSQL = \"SELECT \" + TABLE_EVENT + \".\" + EVENT_ID + \" , \" + EVENT_SCHEDULE_ID +\n \", \" + EVENT_ALARM_TIME + \", \" + EVENT_STATE + \", \" + SCHEDULE_START_TIME +\n \", \" + SCHEDULE_DURATION + \", \" + SCHEDULE_REPEAT_TYPE + \", \" + TABLE_SCHEDULE +\n \".\" + SCHEDULE_TAG + \", \" + SCHEDULE_STATE + \", \" + SCHEDULE_DISABLE_FL + \", \" + SCHEDULE_GROUP_ID +\n \" FROM \" + TABLE_EVENT + \" INNER JOIN \" + TABLE_SCHEDULE +\n \" ON \" + EVENT_SCHEDULE_ID + \" = \" + TABLE_SCHEDULE + \".\" + SCHEDULE_ID +\n \" INNER JOIN \" + TABLE_SCHEDULEGROUP +\n \" ON \" + SCHEDULE_GROUP_ID + \" = \" + TABLE_SCHEDULEGROUP + \".\" + SCHEDULEGROUP_ID +\n \" WHERE \" + EVENT_ALARM_TIME + \" >= \" + (currTime.getTimeInMillis() / 1000) +\n \" AND \" + TABLE_SCHEDULEGROUP + \".\" + SCHEDULEGROUP_TAG + \" = '\" + groupTag + \"'\" +\n \" ORDER BY \" + EVENT_ALARM_TIME +\n \" LIMIT 1;\";\n\n SQLiteDatabase database = getReadableDatabase();\n Cursor cursor = database.rawQuery(rawSQL, null);\n\n List<ScheduleEvent> scheduleEvents = extractScheduleEventsFromCursor(cursor);\n\n\n if (scheduleEvents != null && scheduleEvents.size() > 0) {\n // There should only be one scheduleEvent\n scheduleEvent = scheduleEvents.get(0);\n }\n\n cursor.close();\n return scheduleEvent;\n }\n\n /**\n * Description:\n * Add a new event or update an existing event to the database\n *\n * @param event - the event to add or update\n * @return long - the database id if successful, -1 otherwise\n */\n public long addOrUpdateEvent(Event event) {\n long retVal = -1;\n\n if (event != null) {\n SQLiteDatabase database = getWritableDatabase();\n\n // First check if this exists in the database.\n String[] columns = {EVENT_ID};\n StringBuilder selection = new StringBuilder(EVENT_ID);\n selection.append(\" = \").append(event.getId());\n\n Cursor cursor = database.query(TABLE_EVENT,\n columns,\n selection.toString(),\n null, null, null, null);\n\n if (cursor.getCount() == 1) {\n cursor.moveToFirst();\n\n // Update fields that change.\n ContentValues values = new ContentValues();\n values.put(EVENT_ALARM_TIME, event.getAlarmTime().getTimeInMillis() / 1000);\n database.update(TABLE_EVENT, values, selection.toString(), null);\n retVal = cursor.getLong(0);\n } else if (cursor.getCount() == 0) {\n ContentValues values = new ContentValues();\n values.put(EVENT_SCHEDULE_ID, event.getScheduleID());\n values.put(EVENT_ALARM_TIME, event.getAlarmTime().getTimeInMillis() / 1000);\n values.put(EVENT_STATE, event.getState());\n retVal = database.insert(TABLE_EVENT, null, values);\n event.setId(retVal);\n }\n\n cursor.close();\n }\n return retVal;\n }\n\n /**\n * Description:\n * delete an event from the database.\n *\n * @param event - the event to delete\n * @return boolean - true if successful, false other wise\n */\n public boolean deleteEvent(Event event) {\n boolean bRet = false;\n\n if (event != null) {\n SQLiteDatabase database = getWritableDatabase();\n\n String selection = EVENT_ID + \" = \" + event.getId();\n\n int count = database.delete(TABLE_EVENT, selection, null);\n\n bRet = count >= 1;\n }\n\n return bRet;\n }\n\n /**\n * Description:\n * delete all events that belong to the schedule identified by scheduleId.\n *\n * @param scheduleId - The schedule identified by scheduleId\n * @return boolean - true if successful, false other wise\n */\n public boolean deleteEventByScheduleId(long scheduleId) {\n boolean bRet = false;\n\n if (scheduleId > 0) {\n SQLiteDatabase database = getWritableDatabase();\n\n String selection = EVENT_SCHEDULE_ID + \" = \" + scheduleId;\n\n int count = database.delete(TABLE_EVENT, selection, null);\n\n bRet = count >= 1;\n }\n\n return bRet;\n }\n\n /**\n * Description:\n * Add a new schedule or update an existing schedule to the database\n *\n * @param schedule - the schedule to add or update\n * @return long - the database id if successful, -1 otherwise\n */\n public long addOrUpdateSchedule(Schedule schedule) {\n long retVal = -1;\n\n if (schedule != null) {\n SQLiteDatabase database = getWritableDatabase();\n\n // First check if this exists in the database.\n String[] columns = {SCHEDULE_ID, SCHEDULE_REPEAT_TYPE, SCHEDULE_TAG};\n StringBuilder selection = new StringBuilder(SCHEDULE_ID);\n selection.append(\" = \").append(schedule.getId());\n\n Cursor cursor = database.query(TABLE_SCHEDULE,\n columns,\n selection.toString(),\n null, null, null, null);\n\n if (cursor.getCount() == 1) {\n cursor.moveToFirst();\n\n // Update fields that change.\n ContentValues values = new ContentValues();\n values.put(SCHEDULE_START_TIME, schedule.getStartTime().getTimeInMillis() / 1000);\n values.put(SCHEDULE_DURATION, schedule.getDuration());\n values.put(SCHEDULE_STATE, schedule.getState());\n values.put(SCHEDULE_DISABLE_FL, schedule.isDisabled());\n database.update(TABLE_SCHEDULE, values, selection.toString(), null);\n retVal = cursor.getLong(cursor.getColumnIndex(SCHEDULE_ID));\n if (retVal > 0) {\n schedule.setRepeatType(cursor.getInt(cursor.getColumnIndex(SCHEDULE_REPEAT_TYPE)));\n schedule.setTag(cursor.getString(cursor.getColumnIndex(SCHEDULE_TAG)));\n }\n } else if (cursor.getCount() == 0) {\n ContentValues values = new ContentValues();\n values.put(SCHEDULE_START_TIME, schedule.getStartTime().getTimeInMillis() / 1000);\n values.put(SCHEDULE_DURATION, schedule.getDuration());\n values.put(SCHEDULE_REPEAT_TYPE, schedule.getRepeatType());\n values.put(SCHEDULE_TAG, schedule.getTag());\n values.put(SCHEDULE_STATE, schedule.getState());\n values.put(SCHEDULE_DISABLE_FL, schedule.isDisabled());\n values.put(SCHEDULE_GROUP_ID, schedule.getGroupId());\n retVal = database.insert(TABLE_SCHEDULE, null, values);\n schedule.setId(retVal);\n }\n\n cursor.close();\n }\n return retVal;\n }\n\n /**\n * Description:\n * delete a schedule from the database.\n *\n * @param schedule - the schedule to delete\n * @return boolean - true if successful, false other wise\n */\n public boolean deleteSchedule(Schedule schedule) {\n return schedule != null && deleteSchedule(schedule.getId());\n }\n\n /**\n * Description:\n * delete a schedule from the database.\n *\n * @param scheduleId - the scheduleId to delete\n * @return boolean - true if successful, false otherwise\n */\n public boolean deleteSchedule(long scheduleId) {\n boolean bRet = false;\n\n if (scheduleId > 0) {\n SQLiteDatabase database = getWritableDatabase();\n\n String selection = SCHEDULE_ID + \" = \" + scheduleId;\n\n int count = database.delete(TABLE_SCHEDULE, selection, null);\n\n // There is a cascade to the event table, so deleting a schedule will\n // delete all associated events\n bRet = count >= 1;\n }\n\n return bRet;\n }\n\n /**\n * Description:\n * delete all schedules that match the tag from the database.\n *\n * @param scheduleTag - the schedule tag\n * @return int - number of schedules deleted\n */\n public int deleteScheduleByTag(String scheduleTag) {\n if (scheduleTag == null || scheduleTag.isEmpty()) {\n return 0;\n }\n\n SQLiteDatabase database = getWritableDatabase();\n\n String selection = SCHEDULE_TAG + \" = ?\";\n String[] selectionArgs = {scheduleTag};\n\n int count = database.delete(TABLE_SCHEDULE, selection, selectionArgs);\n return count;\n }\n\n /**\n * Description:\n * Method to get a list of schedules currently stored in the database\n *\n * @return The list of schedules, or null if none is exists\n */\n public List<Schedule> getAllSchedules() {\n\n String[] columns = {SCHEDULE_ID, SCHEDULE_START_TIME, SCHEDULE_DURATION,\n SCHEDULE_REPEAT_TYPE, SCHEDULE_TAG, SCHEDULE_STATE,\n SCHEDULE_DISABLE_FL, SCHEDULE_GROUP_ID};\n\n SQLiteDatabase database = getReadableDatabase();\n Cursor cursor = database.query(TABLE_SCHEDULE, columns, null, null, null, null, null);\n\n List<Schedule> schedules = extractSchedulesFromCursor(cursor);\n\n cursor.close();\n return schedules;\n }\n\n\n /**\n * Description:\n * Method to get a list of schedules that match a particular tag\n *\n * @param tag: The tag to match.\n * @return The list of schedules, or null if there is no match\n */\n public List<Schedule> getSchedulesByTag(String tag) {\n\n if (tag == null || tag.isEmpty()) {\n return null;\n }\n\n\n String[] columns = {SCHEDULE_ID, SCHEDULE_START_TIME, SCHEDULE_DURATION,\n SCHEDULE_REPEAT_TYPE, SCHEDULE_TAG, SCHEDULE_STATE, SCHEDULE_DISABLE_FL,\n SCHEDULE_GROUP_ID};\n\n String selection = SCHEDULE_TAG + \" = ?\";\n String[] selectionArgs = {tag};\n\n SQLiteDatabase database = getReadableDatabase();\n Cursor cursor = database.query(TABLE_SCHEDULE, columns, selection, selectionArgs, null, null, null);\n\n List<Schedule> schedules = extractSchedulesFromCursor(cursor);\n\n cursor.close();\n return schedules;\n }\n\n /**\n * Description:\n * Method to get a list of schedules that belong to a particular group\n *\n * @param groupId: The group Id to match.\n * @return The list of schedules, or null if there is no match\n */\n public List<Schedule> getSchedulesByGroupId(long groupId) {\n\n if (groupId <= 0) {\n return null;\n }\n\n\n String[] columns = {SCHEDULE_ID, SCHEDULE_START_TIME, SCHEDULE_DURATION,\n SCHEDULE_REPEAT_TYPE, SCHEDULE_TAG, SCHEDULE_STATE, SCHEDULE_DISABLE_FL,\n SCHEDULE_GROUP_ID};\n\n String selection = SCHEDULE_GROUP_ID + \" = \" + groupId;\n\n SQLiteDatabase database = getReadableDatabase();\n Cursor cursor = database.query(TABLE_SCHEDULE, columns, selection, null, null, null, null);\n\n List<Schedule> schedules = extractSchedulesFromCursor(cursor);\n\n cursor.close();\n return schedules;\n }\n\n /**\n * Description:\n * Return a schedule given its id\n *\n * @param scheduleId - the schedule id of the schedule to return\n * @return Schedule - the schedule object if found, null otherwise\n */\n public Schedule getScheduleById(long scheduleId) {\n Schedule retSchedule = null;\n if (scheduleId > 0) {\n SQLiteDatabase database = getReadableDatabase();\n\n String[] columns = {SCHEDULE_ID, SCHEDULE_START_TIME, SCHEDULE_DURATION,\n SCHEDULE_REPEAT_TYPE, SCHEDULE_TAG, SCHEDULE_STATE,\n SCHEDULE_DISABLE_FL, SCHEDULE_GROUP_ID};\n String selection = SCHEDULE_ID + \" = \" + scheduleId;\n\n Cursor cursor = database.query(TABLE_SCHEDULE,\n columns,\n selection,\n null, null, null, null);\n\n List<Schedule> schedules = extractSchedulesFromCursor(cursor);\n\n cursor.close();\n\n if (schedules != null && schedules.size() > 0) {\n retSchedule = schedules.get(0);\n }\n }\n\n return retSchedule;\n }\n\n\n /**\n * Description:\n * Add a new schedule group\n *\n * @param group - the schedule group to add\n * @return long - the database id if successful, -1 otherwise\n */\n public long addOrUpdateScheduleGroup(ScheduleGroup group) {\n long retVal = -1;\n\n if (group != null) {\n SQLiteDatabase database = getWritableDatabase();\n\n // First check if this exists in the database.\n String[] columns = {SCHEDULEGROUP_ID};\n String selection = SCHEDULEGROUP_ID + \" = \" + group.getId();\n\n Cursor cursor = database.query(TABLE_SCHEDULEGROUP,\n columns,\n selection,\n null, null, null, null);\n\n if (cursor.getCount() == 1) {\n // Update fields that change.\n ContentValues values = new ContentValues();\n values.put(SCHEDULEGROUP_ENABLED_FL, group.isEnabled());\n values.put(SCHEDULEGROUP_OVERALL_STATE, group.getOverallState());\n database.update(TABLE_SCHEDULEGROUP, values, selection, null);\n retVal = group.getId();\n } else if (cursor.getCount() == 0) {\n ContentValues values = new ContentValues();\n values.put(SCHEDULEGROUP_TAG, group.getTag());\n values.put(SCHEDULEGROUP_ENABLED_FL, group.isEnabled());\n values.put(SCHEDULEGROUP_OVERALL_STATE, group.getOverallState());\n retVal = database.insert(TABLE_SCHEDULEGROUP, null, values);\n group.setId(retVal);\n }\n cursor.close();\n }\n\n return retVal;\n }\n\n\n /**\n * Description:\n * Retrieve a schedule group by id\n *\n * @param id - the id of the schedule group\n * @return ScheduleGroup - the schedule group to retrieve\n */\n public ScheduleGroup getScheduleGroupById(long id) {\n ScheduleGroup group = null;\n if (id > 0) {\n SQLiteDatabase database = getReadableDatabase();\n\n String[] columns = {SCHEDULEGROUP_ID, SCHEDULEGROUP_TAG, SCHEDULEGROUP_ENABLED_FL,\n SCHEDULEGROUP_OVERALL_STATE};\n String selection = SCHEDULEGROUP_ID + \" = \" + id;\n\n Cursor cursor = database.query(TABLE_SCHEDULEGROUP,\n columns,\n selection,\n null, null, null, null);\n\n if (cursor.getCount() > 0) {\n cursor.moveToFirst();\n group = new ScheduleGroup(cursor.getString(cursor.getColumnIndex(SCHEDULEGROUP_TAG)),\n cursor.getInt(cursor.getColumnIndex(SCHEDULEGROUP_ENABLED_FL)) == 1);\n group.setId(id);\n group.setOverallState(cursor.getString(cursor.getColumnIndex(SCHEDULEGROUP_OVERALL_STATE)));\n }\n cursor.close();\n }\n\n return group;\n }\n\n /**\n * Description:\n * Retrieve a schedule group by tag\n *\n * @param tag - the tag assigned to the schedule group\n * @return ScheduleGroup - the schedule group to retrieve\n */\n public ScheduleGroup getScheduleGroupByTag(String tag) {\n ScheduleGroup group = null;\n if (tag != null && !tag.isEmpty()) {\n String[] columns = {SCHEDULEGROUP_ID, SCHEDULEGROUP_TAG, SCHEDULEGROUP_ENABLED_FL};\n String selection = SCHEDULEGROUP_TAG + \" = ?\";\n String[] selectionArgs = {tag};\n\n SQLiteDatabase database = getReadableDatabase();\n Cursor cursor = database.query(TABLE_SCHEDULEGROUP,\n columns, selection, selectionArgs,\n null, null, null, null);\n\n if (cursor.getCount() > 0) {\n cursor.moveToFirst();\n group = new ScheduleGroup(cursor.getString(cursor.getColumnIndex(SCHEDULEGROUP_TAG)),\n cursor.getInt(cursor.getColumnIndex(SCHEDULEGROUP_ENABLED_FL)) == 1);\n group.setId(cursor.getLong(cursor.getColumnIndex(SCHEDULEGROUP_ID)));\n }\n cursor.close();\n }\n\n return group;\n }\n\n /**\n * Description:\n * Delete a schedule group given its id\n *\n * @param id - the id of the group to delete\n * @return ScheduleGroup - the schedule group to retrieve\n */\n public boolean deleteGroupById(long id) {\n boolean bRet = false;\n\n if (id > 0) {\n SQLiteDatabase database = getWritableDatabase();\n\n String selection = SCHEDULEGROUP_ID + \" = \" + id;\n\n int count = database.delete(TABLE_SCHEDULEGROUP, selection, null);\n\n bRet = count >= 1;\n }\n\n return bRet;\n }\n\n /**\n * Description:\n * Add a schedule and its associated events to the database\n * This happens in a transaction\n *\n * @param schedule - the schedule to add\n * @param startAndStopEvents - the events to add\n * @return long - the schedule id if everything was added, or -1\n */\n public long addScheduleAndEvents(Schedule schedule, List<Event> startAndStopEvents, boolean newSchedule) {\n long scheduleId = -1;\n\n SQLiteDatabase database = getWritableDatabase();\n database.beginTransaction();\n try {\n if (newSchedule) {\n // Add the schedule\n ContentValues values = new ContentValues();\n values.put(SCHEDULE_START_TIME, schedule.getStartTime().getTimeInMillis() / 1000);\n values.put(SCHEDULE_DURATION, schedule.getDuration());\n values.put(SCHEDULE_REPEAT_TYPE, schedule.getRepeatType());\n values.put(SCHEDULE_TAG, schedule.getTag());\n values.put(SCHEDULE_STATE, schedule.getState());\n values.put(SCHEDULE_DISABLE_FL, schedule.isDisabled());\n values.put(SCHEDULE_GROUP_ID, schedule.getGroupId());\n scheduleId = database.insert(TABLE_SCHEDULE, null, values);\n schedule.setId(scheduleId);\n } else {\n // Update fields that change.\n String selection = SCHEDULE_ID + \" = \" + schedule.getId();\n\n ContentValues values = new ContentValues();\n values.put(SCHEDULE_START_TIME, schedule.getStartTime().getTimeInMillis() / 1000);\n values.put(SCHEDULE_DURATION, schedule.getDuration());\n values.put(SCHEDULE_STATE, schedule.getState());\n values.put(SCHEDULE_DISABLE_FL, schedule.isDisabled());\n int count = database.update(TABLE_SCHEDULE, values, selection, null);\n if (count == 1) {\n scheduleId = schedule.getId();\n }\n }\n\n if (scheduleId <= 0) {\n return scheduleId;\n }\n\n // Add events\n long eventId = -1;\n for (int i = 0; i < 2; i++) {\n Event event = startAndStopEvents.get(i);\n event.setScheduleID(scheduleId);\n\n ContentValues values = new ContentValues();\n values.put(EVENT_SCHEDULE_ID, event.getScheduleID());\n values.put(EVENT_ALARM_TIME, event.getAlarmTime().getTimeInMillis() / 1000);\n values.put(EVENT_STATE, event.getState());\n eventId = database.insert(TABLE_EVENT, null, values);\n if (eventId <= 0) {\n break;\n }\n event.setId(eventId);\n }\n\n if (eventId > 0) {\n database.setTransactionSuccessful();\n } else {\n scheduleId = -1;\n }\n } finally {\n database.endTransaction();\n }\n\n return scheduleId;\n }\n\n /**\n * Description:\n * delete all events that belong to the schedule group identified by the group tag.\n *\n * @param groupTag - The group tag of the schedule group\n * @return boolean - true if successful, false otherwise\n */\n public boolean deleteEventsByGroupTag(String groupTag) {\n boolean bRet = false;\n\n ScheduleGroup group = getScheduleGroupByTag(groupTag);\n if (group != null) {\n String scheduleIdSQL = \"SELECT \" + SCHEDULE_ID +\n \" FROM \" + TABLE_SCHEDULE +\n \" WHERE \" + SCHEDULE_GROUP_ID + \" = \" + group.getId();\n\n String selection = EVENT_SCHEDULE_ID + \" IN (\" + scheduleIdSQL + \")\";\n\n SQLiteDatabase database = getWritableDatabase();\n database.delete(TABLE_EVENT, selection, null);\n bRet = true;\n\n // If we need to use a raw SQL to perform the delete\n // String rawSQL = \"DELETE FROM \" + TABLE_EVENT +\n //\t\t\" WHERE \" + selection + \";\";\n // database.execSQL(rawSQL);\n }\n\n return bRet;\n }\n\n\n /**\n * Description:\n * Add a list of schedules and their associated events to the database\n * This happens in a transaction\n *\n * @param schedulesAndEventsToAdd - a holder of the schedule and its events\n * @return true if all were successful, false if there was at least one failure.\n * Upon failure, the transaction is rolled back.\n * Check each ScheduleAndEventsToAdd object for which failed.\n */\n public boolean addMultipleScheduleAndEvents(List<ScheduleAndEventsToAdd> schedulesAndEventsToAdd) {\n boolean bRet = true;\n\n if (schedulesAndEventsToAdd == null || schedulesAndEventsToAdd.size() == 0) {\n return false;\n }\n\n SQLiteDatabase database = getWritableDatabase();\n database.beginTransaction();\n try {\n for (ScheduleAndEventsToAdd scheduleAndEvents : schedulesAndEventsToAdd) {\n Schedule schedule = scheduleAndEvents.m_schedule;\n if (scheduleAndEvents.m_newSchedule) {\n // Add the schedule\n ContentValues values = new ContentValues();\n values.put(SCHEDULE_START_TIME, schedule.getStartTime().getTimeInMillis() / 1000);\n values.put(SCHEDULE_DURATION, schedule.getDuration());\n values.put(SCHEDULE_REPEAT_TYPE, schedule.getRepeatType());\n values.put(SCHEDULE_TAG, schedule.getTag());\n values.put(SCHEDULE_STATE, schedule.getState());\n values.put(SCHEDULE_DISABLE_FL, schedule.isDisabled());\n values.put(SCHEDULE_GROUP_ID, schedule.getGroupId());\n long scheduleId = database.insert(TABLE_SCHEDULE, null, values);\n if (scheduleId > 0) {\n schedule.setId(scheduleId);\n scheduleAndEvents.m_addedScheduleId = scheduleId;\n } else {\n bRet = false;\n break;\n }\n } else {\n // Update fields that change.\n String selection = SCHEDULE_ID + \" = \" + schedule.getId();\n\n ContentValues values = new ContentValues();\n values.put(SCHEDULE_START_TIME, schedule.getStartTime().getTimeInMillis() / 1000);\n values.put(SCHEDULE_DURATION, schedule.getDuration());\n values.put(SCHEDULE_STATE, schedule.getState());\n values.put(SCHEDULE_DISABLE_FL, schedule.isDisabled());\n int count = database.update(TABLE_SCHEDULE, values, selection, null);\n if (count == 1) {\n scheduleAndEvents.m_addedScheduleId = schedule.getId();\n } else {\n bRet = false;\n break;\n }\n }\n\n // Add events\n long eventId = -1;\n for (int i = 0; i < 2; i++) {\n Event event = scheduleAndEvents.m_events.get(i);\n event.setScheduleID(scheduleAndEvents.m_addedScheduleId);\n\n ContentValues values = new ContentValues();\n values.put(EVENT_SCHEDULE_ID, event.getScheduleID());\n values.put(EVENT_ALARM_TIME, event.getAlarmTime().getTimeInMillis() / 1000);\n values.put(EVENT_STATE, event.getState());\n eventId = database.insert(TABLE_EVENT, null, values);\n if (eventId <= 0) {\n bRet = false;\n break;\n }\n event.setId(eventId);\n }\n\n if (!bRet) {\n break;\n }\n }\n\n // Commit the transaction\n if (bRet) {\n database.setTransactionSuccessful();\n }\n } finally {\n database.endTransaction();\n }\n return bRet;\n }\n\n /**\n * Description:\n * Delete all schedules that belong to the group identified by group tag\n *\n * @param groupTag - The tag for the group\n * @return true if successful, false otherwise\n */\n public boolean deleteSchedulesByGroup(String groupTag) {\n boolean success = false;\n\n if (groupTag != null && !groupTag.isEmpty()) {\n SQLiteDatabase database = getWritableDatabase();\n database.beginTransaction();\n try {\n // 1 - delete all schedules in the group\n String scheduleIdSQL = \"SELECT \" + TABLE_SCHEDULE + \".\" + SCHEDULE_ID +\n \" FROM \" + TABLE_SCHEDULE + \" INNER JOIN \" + TABLE_SCHEDULEGROUP +\n \" ON \" + SCHEDULE_GROUP_ID + \" = \" + TABLE_SCHEDULEGROUP + \".\" + SCHEDULEGROUP_ID +\n \" WHERE \" + TABLE_SCHEDULEGROUP + \".\" + SCHEDULEGROUP_TAG + \" = ?\";\n String selection = TABLE_SCHEDULE + \".\" + SCHEDULE_ID + \" IN (\" + scheduleIdSQL + \")\";\n String[] selectionArgs = {groupTag};\n database.delete(TABLE_SCHEDULE, selection, selectionArgs);\n\n // 2 - delete the group\n selection = SCHEDULEGROUP_TAG + \" = ?\";\n database.delete(TABLE_SCHEDULEGROUP, selection, selectionArgs);\n database.setTransactionSuccessful();\n success = true;\n } finally {\n database.endTransaction();\n }\n }\n return success;\n }\n\n /**\n * Description:\n * Returns all the groups in the system.\n *\n * @return The list of ScheduleGroups, or null if none is exists\n */\n public List<ScheduleGroup> getAllScheduleGroups() {\n\n String[] columns = {SCHEDULEGROUP_ID, SCHEDULEGROUP_TAG, SCHEDULEGROUP_ENABLED_FL,\n SCHEDULEGROUP_OVERALL_STATE};\n\n SQLiteDatabase database = getReadableDatabase();\n Cursor cursor = database.query(TABLE_SCHEDULEGROUP, columns, null, null, null, null, null);\n\n ArrayList<ScheduleGroup> groups = null;\n\n if (cursor.getCount() > 0) {\n cursor.moveToFirst();\n\n groups = new ArrayList<ScheduleGroup>();\n\n while (!cursor.isAfterLast()) {\n\n ScheduleGroup group = new ScheduleGroup(cursor.getString(cursor.getColumnIndex(SCHEDULEGROUP_TAG)),\n cursor.getInt(cursor.getColumnIndex(SCHEDULEGROUP_ENABLED_FL)) == 1);\n group.setId(cursor.getLong(cursor.getColumnIndex(SCHEDULEGROUP_ID)));\n group.setOverallState(cursor.getString(cursor.getColumnIndex(SCHEDULEGROUP_OVERALL_STATE)));\n\n groups.add(group);\n cursor.moveToNext();\n }\n }\n\n cursor.close();\n return groups;\n }\n\n /**\n * Helper method to populate an ArrayList of schedules given a database cursor\n *\n * @param cursor\n * @return\n */\n private List<Schedule> extractSchedulesFromCursor(Cursor cursor) {\n ArrayList<Schedule> schedules = null;\n\n if (cursor.getCount() > 0) {\n cursor.moveToFirst();\n\n schedules = new ArrayList<Schedule>();\n\n while (!cursor.isAfterLast()) {\n Calendar startTime = Calendar.getInstance();\n startTime.setTimeInMillis(cursor.getLong(cursor.getColumnIndex(SCHEDULE_START_TIME)) * 1000);\n Schedule schedule = new Schedule(startTime,\n cursor.getInt(cursor.getColumnIndex(SCHEDULE_DURATION)),\n cursor.getInt(cursor.getColumnIndex(SCHEDULE_REPEAT_TYPE)),\n cursor.getString(cursor.getColumnIndex(SCHEDULE_TAG)));\n schedule.setId(cursor.getLong(cursor.getColumnIndex(SCHEDULE_ID)));\n schedule.setState(cursor.getString(cursor.getColumnIndex(SCHEDULE_STATE)));\n schedule.setDisabled(cursor.getInt(cursor.getColumnIndex(SCHEDULE_DISABLE_FL)) == 1);\n schedule.setGroupId(cursor.getLong(cursor.getColumnIndex(SCHEDULE_GROUP_ID)));\n\n schedules.add(schedule);\n cursor.moveToNext();\n }\n }\n\n return schedules;\n }\n\n /**\n * Helper method to create a list of ScheduleEvents from a database cursor\n *\n * @param cursor\n * @return List<ScheduleEvent>\n */\n private List<ScheduleEvent> extractScheduleEventsFromCursor(Cursor cursor) {\n ArrayList<ScheduleEvent> scheduleEvents = null;\n\n if (cursor.getCount() > 0) {\n cursor.moveToFirst();\n\n scheduleEvents = new ArrayList<ScheduleEvent>();\n\n while (!cursor.isAfterLast()) {\n\n // Create the event\n Calendar alarmTime = Calendar.getInstance();\n alarmTime.setTimeInMillis(cursor.getLong(cursor.getColumnIndex(EVENT_ALARM_TIME)) * 1000);\n Event event = new Event(cursor.getLong(cursor.getColumnIndex(EVENT_SCHEDULE_ID)),\n alarmTime,\n cursor.getString(cursor.getColumnIndex(EVENT_STATE)));\n event.setId(cursor.getLong(cursor.getColumnIndex(EVENT_ID)));\n\n // Create the schedule\n Calendar startTime = Calendar.getInstance();\n startTime.setTimeInMillis(cursor.getLong(cursor.getColumnIndex(SCHEDULE_START_TIME)) * 1000);\n Schedule schedule = new Schedule(startTime,\n cursor.getInt(cursor.getColumnIndex(SCHEDULE_DURATION)),\n cursor.getInt(cursor.getColumnIndex(SCHEDULE_REPEAT_TYPE)),\n cursor.getString(cursor.getColumnIndex(SCHEDULE_TAG)));\n schedule.setId(cursor.getLong(cursor.getColumnIndex(EVENT_SCHEDULE_ID)));\n schedule.setState(cursor.getString(cursor.getColumnIndex(SCHEDULE_STATE)));\n schedule.setGroupId(cursor.getLong(cursor.getColumnIndex(SCHEDULE_GROUP_ID)));\n\n scheduleEvents.add(new ScheduleEvent(schedule, event));\n\n cursor.moveToNext();\n }\n }\n\n return scheduleEvents;\n }\n\n}", "public class Event {\n private long m_id;\n private long m_scheduleID;\n private Calendar m_alarmTime;\n private String m_state;\n\n public Event(long scheduleID, Calendar alarmTime, String state) {\n m_scheduleID = scheduleID;\n m_alarmTime = alarmTime;\n m_state = state;\n m_id = 0;\n }\n\n public long getId() {\n return m_id;\n }\n\n public void setId(long id) {\n m_id = id;\n }\n\n public long getScheduleID() {\n return m_scheduleID;\n }\n\n public void setScheduleID(long scheduleID) {\n m_scheduleID = scheduleID;\n }\n\n public Calendar getAlarmTime() {\n return m_alarmTime;\n }\n\n public void setAlarmTime(Calendar alarmTime) {\n m_alarmTime = alarmTime;\n }\n\n public String getState() {\n return m_state;\n }\n\n public void setState(String state) {\n m_state = state;\n }\n}", "public class Schedule implements ScheduleState {\n private long m_id;\n private Calendar m_startTime;\n private int m_duration; // In seconds\n private int m_repeatType;\n private String m_tag;\n private String m_state;\n\tprivate boolean m_disabled;\n\tprivate Long m_groupId;\n\tprivate ScheduleGroup m_group;\n\n public Schedule(Calendar startTime, int duration, int repeatType, String tag) {\n m_startTime = startTime;\n m_duration = duration;\n m_repeatType = repeatType;\n m_tag = tag;\n m_id = 0;\n\t m_disabled = false;\n\t m_groupId = null;\n\t m_group = null;\n }\n\n\n\t// Implementing the ScheduleState interface\n\t@Override\n\tpublic long getScheduleId() {\n\t\treturn m_id;\n\t}\n\n\t@Override\n\tpublic Calendar getStartTime() {\n\t\treturn m_startTime;\n\t}\n\n\t@Override\n\tpublic int getDuration() {\n\t\treturn m_duration;\n\t}\n\n\t@Override\n\tpublic int getRepeatType() {\n\t\treturn m_repeatType;\n\t}\n\n\t@Override\n\tpublic String getTag() {\n\t\treturn m_tag;\n\t}\n\n\t@Override\n\tpublic String getState() {\n\t\treturn m_state;\n\t}\n\n\t@Override\n\tpublic boolean isDisabled() {\n\t\treturn m_disabled;\n\t}\n\n\t@Override\n\tpublic String getGroupTag() {\n\t\tif (getGroup() != null) {\n\t\t\treturn getGroup().getTag();\n\t\t}\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic boolean isGroupEnabled() {\n\t\tif (getGroup() != null) {\n\t\t\treturn getGroup().isEnabled();\n\t\t}\n\n\t\t// If a group is not found, this is not part of a group so return true\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String getGroupState() {\n\t\tif (getGroup() != null) {\n\t\t\treturn getGroup().getOverallState();\n\t\t}\n\t\treturn null;\n\t}\n\n\t// Other getters and setters\n\tpublic long getId() {\n return m_id;\n }\n\n\tpublic Long getGroupId() {\n\t\treturn m_groupId;\n\t}\n\n public void setId(long id) {\n m_id = id;\n }\n\n public void setStartTime(Calendar startTime) {\n m_startTime = startTime;\n }\n\n public void setDuration(int duration) {\n m_duration = duration;\n }\n\n public void setRepeatType(int repeatType) {\n m_repeatType = repeatType;\n }\n\n public void setTag(String tag) {\n m_tag = tag;\n }\n\n public void setState(String state) {\n\t m_state = state;\n }\n\n\tpublic void setDisabled(boolean disabled) {\n\t\tm_disabled = disabled;\n\t}\n\n\tpublic void setGroupId(Long groupId) {\n\t\tm_groupId = groupId;\n\t}\n\n\tprivate ScheduleGroup getGroup() {\n\t\t// For this call, the precondition is that the SAManager class has been initialized.\n\t\t// That being the case, the SAMSQLiteHelper singleton has also been created and it hold\n\t\t// a valid context object. Passing in null to get an instance will be fine here.\n\t\tif (m_group == null && m_groupId != null && m_groupId > 0) {\n\t\t\tm_group = SAMSQLiteHelper.getInstance(null).getScheduleGroupById(m_groupId);\n\t\t}\n\t\treturn m_group;\n\t}\n}", "public class ScheduleGroup {\n\tprivate long m_id;\n\tprivate String m_tag;\n\tprivate boolean m_enabled;\n\tprivate String m_overallState;\n\n\n\tpublic ScheduleGroup(String tag, boolean enabled) {\n\t\tm_tag = tag;\n\t\tm_enabled = enabled;\n\t}\n\n\n\tpublic String getTag() {\n\t\treturn m_tag;\n\t}\n\n\tpublic void setTag(String tag) {\n\t\tm_tag = tag;\n\t}\n\n\tpublic boolean isEnabled() {\n\t\treturn m_enabled;\n\t}\n\n\tpublic void setEnabled(boolean enabled) {\n\t\tm_enabled = enabled;\n\t}\n\n\tpublic long getId() {\n\n\t\treturn m_id;\n\t}\n\n\tpublic void setId(long id) {\n\t\tm_id = id;\n\t}\n\n\tpublic void setOverallState(String overallState) {\n\t\tm_overallState = overallState;\n\t}\n\n\tpublic String getOverallState() {\n\t\treturn m_overallState;\n\t}\n\n}", "public class ScheduleAndEventsToAdd {\n\tpublic Schedule m_schedule;\n\tpublic List<Event> m_events;\n\tpublic boolean m_newSchedule;\n\tpublic long m_addedScheduleId;\n\n\tpublic ScheduleAndEventsToAdd(Schedule schedule, List<Event> events, boolean newSchedule) {\n\t\tm_schedule = schedule;\n\t\tm_events = events;\n\t\tm_newSchedule = newSchedule;\n\t\tm_addedScheduleId = -1;\n\t}\n}", "public class ScheduleEvent {\n private Schedule m_schedule;\n private Event m_event;\n\n public ScheduleEvent(Schedule schedule, Event event) {\n m_schedule = schedule;\n m_event = event;\n }\n\n public long getScheduleId() {\n return m_schedule.getId();\n }\n\n public Calendar getStartTime() {\n return m_schedule.getStartTime();\n }\n\n public String getTag() {\n return m_schedule.getTag();\n }\n\n public int getDuration() {\n return m_schedule.getDuration();\n }\n\n public int getRepeatType() {\n return m_schedule.getRepeatType();\n }\n\n public String getEventState() {\n return m_event.getState();\n }\n\n\tpublic String getScheduleState() {\n\t\treturn m_schedule.getState();\n\t}\n\n\tpublic boolean willRepeat() {\n // Enhancement. Logic can be more complicated in case we implement schedules that repeat\n // for a specific number of times e.g. 5 times.\n return m_schedule.getRepeatType() != SAManager.REPEAT_TYPE_NONE;\n }\n\n public Event getEvent() {\n return m_event;\n }\n\n public Schedule getSchedule() {\n return m_schedule;\n }\n}" ]
import com.scalior.schedulealarmmanager.model.Event; import com.scalior.schedulealarmmanager.model.Schedule; import com.scalior.schedulealarmmanager.model.ScheduleGroup; import com.scalior.schedulealarmmanager.modelholder.ScheduleAndEventsToAdd; import com.scalior.schedulealarmmanager.modelholder.ScheduleEvent; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.util.SparseArray; import com.scalior.schedulealarmmanager.database.SAMSQLiteHelper;
/* The MIT License (MIT) * * Copyright (c) 2014 Scalior, Inc * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Author: Eyong Nsoesie ([email protected]) * Date: 10/05/2014 */ package com.scalior.schedulealarmmanager; //import android.content.pm.PackageInfo; //import android.content.pm.PackageManager.NameNotFoundException; /** * This class serves as an interface to manage schedule alarms. * */ public class SAManager { public static final int REPEAT_TYPE_HOURLY = 1; public static final int REPEAT_TYPE_DAILY = 2; public static final int REPEAT_TYPE_WEEKLY = 3; public static final int REPEAT_TYPE_MONTHLY = 4; public static final int REPEAT_TYPE_YEARLY = 5; public static final int REPEAT_TYPE_NONE = 6; public static final String STATE_ON = "ON"; public static final String STATE_OFF = "OFF"; private static SAManager m_instance; private Context m_context; private boolean m_initialized; private SAMSQLiteHelper m_dbHelper; private AlarmProcessingUtil m_alarmProcessor; private String m_versionName; /** * Description: * Get the singleton instance of the Schedule Alarm Manager * If it has already been constructed, the passed in parameters have no effect * @param p_context: The application context * @return The singleton instance */ public static SAManager getInstance(Context p_context) { if (m_instance == null ) { m_instance = new SAManager(p_context); } return m_instance; } private SAManager(Context p_context) { m_context = p_context; m_dbHelper = SAMSQLiteHelper.getInstance(m_context); m_alarmProcessor = AlarmProcessingUtil.getInstance(m_context); m_initialized = false; } /** * Description: * Initialize the Schedule Alarm Manager * @return boolean - true if successful, false other wise */ public boolean init() { m_alarmProcessor.updateScheduleStates(null); m_initialized = true; return true; } /** * Callback accessor */ public SAMCallback getCallback() { return m_alarmProcessor.getSamCallback(); } /** * Description: * This method sets the callback. * * @param callback - The callback instance. Once set can't be changed * @param replace - If true, a current callback will be replaced with this one * If false and a callback is already set, the new callback will * be ignored. */ public void setCallback(SAMCallback callback, boolean replace) { m_alarmProcessor.setSamCallback(callback, replace); } /** * Description: * Adds a schedule * @param startTime - When the schedule starts. It can't be more than 24 hours in the past. * @param duration - The duration of the schedule in minutes * @param repeatType - One of the repeat type constants * @param tag - A user specific tag identifying the schedule. This will be passed back to the * user when the schedule's alarm is triggered * @param groupTag - A user specific tag identifying the group that this schedule belongs to. * This can be null. * @return long - the added schedule's id if successful, -1 otherwise * Do not count on this id to persist application restarts. Use the tag * to identify schedules across restarts. */ public long addSchedule(Calendar startTime, int duration, int repeatType, String tag, String groupTag) throws IllegalArgumentException, IllegalStateException { if (!m_initialized) { throw new IllegalStateException("SAManager not initialized"); } Calendar currTime = Calendar.getInstance(); // Check for validity of parameters if (duration <= 0 || ((currTime.getTimeInMillis() - startTime.getTimeInMillis()) > AlarmProcessingUtil.DAY_MS) || // Start time shouldn't be more than 24 hours in the past !isRepeatTypeValid(repeatType) || tag == null || tag.isEmpty()) { throw new IllegalArgumentException(); }
ScheduleGroup group = null;
3
openstack/sahara-extra
hadoop-swiftfs/src/test/java/org/apache/hadoop/fs/swift/TestSwiftFileSystemBasicOps.java
[ "public class SwiftNativeFileSystem extends FileSystem {\n\n /** filesystem prefix: {@value} */\n public static final String SWIFT = \"swift\";\n private static final Log LOG =\n LogFactory.getLog(SwiftNativeFileSystem.class);\n\n /**\n * path to user work directory for storing temporary files\n */\n private Path workingDir;\n\n /**\n * Swift URI\n */\n private URI uri;\n\n /**\n * reference to swiftFileSystemStore\n */\n private SwiftNativeFileSystemStore store;\n\n /**\n * Default constructor for Hadoop\n */\n public SwiftNativeFileSystem() {\n // set client in initialize()\n }\n\n /**\n * This constructor used for testing purposes\n */\n public SwiftNativeFileSystem(SwiftNativeFileSystemStore store) {\n this.store = store;\n }\n\n /**\n * This is for testing\n * @return the inner store class\n */\n public SwiftNativeFileSystemStore getStore() {\n return store;\n }\n\n// @Override\n public String getScheme() {\n return SWIFT;\n }\n\n /**\n * default class initialization\n *\n * @param fsuri path to Swift\n * @param conf Hadoop configuration\n * @throws IOException\n */\n @Override\n public void initialize(URI fsuri, Configuration conf) throws IOException {\n super.initialize(fsuri, conf);\n\n setConf(conf);\n if (store == null) {\n store = new SwiftNativeFileSystemStore();\n }\n this.uri = fsuri;\n String username = System.getProperty(\"user.name\");\n this.workingDir = new Path(\"/user\", username)\n .makeQualified(uri, new Path(username));\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Initializing SwiftNativeFileSystem against URI \" + uri\n + \" and working dir \" + workingDir);\n }\n store.initialize(uri, conf);\n LOG.debug(\"SwiftFileSystem initialized\");\n }\n\n /**\n * @return path to Swift\n */\n @Override\n public URI getUri() {\n\n return uri;\n }\n\n @Override\n public String toString() {\n return \"Swift FileSystem \" + store;\n }\n\n /**\n * Path to user working directory\n *\n * @return Hadoop path\n */\n @Override\n public Path getWorkingDirectory() {\n return workingDir;\n }\n\n @Override\n public String getCanonicalServiceName() {\n return null;\n }\n\n /**\n * @param dir user working directory\n */\n @Override\n public void setWorkingDirectory(Path dir) {\n workingDir = makeAbsolute(dir);\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"SwiftFileSystem.setWorkingDirectory to \" + dir);\n }\n }\n\n /**\n * Return a file status object that represents the path.\n *\n * @param path The path we want information from\n * @return a FileStatus object\n */\n @Override\n public FileStatus getFileStatus(Path path) throws IOException {\n Path absolutePath = makeAbsolute(path);\n return store.getObjectMetadata(absolutePath);\n }\n\n /**\n * The blocksize of this filesystem is set by the property\n * SwiftProtocolConstants.SWIFT_BLOCKSIZE;the default is the value of\n * SwiftProtocolConstants.DEFAULT_SWIFT_BLOCKSIZE;\n * @return the blocksize for this FS.\n */\n @Override\n public long getDefaultBlockSize() {\n return store.getBlocksize();\n }\n\n /**\n * The blocksize for this filesystem.\n * @see #getDefaultBlockSize()\n * @param f path of file\n * @return the blocksize for the path\n */\n @Override\n public long getDefaultBlockSize(Path f) {\n return store.getBlocksize();\n }\n\n @Override\n public long getBlockSize(Path path) throws IOException {\n return store.getBlocksize();\n }\n\n /**\n * Return an array containing hostnames, offset and size of\n * portions of the given file. For a nonexistent\n * file or regions, null will be returned.\n * <p/>\n * This call is most helpful with DFS, where it returns\n * hostnames of machines that contain the given file.\n * <p/>\n * The FileSystem will simply return an elt containing 'localhost'.\n */\n @Override\n public BlockLocation[] getFileBlockLocations(FileStatus file,\n long start,\n long len) throws IOException {\n //argument checks\n if (file == null) {\n return null;\n }\n if (file.isDir()) {\n return new BlockLocation[0];\n }\n\n if (start < 0 || len < 0) {\n throw new IllegalArgumentException(\"Negative start or len parameter\" +\n \" to getFileBlockLocations\");\n }\n if (file.getLen() <= start) {\n return new BlockLocation[0];\n }\n\n // Check if requested file in Swift is more than 5Gb. In this case\n // each block has its own location -which may be determinable\n // from the Swift client API, depending on the remote server\n final FileStatus[] listOfFileBlocks;\n if (file instanceof SwiftFileStatus && ((SwiftFileStatus)file).isDLO()) {\n listOfFileBlocks = store.listSegments(file, true);\n } else {\n listOfFileBlocks = null;\n }\n\n List<URI> locations = new ArrayList<URI>();\n if (listOfFileBlocks != null && listOfFileBlocks.length > 1) {\n for (FileStatus fileStatus : listOfFileBlocks) {\n if (SwiftObjectPath.fromPath(uri, fileStatus.getPath())\n .equals(SwiftObjectPath.fromPath(uri, file.getPath()))) {\n continue;\n }\n locations.addAll(store.getObjectLocation(fileStatus.getPath()));\n }\n } else {\n locations = store.getObjectLocation(file.getPath());\n }\n\n if (locations.isEmpty()) {\n LOG.debug(\"No locations returned for \" + file.getPath());\n //no locations were returned for the object\n //fall back to the superclass\n\n String[] name = {SwiftProtocolConstants.BLOCK_LOCATION};\n String[] host = { \"localhost\" };\n String[] topology={SwiftProtocolConstants.TOPOLOGY_PATH};\n return new BlockLocation[] {\n new BlockLocation(name, host, topology,0, file.getLen())\n };\n }\n\n final String[] names = new String[locations.size()];\n final String[] hosts = new String[locations.size()];\n int i = 0;\n for (URI location : locations) {\n hosts[i] = location.getHost();\n names[i] = location.getAuthority();\n i++;\n }\n return new BlockLocation[]{\n new BlockLocation(names, hosts, 0, file.getLen())\n };\n }\n\n /**\n * Create the parent directories.\n * As an optimization, the entire hierarchy of parent\n * directories is <i>Not</i> polled. Instead\n * the tree is walked up from the last to the first,\n * creating directories until one that exists is found.\n *\n * This strategy means if a file is created in an existing directory,\n * one quick poll sufficies.\n *\n * There is a big assumption here: that all parent directories of an existing\n * directory also exists.\n * @param path path to create.\n * @param permission to apply to files\n * @return true if the operation was successful\n * @throws IOException on a problem\n */\n @Override\n public boolean mkdirs(Path path, FsPermission permission) throws IOException {\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"SwiftFileSystem.mkdirs: \" + path);\n }\n Path directory = makeAbsolute(path);\n\n //build a list of paths to create\n List<Path> paths = new ArrayList<Path>();\n while (shouldCreate(directory)) {\n //this directory needs creation, add to the list\n paths.add(0, directory);\n //now see if the parent needs to be created\n directory = directory.getParent();\n }\n\n //go through the list of directories to create\n for (Path p : paths) {\n if (isNotRoot(p)) {\n //perform a mkdir operation without any polling of\n //the far end first\n forceMkdir(p);\n }\n }\n\n //if an exception was not thrown, this operation is considered\n //a success\n return true;\n }\n\n private boolean isNotRoot(Path absolutePath) {\n return !isRoot(absolutePath);\n }\n\n private boolean isRoot(Path absolutePath) {\n return absolutePath.getParent() == null;\n }\n\n /**\n * internal implementation of directory creation.\n *\n * @param path path to file\n * @return boolean file is created; false: no need to create\n * @throws IOException if specified path is file instead of directory\n */\n private boolean mkdir(Path path) throws IOException {\n Path directory = makeAbsolute(path);\n boolean shouldCreate = shouldCreate(directory);\n if (shouldCreate) {\n forceMkdir(directory);\n }\n return shouldCreate;\n }\n\n /**\n * Should mkdir create this directory?\n * If the directory is root : false\n * If the entry exists and is a directory: false\n * If the entry exists and is a file: exception\n * else: true\n * @param directory path to query\n * @return true iff the directory should be created\n * @throws IOException IO problems\n * @throws SwiftNotDirectoryException if the path references a file\n */\n private boolean shouldCreate(Path directory) throws IOException {\n FileStatus fileStatus;\n boolean shouldCreate;\n if (isRoot(directory)) {\n //its the base dir, bail out immediately\n return false;\n }\n try {\n //find out about the path\n fileStatus = getFileStatus(directory);\n\n if (!fileStatus.isDir()) {\n //if it's a file, raise an error\n throw new SwiftNotDirectoryException(directory,\n String.format(\": can't mkdir since it exists and is not a directory: %s\",\n fileStatus));\n } else {\n //path exists, and it is a directory\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"skipping mkdir(\" + directory + \") as it exists already\");\n }\n shouldCreate = false;\n }\n } catch (FileNotFoundException e) {\n shouldCreate = true;\n }\n return shouldCreate;\n }\n\n /**\n * mkdir of a directory -irrespective of what was there underneath.\n * There are no checks for the directory existing, there not\n * being a path there, etc. etc. Those are assumed to have\n * taken place already\n * @param absolutePath path to create\n * @throws IOException IO problems\n */\n private void forceMkdir(Path absolutePath) throws IOException {\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Making dir '\" + absolutePath + \"' in Swift\");\n }\n //file is not found: it must be created\n store.createDirectory(absolutePath);\n }\n\n /**\n * List the statuses of the files/directories in the given path if the path is\n * a directory.\n *\n * @param path given path\n * @return the statuses of the files/directories in the given path\n * @throws IOException\n */\n @Override\n public FileStatus[] listStatus(Path path) throws IOException {\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"SwiftFileSystem.listStatus for: \" + path);\n }\n Path absolutePath = makeAbsolute(path);\n FileStatus status = getFileStatus(absolutePath);\n if (status.isDir()) {\n return store.listSubPaths(absolutePath, false, true);\n } else {\n return new FileStatus[] {status};\n }\n }\n\n /**\n * This optional operation is not supported\n */\n @Override\n public FSDataOutputStream append(Path f, int bufferSize, Progressable progress)\n throws IOException {\n LOG.debug(\"SwiftFileSystem.append\");\n throw new SwiftUnsupportedFeatureException(\"Not supported: append()\");\n }\n\n /**\n * @param permission Currently ignored.\n */\n @Override\n public FSDataOutputStream create(Path file, FsPermission permission,\n boolean overwrite, int bufferSize,\n short replication, long blockSize,\n Progressable progress)\n throws IOException {\n LOG.debug(\"SwiftFileSystem.create\");\n\n FileStatus fileStatus = null;\n Path absolutePath = makeAbsolute(file);\n try {\n fileStatus = getFileStatus(absolutePath);\n } catch (FileNotFoundException e) {\n //the file isn't there.\n }\n\n if (fileStatus != null) {\n //the path exists -action depends on whether or not it is a directory,\n //and what the overwrite policy is.\n\n //What is clear at this point is that if the entry exists, there's\n //no need to bother creating any parent entries\n if (fileStatus.isDir()) {\n //here someone is trying to create a file over a directory\n\n/* we can't throw an exception here as there is no easy way to distinguish\n a file from the dir\n\n throw new SwiftPathExistsException(\"Cannot create a file over a directory:\"\n + file);\n */\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"Overwriting either an empty file or a directory\");\n }\n }\n if (overwrite) {\n //overwrite set -> delete the object.\n store.delete(absolutePath, true);\n } else {\n throw new SwiftPathExistsException(\"Path exists: \" + file);\n }\n } else {\n // destination does not exist -trigger creation of the parent\n Path parent = file.getParent();\n if (parent != null) {\n if (!mkdirs(parent)) {\n throw new SwiftOperationFailedException(\n \"Mkdirs failed to create \" + parent);\n }\n }\n }\n\n SwiftNativeOutputStream out = createSwiftOutputStream(file);\n return new FSDataOutputStream(out, statistics);\n }\n\n /**\n * Create the swift output stream\n * @param path path to write to\n * @return the new file\n * @throws IOException\n */\n protected SwiftNativeOutputStream createSwiftOutputStream(Path path) throws\n IOException {\n long partSizeKB = getStore().getPartsizeKB();\n return new SwiftNativeOutputStream(getConf(),\n getStore(),\n path.toUri().toString(),\n partSizeKB);\n }\n\n /**\n * Opens an FSDataInputStream at the indicated Path.\n *\n * @param path the file name to open\n * @param bufferSize the size of the buffer to be used.\n * @return the input stream\n * @throws FileNotFoundException if the file is not found\n * @throws IOException any IO problem\n */\n @Override\n public FSDataInputStream open(Path path, int bufferSize) throws IOException {\n int bufferSizeKB = getStore().getBufferSizeKB();\n long readBlockSize = bufferSizeKB * 1024L;\n return open(path, bufferSize, readBlockSize);\n }\n\n /**\n * Low-level operation to also set the block size for this operation\n * @param path the file name to open\n * @param bufferSize the size of the buffer to be used.\n * @param readBlockSize how big should the read blockk/buffer size be?\n * @return the input stream\n * @throws FileNotFoundException if the file is not found\n * @throws IOException any IO problem\n */\n public FSDataInputStream open(Path path,\n int bufferSize,\n long readBlockSize) throws IOException {\n if (readBlockSize <= 0) {\n throw new SwiftConfigurationException(\"Bad remote buffer size\");\n }\n Path absolutePath = makeAbsolute(path);\n return new FSDataInputStream(\n new StrictBufferedFSInputStream(\n new SwiftNativeInputStream(store,\n statistics,\n absolutePath,\n readBlockSize),\n bufferSize));\n }\n\n /**\n * Renames Path src to Path dst. On swift this uses copy-and-delete\n * and <i>is not atomic</i>.\n *\n * @param src path\n * @param dst path\n * @return true if directory renamed, false otherwise\n * @throws IOException on problems\n */\n @Override\n public boolean rename(Path src, Path dst) throws IOException {\n\n try {\n store.rename(makeAbsolute(src), makeAbsolute(dst));\n //success\n return true;\n } catch (SwiftOperationFailedException e) {\n //downgrade to a failure\n return false;\n } catch (FileNotFoundException e) {\n //downgrade to a failure\n return false;\n }\n }\n\n\n /**\n * Delete a file or directory\n *\n * @param path the path to delete.\n * @param recursive if path is a directory and set to\n * true, the directory is deleted else throws an exception if the\n * directory is not empty\n * case of a file the recursive can be set to either true or false.\n * @return true if the object was deleted\n * @throws IOException IO problems\n */\n @Override\n public boolean delete(Path path, boolean recursive) throws IOException {\n try {\n return store.delete(path, recursive);\n } catch (FileNotFoundException e) {\n //base path was not found.\n return false;\n }\n }\n\n /**\n * Delete a file.\n * This method is abstract in Hadoop 1.x; in 2.x+ it is non-abstract\n * and deprecated\n */\n @Override\n public boolean delete(Path f) throws IOException {\n return delete(f, true);\n }\n\n /**\n * Makes path absolute\n *\n * @param path path to file\n * @return absolute path\n */\n protected Path makeAbsolute(Path path) {\n if (path.isAbsolute()) {\n return path;\n }\n return new Path(workingDir, path);\n }\n\n /**\n * Get the current operation statistics\n * @return a snapshot of the statistics\n */\n public List<DurationStats> getOperationStatistics() {\n return store.getOperationStatistics();\n }\n\n /**\n * Low level method to do a deep listing of all entries, not stopping\n * at the next directory entry. This is to let tests be confident that\n * recursive deletes &c really are working.\n * @param path path to recurse down\n * @param newest ask for the newest data, potentially slower than not.\n * @return a potentially empty array of file status\n * @throws IOException any problem\n */\n @InterfaceAudience.Private\n public FileStatus[] listRawFileStatus(Path path, boolean newest) throws IOException {\n return store.listSubPaths(makeAbsolute(path), true, newest);\n }\n\n /**\n * Get the number of partitions written by an output stream\n * This is for testing\n * @param outputStream output stream\n * @return the #of partitions written by that stream\n */\n @InterfaceAudience.Private\n public static int getPartitionsWritten(FSDataOutputStream outputStream) {\n SwiftNativeOutputStream snos = getSwiftNativeOutputStream(outputStream);\n return snos.getPartitionsWritten();\n }\n\n private static SwiftNativeOutputStream getSwiftNativeOutputStream(\n FSDataOutputStream outputStream) {\n OutputStream wrappedStream = outputStream.getWrappedStream();\n return (SwiftNativeOutputStream) wrappedStream;\n }\n\n /**\n * Get the size of partitions written by an output stream\n * This is for testing\n *\n * @param outputStream output stream\n * @return partition size in bytes\n */\n @InterfaceAudience.Private\n public static long getPartitionSize(FSDataOutputStream outputStream) {\n SwiftNativeOutputStream snos = getSwiftNativeOutputStream(outputStream);\n return snos.getFilePartSize();\n }\n\n /**\n * Get the the number of bytes written to an output stream\n * This is for testing\n *\n * @param outputStream output stream\n * @return partition size in bytes\n */\n @InterfaceAudience.Private\n public static long getBytesWritten(FSDataOutputStream outputStream) {\n SwiftNativeOutputStream snos = getSwiftNativeOutputStream(outputStream);\n return snos.getBytesWritten();\n }\n\n /**\n * Get the the number of bytes uploaded by an output stream\n * to the swift cluster.\n * This is for testing\n *\n * @param outputStream output stream\n * @return partition size in bytes\n */\n @InterfaceAudience.Private\n public static long getBytesUploaded(FSDataOutputStream outputStream) {\n SwiftNativeOutputStream snos = getSwiftNativeOutputStream(outputStream);\n return snos.getBytesUploaded();\n }\n\n}", "public class SwiftTestUtils extends org.junit.Assert {\n\n private static final Log LOG =\n LogFactory.getLog(SwiftTestUtils.class);\n\n public static final String TEST_FS_SWIFT = \"test.fs.swift.name\";\n public static final String IO_FILE_BUFFER_SIZE = \"io.file.buffer.size\";\n\n /**\n * Get the test URI\n * @param conf configuration\n * @throws SwiftConfigurationException missing parameter or bad URI\n */\n public static URI getServiceURI(Configuration conf) throws\n SwiftConfigurationException {\n String instance = conf.get(TEST_FS_SWIFT);\n if (instance == null) {\n throw new SwiftConfigurationException(\n \"Missing configuration entry \" + TEST_FS_SWIFT);\n }\n try {\n return new URI(instance);\n } catch (URISyntaxException e) {\n throw new SwiftConfigurationException(\"Bad URI: \" + instance);\n }\n }\n\n public static boolean hasServiceURI(Configuration conf) {\n String instance = conf.get(TEST_FS_SWIFT);\n return instance != null;\n }\n\n /**\n * Assert that a property in the property set matches the expected value\n * @param props property set\n * @param key property name\n * @param expected expected value. If null, the property must not be in the set\n */\n public static void assertPropertyEquals(Properties props,\n String key,\n String expected) {\n String val = props.getProperty(key);\n if (expected == null) {\n assertNull(\"Non null property \" + key + \" = \" + val, val);\n } else {\n assertEquals(\"property \" + key + \" = \" + val,\n expected,\n val);\n }\n }\n\n /**\n *\n * Write a file and read it in, validating the result. Optional flags control\n * whether file overwrite operations should be enabled, and whether the\n * file should be deleted afterwards.\n *\n * If there is a mismatch between what was written and what was expected,\n * a small range of bytes either side of the first error are logged to aid\n * diagnosing what problem occurred -whether it was a previous file\n * or a corrupting of the current file. This assumes that two\n * sequential runs to the same path use datasets with different character\n * moduli.\n *\n * @param fs filesystem\n * @param path path to write to\n * @param len length of data\n * @param overwrite should the create option allow overwrites?\n * @param delete should the file be deleted afterwards? -with a verification\n * that it worked. Deletion is not attempted if an assertion has failed\n * earlier -it is not in a <code>finally{}</code> block.\n * @throws IOException IO problems\n */\n public static void writeAndRead(FileSystem fs,\n Path path,\n byte[] src,\n int len,\n int blocksize,\n boolean overwrite,\n boolean delete) throws IOException {\n fs.mkdirs(path.getParent());\n\n writeDataset(fs, path, src, len, blocksize, overwrite);\n\n byte[] dest = readDataset(fs, path, len);\n\n compareByteArrays(src, dest, len);\n\n if (delete) {\n boolean deleted = fs.delete(path, false);\n assertTrue(\"Deleted\", deleted);\n assertPathDoesNotExist(fs, \"Cleanup failed\", path);\n }\n }\n\n /**\n * Write a file.\n * Optional flags control\n * whether file overwrite operations should be enabled\n * @param fs filesystem\n * @param path path to write to\n * @param len length of data\n * @param overwrite should the create option allow overwrites?\n * @throws IOException IO problems\n */\n public static void writeDataset(FileSystem fs,\n Path path,\n byte[] src,\n int len,\n int blocksize,\n boolean overwrite) throws IOException {\n assertTrue(\n \"Not enough data in source array to write \" + len + \" bytes\",\n src.length >= len);\n FSDataOutputStream out = fs.create(path,\n overwrite,\n fs.getConf()\n .getInt(IO_FILE_BUFFER_SIZE,\n 4096),\n (short) 1,\n blocksize);\n out.write(src, 0, len);\n out.close();\n assertFileHasLength(fs, path, len);\n }\n\n /**\n * Read the file and convert to a byte dataaset\n * @param fs filesystem\n * @param path path to read from\n * @param len length of data to read\n * @return the bytes\n * @throws IOException IO problems\n */\n public static byte[] readDataset(FileSystem fs, Path path, int len)\n throws IOException {\n FSDataInputStream in = fs.open(path);\n byte[] dest = new byte[len];\n try {\n in.readFully(0, dest);\n } finally {\n in.close();\n }\n return dest;\n }\n\n /**\n * Assert that tthe array src[0..len] and dest[] are equal\n * @param src source data\n * @param dest actual\n * @param len length of bytes to compare\n */\n public static void compareByteArrays(byte[] src,\n byte[] dest,\n int len) {\n assertEquals(\"Number of bytes read != number written\",\n len, dest.length);\n int errors = 0;\n int first_error_byte = -1;\n for (int i = 0; i < len; i++) {\n if (src[i] != dest[i]) {\n if (errors == 0) {\n first_error_byte = i;\n }\n errors++;\n }\n }\n\n if (errors > 0) {\n String message = String.format(\" %d errors in file of length %d\",\n errors, len);\n LOG.warn(message);\n // the range either side of the first error to print\n // this is a purely arbitrary number, to aid user debugging\n final int overlap = 10;\n for (int i = Math.max(0, first_error_byte - overlap);\n i < Math.min(first_error_byte + overlap, len);\n i++) {\n byte actual = dest[i];\n byte expected = src[i];\n String letter = toChar(actual);\n String line = String.format(\"[%04d] %2x %s\\n\", i, actual, letter);\n if (expected != actual) {\n line = String.format(\"[%04d] %2x %s -expected %2x %s\\n\",\n i,\n actual,\n letter,\n expected,\n toChar(expected));\n }\n LOG.warn(line);\n }\n fail(message);\n }\n }\n\n /**\n * Convert a byte to a character for printing. If the\n * byte value is < 32 -and hence unprintable- the byte is\n * returned as a two digit hex value\n * @param b byte\n * @return the printable character string\n */\n public static String toChar(byte b) {\n if (b >= 0x20) {\n return Character.toString((char) b);\n } else {\n return String.format(\"%02x\", b);\n }\n }\n\n public static String toChar(byte[] buffer) {\n StringBuilder builder = new StringBuilder(buffer.length);\n for (byte b : buffer) {\n builder.append(toChar(b));\n }\n return builder.toString();\n }\n\n public static byte[] toAsciiByteArray(String s) {\n char[] chars = s.toCharArray();\n int len = chars.length;\n byte[] buffer = new byte[len];\n for (int i = 0; i < len; i++) {\n buffer[i] = (byte) (chars[i] & 0xff);\n }\n return buffer;\n }\n\n public static void cleanupInTeardown(FileSystem fileSystem,\n String cleanupPath) {\n cleanup(\"TEARDOWN\", fileSystem, cleanupPath);\n }\n\n public static void cleanup(String action,\n FileSystem fileSystem,\n String cleanupPath) {\n noteAction(action);\n try {\n if (fileSystem != null) {\n fileSystem.delete(new Path(cleanupPath).makeQualified(fileSystem),\n true);\n }\n } catch (Exception e) {\n LOG.error(\"Error deleting in \"+ action + \" - \" + cleanupPath + \": \" + e, e);\n }\n }\n\n public static void noteAction(String action) {\n if (LOG.isDebugEnabled()) {\n LOG.debug(\"============== \"+ action +\" =============\");\n }\n }\n\n /**\n * downgrade a failure to a message and a warning, then an\n * exception for the Junit test runner to mark as failed\n * @param message text message\n * @param failure what failed\n * @throws AssumptionViolatedException always\n */\n public static void downgrade(String message, Throwable failure) {\n LOG.warn(\"Downgrading test \" + message, failure);\n AssumptionViolatedException ave =\n new AssumptionViolatedException(failure, null);\n throw ave;\n }\n\n /**\n * report an overridden test as unsupported\n * @param message message to use in the text\n * @throws AssumptionViolatedException always\n */\n public static void unsupported(String message) {\n throw new AssumptionViolatedException(message);\n }\n\n /**\n * report a test has been skipped for some reason\n * @param message message to use in the text\n * @throws AssumptionViolatedException always\n */\n public static void skip(String message) {\n throw new AssumptionViolatedException(message);\n }\n\n\n /**\n * Make an assertion about the length of a file\n * @param fs filesystem\n * @param path path of the file\n * @param expected expected length\n * @throws IOException on File IO problems\n */\n public static void assertFileHasLength(FileSystem fs, Path path,\n int expected) throws IOException {\n FileStatus status = fs.getFileStatus(path);\n assertEquals(\n \"Wrong file length of file \" + path + \" status: \" + status,\n expected,\n status.getLen());\n }\n\n /**\n * Assert that a path refers to a directory\n * @param fs filesystem\n * @param path path of the directory\n * @throws IOException on File IO problems\n */\n public static void assertIsDirectory(FileSystem fs,\n Path path) throws IOException {\n FileStatus fileStatus = fs.getFileStatus(path);\n assertIsDirectory(fileStatus);\n }\n\n /**\n * Assert that a path refers to a directory\n * @param fileStatus stats to check\n */\n public static void assertIsDirectory(FileStatus fileStatus) {\n assertTrue(\"Should be a dir -but isn't: \" + fileStatus,\n fileStatus.isDir());\n }\n\n /**\n * Write the text to a file, returning the converted byte array\n * for use in validating the round trip\n * @param fs filesystem\n * @param path path of file\n * @param text text to write\n * @param overwrite should the operation overwrite any existing file?\n * @return the read bytes\n * @throws IOException on IO problems\n */\n public static byte[] writeTextFile(FileSystem fs,\n Path path,\n String text,\n boolean overwrite) throws IOException {\n FSDataOutputStream stream = fs.create(path, overwrite);\n byte[] bytes = new byte[0];\n if (text != null) {\n bytes = toAsciiByteArray(text);\n stream.write(bytes);\n }\n stream.close();\n return bytes;\n }\n\n /**\n * Touch a file: fails if it is already there\n * @param fs filesystem\n * @param path path\n * @throws IOException IO problems\n */\n public static void touch(FileSystem fs,\n Path path) throws IOException {\n fs.delete(path, true);\n writeTextFile(fs, path, null, false);\n }\n\n public static void assertDeleted(FileSystem fs,\n Path file,\n boolean recursive) throws IOException {\n assertPathExists(fs, \"about to be deleted file\", file);\n boolean deleted = fs.delete(file, recursive);\n String dir = ls(fs, file.getParent());\n assertTrue(\"Delete failed on \" + file + \": \" + dir, deleted);\n assertPathDoesNotExist(fs, \"Deleted file\", file);\n }\n\n /**\n * Read in \"length\" bytes, convert to an ascii string\n * @param fs filesystem\n * @param path path to read\n * @param length #of bytes to read.\n * @return the bytes read and converted to a string\n * @throws IOException\n */\n public static String readBytesToString(FileSystem fs,\n Path path,\n int length) throws IOException {\n FSDataInputStream in = fs.open(path);\n try {\n byte[] buf = new byte[length];\n in.readFully(0, buf);\n return toChar(buf);\n } finally {\n in.close();\n }\n }\n\n public static String getDefaultWorkingDirectory() {\n return \"/user/\" + System.getProperty(\"user.name\");\n }\n\n public static String ls(FileSystem fileSystem, Path path) throws IOException {\n return SwiftUtils.ls(fileSystem, path);\n }\n\n public static String dumpStats(String pathname, FileStatus[] stats) {\n return pathname + SwiftUtils.fileStatsToString(stats,\"\\n\");\n }\n\n /**\n /**\n * Assert that a file exists and whose {@link FileStatus} entry\n * declares that this is a file and not a symlink or directory.\n * @param fileSystem filesystem to resolve path against\n * @param filename name of the file\n * @throws IOException IO problems during file operations\n */\n public static void assertIsFile(FileSystem fileSystem, Path filename) throws\n IOException {\n assertPathExists(fileSystem, \"Expected file\", filename);\n FileStatus status = fileSystem.getFileStatus(filename);\n String fileInfo = filename + \" \" + status;\n assertFalse(\"File claims to be a directory \" + fileInfo,\n status.isDir());\n/* disabled for Hadoop v1 compatibility\n assertFalse(\"File claims to be a symlink \" + fileInfo,\n status.isSymlink());\n*/\n }\n\n /**\n * Create a dataset for use in the tests; all data is in the range\n * base to (base+modulo-1) inclusive\n * @param len length of data\n * @param base base of the data\n * @param modulo the modulo\n * @return the newly generated dataset\n */\n public static byte[] dataset(int len, int base, int modulo) {\n byte[] dataset = new byte[len];\n for (int i = 0; i < len; i++) {\n dataset[i] = (byte) (base + (i % modulo));\n }\n return dataset;\n }\n\n /**\n * Assert that a path exists -but make no assertions as to the\n * type of that entry\n *\n * @param fileSystem filesystem to examine\n * @param message message to include in the assertion failure message\n * @param path path in the filesystem\n * @throws IOException IO problems\n */\n public static void assertPathExists(FileSystem fileSystem, String message,\n Path path) throws IOException {\n if (!fileSystem.exists(path)) {\n //failure, report it\n fail(message + \": not found \" + path + \" in \" + path.getParent());\n ls(fileSystem, path.getParent());\n }\n }\n\n /**\n * Assert that a path does not exist\n *\n * @param fileSystem filesystem to examine\n * @param message message to include in the assertion failure message\n * @param path path in the filesystem\n * @throws IOException IO problems\n */\n public static void assertPathDoesNotExist(FileSystem fileSystem,\n String message,\n Path path) throws IOException {\n try {\n FileStatus status = fileSystem.getFileStatus(path);\n fail(message + \": unexpectedly found \" + path + \" as \" + status);\n } catch (FileNotFoundException expected) {\n //this is expected\n\n }\n }\n\n\n /**\n * Assert that a FileSystem.listStatus on a dir finds the subdir/child entry\n * @param fs filesystem\n * @param dir directory to scan\n * @param subdir full path to look for\n * @throws IOException IO probles\n */\n public static void assertListStatusFinds(FileSystem fs,\n Path dir,\n Path subdir) throws IOException {\n FileStatus[] stats = fs.listStatus(dir);\n boolean found = false;\n StringBuilder builder = new StringBuilder();\n for (FileStatus stat : stats) {\n builder.append(stat.toString()).append('\\n');\n if (stat.getPath().equals(subdir)) {\n found = true;\n }\n }\n assertTrue(\"Path \" + subdir\n + \" not found in directory \" + dir + \":\" + builder,\n found);\n }\n\n}", "public static void assertFileHasLength(FileSystem fs, Path path,\n int expected) throws IOException {\n FileStatus status = fs.getFileStatus(path);\n assertEquals(\n \"Wrong file length of file \" + path + \" status: \" + status,\n expected,\n status.getLen());\n}", "public static void assertIsDirectory(FileSystem fs,\n Path path) throws IOException {\n FileStatus fileStatus = fs.getFileStatus(path);\n assertIsDirectory(fileStatus);\n}", "public static String readBytesToString(FileSystem fs,\n Path path,\n int length) throws IOException {\n FSDataInputStream in = fs.open(path);\n try {\n byte[] buf = new byte[length];\n in.readFully(0, buf);\n return toChar(buf);\n } finally {\n in.close();\n }\n}", "public static byte[] writeTextFile(FileSystem fs,\n Path path,\n String text,\n boolean overwrite) throws IOException {\n FSDataOutputStream stream = fs.create(path, overwrite);\n byte[] bytes = new byte[0];\n if (text != null) {\n bytes = toAsciiByteArray(text);\n stream.write(bytes);\n }\n stream.close();\n return bytes;\n}" ]
import static org.apache.hadoop.fs.swift.util.SwiftTestUtils.assertFileHasLength; import static org.apache.hadoop.fs.swift.util.SwiftTestUtils.assertIsDirectory; import static org.apache.hadoop.fs.swift.util.SwiftTestUtils.readBytesToString; import static org.apache.hadoop.fs.swift.util.SwiftTestUtils.writeTextFile; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.swift.exceptions.SwiftBadRequestException; import org.apache.hadoop.fs.swift.exceptions.SwiftNotDirectoryException; import org.apache.hadoop.fs.swift.snative.SwiftNativeFileSystem; import org.apache.hadoop.fs.swift.util.SwiftTestUtils; import org.junit.Test; import java.io.FileNotFoundException; import java.io.IOException;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.fs.swift; /** * Test basic filesystem operations. * Many of these are similar to those in {@link TestSwiftFileSystemContract} * -this is a JUnit4 test suite used to initially test the Swift * component. Once written, there's no reason not to retain these tests. */ public class TestSwiftFileSystemBasicOps extends SwiftFileSystemBaseTest { private static final Log LOG = LogFactory.getLog(TestSwiftFileSystemBasicOps.class); @Test(timeout = SWIFT_TEST_TIMEOUT) public void testLsRoot() throws Throwable { Path path = new Path("/"); FileStatus[] statuses = fs.listStatus(path); } @Test(timeout = SWIFT_TEST_TIMEOUT) public void testMkDir() throws Throwable { Path path = new Path("/test/MkDir"); fs.mkdirs(path); //success then -so try a recursive operation fs.delete(path, true); } @Test(timeout = SWIFT_TEST_TIMEOUT) public void testDeleteNonexistentFile() throws Throwable { Path path = new Path("/test/DeleteNonexistentFile"); assertFalse("delete returned true", fs.delete(path, false)); } @Test(timeout = SWIFT_TEST_TIMEOUT) public void testPutFile() throws Throwable { Path path = new Path("/test/PutFile"); Exception caught = null; writeTextFile(fs, path, "Testing a put to a file", false); assertDeleted(path, false); } @Test(timeout = SWIFT_TEST_TIMEOUT) public void testPutGetFile() throws Throwable { Path path = new Path("/test/PutGetFile"); try { String text = "Testing a put and get to a file " + System.currentTimeMillis(); writeTextFile(fs, path, text, false); String result = readBytesToString(fs, path, text.length()); assertEquals(text, result); } finally { delete(fs, path); } } @Test(timeout = SWIFT_TEST_TIMEOUT) public void testPutDeleteFileInSubdir() throws Throwable { Path path = new Path("/test/PutDeleteFileInSubdir/testPutDeleteFileInSubdir"); String text = "Testing a put and get to a file in a subdir " + System.currentTimeMillis(); writeTextFile(fs, path, text, false); assertDeleted(path, false); //now delete the parent that should have no children assertDeleted(new Path("/test/PutDeleteFileInSubdir"), false); } @Test(timeout = SWIFT_TEST_TIMEOUT) public void testRecursiveDelete() throws Throwable { Path childpath = new Path("/test/testRecursiveDelete"); String text = "Testing a put and get to a file in a subdir " + System.currentTimeMillis(); writeTextFile(fs, childpath, text, false); //now delete the parent that should have no children assertDeleted(new Path("/test"), true); assertFalse("child entry still present " + childpath, fs.exists(childpath)); }
private void delete(SwiftNativeFileSystem fs, Path path) {
0
eladnava/redalert-android
app/src/main/java/com/red/alert/activities/AlertView.java
[ "public class AlertViewParameters {\n public static final String ALERT_CITY = \"AlertZone\";\n public static final String ALERT_DATE_STRING = \"AlertDateString\";\n}", "public class City {\n @JsonProperty(\"lat\")\n public double latitude;\n\n @JsonProperty(\"lng\")\n public double longitude;\n\n @JsonProperty(\"name\")\n public String name;\n\n @JsonProperty(\"name_en\")\n public String nameEnglish;\n\n @JsonProperty(\"zone\")\n public String zone;\n\n @JsonProperty(\"zone_en\")\n public String zoneEnglish;\n\n @JsonProperty(\"value\")\n public String value;\n\n @JsonProperty(\"time\")\n public String time;\n\n @JsonProperty(\"time_en\")\n public String timeEnglish;\n\n @JsonProperty(\"shelters\")\n public int shelters;\n\n @JsonProperty(\"countdown\")\n public int countdown;\n\n @Override\n public String toString() {\n return value;\n }\n}", "public class RTLSupport {\n @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)\n public static void mirrorActionBar(Activity activity) {\n // Hebrew only\n if (!Localization.isHebrewLocale(activity)) {\n return;\n }\n\n // Must be Jellybean or newer\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {\n // Set RTL layout direction\n activity.getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);\n }\n }\n\n @SuppressLint(\"NewApi\")\n public static void mirrorDialog(Dialog dialog, Context context) {\n // Hebrew only\n if (!Localization.isHebrewLocale(context)) {\n return;\n }\n\n try {\n // Get message text view\n TextView message = (TextView) dialog.findViewById(android.R.id.message);\n\n // Defy gravity\n if (message != null) {\n message.setGravity(Gravity.RIGHT);\n }\n\n // Get the title of text view\n TextView title = (TextView) dialog.findViewById(context.getResources().getIdentifier(\"alertTitle\", \"id\", \"android\"));\n\n // Defy gravity\n title.setGravity(Gravity.RIGHT);\n\n // Get list view (may not exist)\n ListView listView = (ListView) dialog.findViewById(context.getResources().getIdentifier(\"select_dialog_listview\", \"id\", \"android\"));\n\n // Check if list & set RTL mode\n if (listView != null) {\n listView.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);\n }\n\n // Get title's parent layout\n LinearLayout parent = ((LinearLayout) title.getParent());\n\n // Get layout params\n LinearLayout.LayoutParams originalParams = (LinearLayout.LayoutParams) parent.getLayoutParams();\n\n // Set width to WRAP_CONTENT\n originalParams.width = LinearLayout.LayoutParams.WRAP_CONTENT;\n\n // Defy gravity\n originalParams.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;\n\n // Set layout params\n parent.setLayoutParams(originalParams);\n }\n catch (Exception exc) {\n // Log failure to logcat\n Log.d(Logging.TAG, \"RTL failed\", exc);\n }\n }\n}", "public class RTLMarkerInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {\n LayoutInflater mInflater;\n\n public RTLMarkerInfoWindowAdapter(LayoutInflater inflater) {\n // Set inflater\n this.mInflater = inflater;\n }\n\n @Override\n public View getInfoWindow(Marker Marker) {\n // Do nothing\n return null;\n }\n\n @Override\n public View getInfoContents(Marker marker) {\n // Inflate custom view\n View popup = mInflater.inflate(R.layout.map_tooltip, null);\n\n // Get text view\n TextView textView = (TextView) popup.findViewById(R.id.title);\n\n // Set text\n textView.setText(marker.getTitle());\n\n // Get snippet view\n textView = (TextView) popup.findViewById(R.id.snippet);\n\n // Set snippet\n textView.setText(marker.getSnippet());\n\n // No snippet?\n if (marker.getSnippet() == null) {\n textView.setVisibility(View.GONE);\n }\n\n // Return popup\n return popup;\n }\n}", "public class AppNotifications {\n public static void clearAll(Context context) {\n // Get notification manager\n NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);\n\n // Cancel all notifications\n notificationManager.cancelAll();\n\n // Stop alert sound if playing\n SoundLogic.stopSound(context);\n }\n}", "public class Localization {\n public static boolean isEnglishLocale(Context context) {\n // Override locale, if chosen\n overridePhoneLocale(context);\n\n // Get language code\n String languageCode = context.getResources().getConfiguration().locale.getLanguage();\n\n // English locale codes list\n List<String> englishLocales = new ArrayList<>();\n\n // Locale codes that are considered \"English\"\n englishLocales.add(context.getString(R.string.englishCode));\n englishLocales.add(context.getString(R.string.italianCode));\n\n // Traverse valid locale codes\n for (String code : englishLocales) {\n // Check for string equality\n if (languageCode.equals(code)) {\n return true;\n }\n }\n\n // Not an English locale\n return false;\n }\n\n public static boolean isHebrewLocale(Context context) {\n // Override locale, if chosen\n overridePhoneLocale(context);\n\n // Get language code\n String languageCode = context.getResources().getConfiguration().locale.getLanguage();\n\n // Detect using locale code\n return languageCode.equals(context.getString(R.string.hebrewCode)) || languageCode.equals(context.getString(R.string.hebrewCode2));\n }\n\n public static void overridePhoneLocale(Context context) {\n // Create new configuration\n Configuration configuration = context.getResources().getConfiguration();\n\n // Get new locale code\n String overrideLocale = Singleton.getSharedPreferences(context).getString(context.getString(R.string.langPref), \"\");\n\n // Chosen a new locale?\n if (!StringUtils.stringIsNullOrEmpty(overrideLocale)) {\n // Set it\n configuration.locale = new Locale(overrideLocale);\n }\n else {\n // Use default locale\n configuration.locale = Locale.getDefault();\n }\n\n // Apply the configuration\n context.getResources().updateConfiguration(configuration, context.getResources().getDisplayMetrics());\n }\n}", "public class LocationData {\n private static List<City> mCities;\n\n /*\n // Zone = דן 161\n // Zone Code = 161\n // City Name = תל אביב\n // City Countdown = 15 שניות\n */\n\n public static String[] getAllCityNames(Context context) {\n // Check for english locale\n boolean isHebrew = Localization.isHebrewLocale(context);\n\n // Get all city objects\n List<City> cities = getAllCities(context);\n\n // Prepare names array\n List<String> names = new ArrayList<>();\n\n // Loop over cities\n for (City city : cities) {\n // Hebrew?\n if (isHebrew) {\n // Add to list\n names.add(city.name);\n }\n else {\n // Add english name to list\n names.add(city.nameEnglish);\n }\n }\n\n // Return array\n return names.toArray(new String[names.size()]);\n }\n\n public static String[] getAllCityValues(Context context) {\n // Prepare cities array\n List<City> cities = getAllCities(context);\n\n // Prepare array\n List<String> values = new ArrayList<String>();\n\n // Loop over cities\n for (City city : cities) {\n // Add to list\n values.add(city.value);\n }\n\n // Return array\n return values.toArray(new String[values.size()]);\n }\n\n public static String[] getAllCityZones(Context context) {\n // Get user's locale\n boolean isHebrew = Localization.isHebrewLocale(context);\n\n // Prepare cities array\n List<City> cities = getAllCities(context);\n\n // Prepare array\n List<String> values = new ArrayList<String>();\n\n // Loop over cities\n for (City city : cities) {\n // Hebrew?\n if (isHebrew) {\n // Add to list\n values.add(city.zone);\n }\n else {\n // Add to list\n values.add(city.zoneEnglish);\n }\n }\n\n // Return array\n return values.toArray(new String[values.size()]);\n }\n\n public static List<City> getAllCities(Context context) {\n // Got it in cache?\n if (mCities != null) {\n return mCities;\n }\n\n // Initialize the list\n mCities = new ArrayList<>();\n\n try {\n // Open the cities.json for reading\n InputStream stream = context.getResources().openRawResource(R.raw.cities);\n\n // Create a buffered reader\n BufferedReader reader = new BufferedReader(new InputStreamReader(stream));\n\n // StringBuilder for efficiency\n StringBuilder builder = new StringBuilder();\n\n // A temporary variable to store current line\n String currentLine;\n\n // Read all lines\n while ((currentLine = reader.readLine()) != null) {\n // Append to builder\n builder.append(currentLine);\n }\n\n // Convert to string\n String json = builder.toString();\n\n // Convert to city objects\n mCities = Singleton.getJackson().readValue(json, new TypeReference<List<City>>() {\n });\n }\n catch (Exception exc) {\n // Log it\n Log.e(Logging.TAG, \"Failed to load cities.json\", exc);\n }\n\n // Return them\n return mCities;\n }\n\n public static String getSelectedCityNamesByValues(Context context, String selection, CharSequence[] names, CharSequence[] values) {\n // No value? All cities are selected\n if (StringUtils.stringIsNullOrEmpty(selection) || selection.equals(context.getString(R.string.all))) {\n return context.getString(R.string.allString);\n }\n\n // Value equals none | null?\n else if (selection.equals(context.getString(R.string.none)) || selection.equals(context.getString(R.string.nullString))) {\n return context.getString(R.string.noneString);\n }\n\n // Display names\n List<String> selectedCityNames = new ArrayList<String>();\n\n // Remove area code\n String[] selectedValues = selection.split(\"\\\\|\");\n\n // Loop over values\n for (String selectedValue : selectedValues) {\n // Loop over values\n for (int i = 0; i < values.length; i++) {\n // Got the value?\n if (values[i].equals(selectedValue)) {\n // Add the name to list\n selectedCityNames.add(names[i].toString());\n }\n }\n }\n\n // Failed to find cities?\n if (selectedCityNames.size() == 0) {\n // Return \"none\"\n return context.getString(R.string.noneString);\n }\n\n // Implode into a CSV string\n String displayText = StringUtils.implode(\", \", selectedCityNames);\n\n // Truncate if too long\n if (displayText.length() > 120) {\n displayText = displayText.substring(0, 120) + \"...\";\n }\n\n // Return display text\n return displayText;\n }\n\n public static String getLocalizedZoneWithCountdown(String cityName, Context context) {\n // Get user's locale\n boolean isHebrew = Localization.isHebrewLocale(context);\n\n // Prepare cities array\n List<City> cities = getAllCities(context);\n\n // Loop over cities\n for (City city : cities) {\n // Got a match?\n if (city.name.equals(cityName)) {\n // Hebrew?\n if (isHebrew) {\n // Return area countdown\n return city.zone + \" (\" + city.time + \")\";\n }\n else {\n // Return area countdown in English\n return city.zoneEnglish + \" (\" + city.timeEnglish + \")\";\n }\n }\n }\n\n // No match\n return \"\";\n }\n\n public static int getCityCountdown(String cityName, Context context) {\n // Prepare cities array\n List<City> cities = getAllCities(context);\n\n // Loop over cities\n for (City city : cities) {\n // Got a match?\n if (city.name.equals(cityName)) {\n // Return countdown\n return city.countdown;\n }\n }\n\n // No match\n return 0;\n }\n\n public static String getLocalizedCityName(String cityName, Context context) {\n // Get user's locale\n boolean isHebrew = Localization.isHebrewLocale(context);\n\n // Hebrew?\n if (isHebrew) {\n return cityName;\n }\n\n // Prepare cities array\n List<City> cities = getAllCities(context);\n\n // Loop over cities\n for (City city : cities) {\n // Got a match?\n if (city.name.equals(cityName)) {\n // Return english name\n return city.nameEnglish;\n }\n }\n\n // No match\n return cityName;\n }\n\n public static City getCityByName(String cityName, Context context) {\n // Prepare cities array\n List<City> cities = getAllCities(context);\n\n // Loop over cities\n for (City city : cities) {\n // Got a match?\n if (city.name.equals(cityName)) {\n return city;\n }\n }\n\n // No match\n return null;\n }\n\n public static String getNearbyCityNames(Location myLocation, Context context) {\n // Get user's locale\n boolean isHebrew = Localization.isHebrewLocale(context);\n\n // Prepare cities array\n List<City> cities = getAllCities(context);\n\n // Output array\n List<String> cityNames = new ArrayList<>();\n\n // Calculate max distance\n double maxDistance = LocationLogic.getMaxDistanceKilometers(context, -1);\n\n // String is not empty\n for (City city : cities) {\n // Prepare new location\n Location location = new Location(\"\");\n\n // Set lat & long\n location.setLatitude(city.latitude);\n location.setLongitude(city.longitude);\n\n // Get distance to city in KM\n float distance = location.distanceTo(myLocation) / 1000;\n\n // Distance is less than max?\n if (distance <= maxDistance) {\n // Hebrew?\n if (isHebrew) {\n // Add to list\n cityNames.add(city.name);\n }\n else {\n // Add to list\n cityNames.add(city.nameEnglish);\n }\n }\n }\n\n // Join and add original code\n return StringUtils.implode(\", \", cityNames);\n }\n\n public static Location getCityLocation(String cityName, Context context) {\n // Prepare cities array\n List<City> cities = getAllCities(context);\n\n // Loop over cities\n for (City city : cities) {\n // Got a match?\n if (city.name.equals(cityName)) {\n // Prepare new location\n Location location = new Location(LocationManager.PASSIVE_PROVIDER);\n\n // Set lat & long\n location.setLatitude(city.latitude);\n location.setLongitude(city.longitude);\n\n // Add to list\n return location;\n }\n }\n\n // Fail\n return null;\n }\n\n public static List<String> explodeCitiesPSV(String citiesPSV) {\n // Unique cities list\n List<String> uniqueList = new ArrayList<>();\n\n // Explode into array\n List<String> psvList = Arrays.asList(citiesPSV.split(\"\\\\|\"));\n\n // Loop over items\n for (String item : psvList) {\n // Not already added?\n if (!StringUtils.stringIsNullOrEmpty(item) && !uniqueList.contains(item) && !item.equals(\"none\") && !item.equals(\"null\")) {\n // Add it\n uniqueList.add(item);\n }\n }\n\n // Return them\n return uniqueList;\n }\n\n public static String getZoneByCityName(String cityName, Context context) {\n // Prepare cities array\n List<City> cities = getAllCities(context);\n\n // Loop over cities\n for (City city : cities) {\n // Got a match?\n if (city.name.equals(cityName)) {\n return city.zone;\n }\n }\n\n // Unknown city\n return \"\";\n }\n\n public static String getLocalizedZoneByCityName(String cityName, Context context) {\n // Get user's locale\n boolean isHebrew = Localization.isHebrewLocale(context);\n\n // Prepare cities array\n List<City> cities = getAllCities(context);\n\n // Loop over cities\n for (City city : cities) {\n // Got a match?\n if (city.name.equals(cityName)) {\n return isHebrew ? city.zone: city.zoneEnglish;\n }\n }\n\n // Unknown city\n return \"\";\n }\n}" ]
import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Handler; import androidx.core.app.ActivityCompat; import androidx.core.view.MenuItemCompat; import androidx.appcompat.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.red.alert.R; import com.red.alert.logic.communication.intents.AlertViewParameters; import com.red.alert.model.metadata.City; import com.red.alert.ui.localization.rtl.RTLSupport; import com.red.alert.ui.localization.rtl.adapters.RTLMarkerInfoWindowAdapter; import com.red.alert.ui.notifications.AppNotifications; import com.red.alert.utils.localization.Localization; import com.red.alert.utils.metadata.LocationData;
package com.red.alert.activities; public class AlertView extends AppCompatActivity { GoogleMap mMap; String mAlertCity; String mAlertDateString; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Initialize alert unpackExtras(); // Initialize UI initializeUI(); } void unpackExtras() { // Get alert area mAlertCity = getIntent().getStringExtra(AlertViewParameters.ALERT_CITY); // Get alert date string mAlertDateString = getIntent().getStringExtra(AlertViewParameters.ALERT_DATE_STRING); } void mapLoadedListener() { // Wait for map to load mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() { @Override public void onCameraChange(CameraPosition arg0) { // Prevent from being called again mMap.setOnCameraChangeListener(null); // Fix RTL bug with hebrew mMap.setInfoWindowAdapter(new RTLMarkerInfoWindowAdapter(getLayoutInflater())); // Show my location button if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mMap.setMyLocationEnabled(true); } // Wait for tiles to load new Handler().postDelayed(new Runnable() { @Override public void run() { // Add map overlays addOverlays(); } }, 500); } }); } void initializeMap() { // Get map instance if (mMap == null) { // Stop execution return; } // Wait for map to load mapLoadedListener(); } void addOverlays() { // Get alert area
City city = LocationData.getCityByName(mAlertCity, this);
1
gabormakrai/dijkstra-performance
DijkstraPerformance/src/dijkstra/performance/scenario/RandomPengyifanFibonacciPriorityQueueScenario.java
[ "public class NeighbourArrayGraphGenerator {\r\n\t\r\n\tpublic int[][] neighbours;\r\n\tpublic double[][] weights;\r\n\t\r\n\tpublic void generateRandomGraph(int size, double p, Random random) {\r\n\t\t\r\n\t\tHashSet<Integer>[] neighboursList = generateList(size);\r\n\r\n\t\t// create random spanning tree\r\n\t\tgenerateSpanningTree(neighboursList, random);\r\n\t\t\r\n\t\t// add more random arcs\r\n\t\tint arcs = (int)Math.round(size * size * p) - (size - 1) * 2; \r\n\t\taddRandomArcs(arcs, neighboursList, random);\r\n\r\n\t\t// create neighbours array\r\n\t\tneighbours = createNeighboursArrat(neighboursList);\r\n\t\t\r\n\t\t// fill weights with random values\r\n\t\tweights = createWeightsArray(neighbours, random);\r\n\t}\r\n\t\r\n\t@SuppressWarnings(\"unchecked\")\r\n\tprivate HashSet<Integer>[] generateList(int size) {\r\n\t\tHashSet<Integer>[] neighboursList = new HashSet[size];\r\n\t\tfor (int i = 0; i < size; ++i) {\r\n\t\t\tneighboursList[i] = new HashSet<Integer>();\r\n\t\t}\r\n\t\treturn neighboursList;\r\n\t}\r\n\t\r\n\tprivate void generateSpanningTree(HashSet<Integer>[] neighboursList, Random random) {\r\n\t\tboolean[] nodes = new boolean[neighboursList.length];\r\n\t\tfor (int i = 0; i < nodes.length; ++i) {\r\n\t\t\tnodes[i] = false;\r\n\t\t}\r\n\t\tint nodeNumber = nodes.length;\r\n\t\tboolean firstIteration = true;\r\n\t\twhile(nodeNumber != 0) {\r\n\t\t\tint v = random.nextInt(nodes.length);\r\n\t\t\tint w = random.nextInt(nodes.length);\r\n\t\t\tif (v == w) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tif (firstIteration) {\r\n\t\t\t\tfirstIteration = false;\r\n\t\t\t} else if ((nodes[v] && nodes[w]) || (!nodes[v] && !nodes[w])) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tneighboursList[v].add(w);\r\n\t\t\tneighboursList[w].add(v);\r\n\t\t\tif (!nodes[v]) {\r\n\t\t\t\tnodes[v] = true;\r\n\t\t\t\t--nodeNumber;\r\n\t\t\t}\r\n\t\t\tif (!nodes[w]) {\r\n\t\t\t\tnodes[w] = true;\r\n\t\t\t\t--nodeNumber;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate int[][] createNeighboursArrat(HashSet<Integer>[] neighboursList) {\r\n\t\tint[][] neighbours = new int[neighboursList.length][];\r\n\t\tfor (int i = 0; i < neighbours.length; ++i) {\r\n\t\t\tneighbours[i] = new int[neighboursList[i].size()];\r\n\t\t\tint j = 0;\r\n\t\t\tfor (Integer neighbour : neighboursList[i]) {\r\n\t\t\t\tneighbours[i][j] = neighbour;\r\n\t\t\t\t++j;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn neighbours;\r\n\t}\r\n\t\r\n\tprivate double[][] createWeightsArray(int[][] neighbours, Random random) {\r\n\t\tdouble[][] weights = new double[neighbours.length][];\r\n\t\tfor (int i = 0; i < weights.length; ++i) {\r\n\t\t\tif (neighbours[i] == null) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tweights[i] = new double[neighbours[i].length];\r\n\t\t\tfor (int j = 0; j < neighbours[i].length; ++j) {\r\n\t\t\t\tweights[i][j] = random.nextDouble();\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn weights;\r\n\t}\r\n\t\r\n\tprivate void addRandomArcs(int arcs, HashSet<Integer>[] neighboursList, Random random) {\r\n\t\tint size = neighboursList.length;\r\n\t\tfor (int i = 0; i < arcs; ++i) {\r\n\t\t\tint v = random.nextInt(size);\r\n\t\t\tint w = random.nextInt(size);\r\n\t\t\t\r\n\t\t\tif (neighboursList[v].contains(w) || v == w) {\r\n\t\t\t\t--i;\r\n\t\t\t} else {\r\n\t\t\t\tneighboursList[v].add(w);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n}\r", "public interface PerformanceScenario {\r\n\tpublic void generateGraph();\r\n\tpublic void runShortestPath();\r\n\tpublic int[] testPrevious(int randomSeed);\r\n}\r", "public class PriorityQueueDijkstra {\r\n\t\r\n\tpublic static void createPreviousArray(int[][] neighbours, double[][] weights, int source, int[] previous, PriorityObject[] priorityObjectArray, PriorityQueue<PriorityObject> priorityQueue) {\r\n\t\t\r\n\t\tfor (int i = 0; i < priorityObjectArray.length; ++i) {\r\n\t\t\tpriorityObjectArray[i].priority = Double.MAX_VALUE;\r\n\t\t\tprevious[i] = -1;\r\n\t\t}\r\n\t\t\r\n\t\tpriorityObjectArray[source].priority = 0.0;\r\n\t\t\r\n\t\tpriorityQueue.clear();\r\n\t\tfor (int i = 0; i < priorityObjectArray.length; ++i) {\r\n\t\t\tpriorityQueue.add(priorityObjectArray[i]);\r\n\t\t}\r\n\t\t\t\t\r\n\t\twhile (priorityQueue.size() != 0) {\r\n\t\t\t\r\n\t\t\t// extract min\r\n\t\t\tPriorityObject min = priorityQueue.extractMin();\r\n\t\t\tint u = min.node;\r\n\t\t\t\r\n\t\t\t// find the neighbours\r\n\t\t\tif (neighbours[u] == null) {\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\tfor (int i = 0; i < neighbours[u].length; ++i) {\r\n\t\t\t\tdouble alt = priorityObjectArray[u].priority + weights[u][i];\r\n\t\t\t\tif (alt < priorityObjectArray[neighbours[u][i]].priority) {\r\n\t\t\t\t\tpriorityQueue.decreasePriority(priorityObjectArray[neighbours[u][i]], alt);\r\n\t\t\t\t\tprevious[neighbours[u][i]] = u;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static int[] shortestPath(int[] previous, int destination) {\r\n\t\tif (previous[destination] == -1) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\t\r\n\t\tLinkedList<Integer> reversedRoute = new LinkedList<>();\r\n\t\tint u = destination;\r\n\t\t\r\n\t\twhile (u != -1) {\r\n\t\t\treversedRoute.add(u);\r\n\t\t\tu = previous[u];\r\n\t\t}\r\n\t\t\r\n\t\tint[] path = new int[reversedRoute.size()];\r\n\t\tfor (int i = 0; i < path.length; ++i) {\r\n\t\t\tpath[i] = reversedRoute.get(path.length - 1 - i);\r\n\t\t}\r\n\t\t\r\n\t\treturn path;\r\n\t}\t\t\r\n}\r", "public class PengyifanDijkstraPriorityObject extends PriorityObject {\r\n\t\r\n\tpublic FibonacciHeap.Entry entry;\r\n\r\n\tpublic PengyifanDijkstraPriorityObject(int node, double distance) {\r\n\t\tsuper(node, distance);\r\n\t}\r\n\t\r\n}\r", "public class PengyifanFibonacciPriorityQueue implements dijkstra.priority.PriorityQueue<PriorityObject> {\r\n\r\n\tFibonacciHeap heap = new FibonacciHeap();\r\n\tint heapSize = 0;\r\n\r\n\t@Override\r\n\tpublic void add(PriorityObject item) {\r\n\t\tEntry entry = new Entry(item.priority, item);\r\n\t\theap.insert(entry);\r\n\t\t((PengyifanDijkstraPriorityObject)item).entry = entry;\r\n\t\t++heapSize;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void decreasePriority(PriorityObject item, double priority) {\r\n\t\titem.priority = priority;\r\n\t\theap.decreaseKey(((PengyifanDijkstraPriorityObject)item).entry, priority);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic PriorityObject extractMin() {\r\n\t\tif (heapSize > 0) {\r\n\t\t\t--heapSize;\r\n\t\t} else {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\treturn (PriorityObject) heap.extractMin().getObject();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void clear() {\r\n\t\theap = new FibonacciHeap();\r\n\t\theapSize = 0;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int size() {\r\n\t\treturn heapSize;\r\n\t\t\r\n\t}\t\r\n\r\n}\r" ]
import java.util.Random; import dijkstra.graph.NeighbourArrayGraphGenerator; import dijkstra.performance.PerformanceScenario; import dijkstra.priority.PriorityQueueDijkstra; import dijkstra.priority.impl.PengyifanDijkstraPriorityObject; import dijkstra.priority.impl.PengyifanFibonacciPriorityQueue;
package dijkstra.performance.scenario; public class RandomPengyifanFibonacciPriorityQueueScenario implements PerformanceScenario { NeighbourArrayGraphGenerator generator = new NeighbourArrayGraphGenerator(); int[] previous; PengyifanDijkstraPriorityObject[] priorityObjectArray; PengyifanFibonacciPriorityQueue priorityQueue; Random random; int size; double p; int previosArrayBuilds; public RandomPengyifanFibonacciPriorityQueueScenario(int size, double p, int previousArrayBuilds, Random random) { this.size = size; this.p = p; this.previosArrayBuilds = previousArrayBuilds; this.random = random; } @Override public void runShortestPath() { for (int i = 0; i < previosArrayBuilds; ++i) { int origin = random.nextInt(size);
PriorityQueueDijkstra.createPreviousArray(generator.neighbours, generator.weights, origin, previous, priorityObjectArray, priorityQueue);
2
blacklocus/jres
jres-test/src/test/java/com/blacklocus/jres/request/mapping/JresPutMappingTest.java
[ "public class BaseJresTest {\n\n @BeforeClass\n public static void startLocalElasticSearch() {\n ElasticSearchTestInstance.triggerStaticInit();\n }\n\n /**\n * Configured to connect to a local ElasticSearch instance created specifically for unit testing\n */\n protected Jres jres = new Jres(Suppliers.ofInstance(\"http://localhost:9201\"));\n\n}", "public class JresCreateIndex extends JresJsonRequest<JresAcknowledgedReply> {\n\n private final String index;\n private final Object settings;\n\n public JresCreateIndex(String index) {\n this(index, null);\n }\n\n public JresCreateIndex(String index, String settingsJson) {\n super(JresAcknowledgedReply.class);\n this.index = index;\n this.settings = settingsJson;\n }\n\n @Override\n public String getHttpMethod() {\n return HttpPut.METHOD_NAME;\n }\n\n @Override\n public String getPath() {\n return index;\n }\n\n @Override\n public Object getPayload() {\n return settings;\n }\n\n}", "public class JresBooleanReply implements JresReply {\n\n private final boolean verity;\n\n public JresBooleanReply(boolean verity) {\n this.verity = verity;\n }\n\n @Override\n public JsonNode node() {\n return null;\n }\n\n public boolean verity() {\n return verity;\n }\n\n}", "public class JresAcknowledgedReply extends JresJsonReply {\n\n private Boolean acknowledged;\n\n public Boolean getAcknowledged() {\n return acknowledged;\n }\n}", "public class JresErrorReplyException extends RuntimeException implements JresReply {\n\n private final String error;\n private final Integer status;\n private final JsonNode node;\n\n public JresErrorReplyException(String error, Integer status, JsonNode node) {\n super(error);\n this.error = error;\n this.status = status;\n this.node = node;\n }\n\n @Override\n public JsonNode node() {\n return node;\n }\n\n public String getError() {\n return error;\n }\n\n public Integer getStatus() {\n return status;\n }\n\n public <T> T asType(Class<T> klass) {\n return ObjectMappers.fromJson(node, klass);\n }\n\n public <T> T asType(TypeReference<T> typeReference) {\n return ObjectMappers.fromJson(node, typeReference);\n }\n}" ]
import com.blacklocus.jres.BaseJresTest; import com.blacklocus.jres.request.index.JresCreateIndex; import com.blacklocus.jres.response.JresBooleanReply; import com.blacklocus.jres.response.common.JresAcknowledgedReply; import com.blacklocus.jres.response.common.JresErrorReplyException; import org.junit.Assert; import org.junit.Test;
/** * Copyright 2015 BlackLocus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.blacklocus.jres.request.mapping; public class JresPutMappingTest extends BaseJresTest { @Test public void sad() { String index = "JresPutMappingRequestTest_sad".toLowerCase(); String type = "test"; try { jres.quest(new JresPutMapping(index, type, "{\"test\":{}}")); Assert.fail("Shouldn't be able to put type mapping on non-existent index"); } catch (JresErrorReplyException e) { // good } jres.quest(new JresCreateIndex(index)); try { jres.quest(new JresPutMapping(index, type, null)); Assert.fail("Invalid data"); } catch (JresErrorReplyException e) { // good } try { jres.quest(new JresPutMapping(index, type, "")); Assert.fail("Invalid data"); } catch (JresErrorReplyException e) { // good } try { jres.quest(new JresPutMapping(index, type, "{}")); Assert.fail("Invalid data"); } catch (JresErrorReplyException e) { // good } } @Test public void happy() { String index = "JresPutMappingRequestTest_happy".toLowerCase(); String type = "test"; { JresBooleanReply response = jres.bool(new JresTypeExists(index, type)); Assert.assertFalse(response.verity()); } jres.quest(new JresCreateIndex(index)); {
JresAcknowledgedReply response = jres.quest(new JresPutMapping(index, type, "{\"test\":{}}"));
3
johanneslerch/FlowTwist
FlowTwist/test/flow/twist/test/util/AbstractPathTests.java
[ "public static UnitSelector anyUnit() {\n\treturn new UnitSelector() {\n\n\t\t@Override\n\t\tpublic boolean matches(SootMethod method, Unit unit) {\n\t\t\treturn true;\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"any unit\";\n\t\t}\n\t};\n}", "public static UnitSelector unitByLabel(final String label) {\n\treturn new UnitSelector() {\n\t\t@Override\n\t\tpublic boolean matches(SootMethod method, Unit unit) {\n\t\t\treturn unit.toString().contains(label);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn label;\n\t\t}\n\t};\n}", "public static UnitSelector unitInMethod(final String methodString, final UnitSelector selector) {\n\treturn new UnitSelector() {\n\t\t@Override\n\t\tpublic boolean matches(SootMethod method, Unit unit) {\n\t\t\treturn method.toString().contains(methodString) && selector.matches(method, unit);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"'\" + selector.toString() + \"' in '\" + methodString + \"'\";\n\t\t}\n\t};\n}", "public static UnitSelector unitWithoutLabel(final String label, final UnitSelector selector) {\n\treturn new UnitSelector() {\n\t\t@Override\n\t\tpublic boolean matches(SootMethod method, Unit unit) {\n\t\t\treturn !unit.toString().contains(label) && selector.matches(method, unit);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"'\" + selector.toString() + \"' without '\" + label + \"'\";\n\t\t}\n\t};\n}", "public class PathSelector {\n\tprivate List<Path> paths;\n\n\tpublic PathSelector(List<Path> paths) {\n\t\tthis.paths = paths;\n\t}\n\n\tpublic PathSelector endsAt(UnitSelector selector) {\n\t\tList<Path> matchingPaths = Lists.newLinkedList();\n\t\tfor (Path path : paths) {\n\t\t\tUnit unit = path.getLast();\n\t\t\tif (selector.matches(path.context.icfg.getMethodOf(unit), unit)) {\n\t\t\t\tmatchingPaths.add(path);\n\t\t\t}\n\t\t}\n\t\treturn new PathSelector(matchingPaths);\n\t}\n\n\tpublic PathSelector contains(UnitSelector selector) {\n\t\tList<Path> matchingPaths = Lists.newLinkedList();\n\t\tfor (Path path : paths) {\n\t\t\tif (pathContains(selector, path)) {\n\t\t\t\tmatchingPaths.add(path);\n\t\t\t}\n\t\t}\n\t\treturn new PathSelector(matchingPaths);\n\t}\n\n\tprivate boolean pathContains(UnitSelector selector, Path path) {\n\t\tfor (PathElement element : path) {\n\t\t\tif (selector.matches(path.context.icfg.getMethodOf(element.to), element.to)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tpublic PathSelector doesNotContain(UnitSelector selector) {\n\t\tList<Path> matchingPaths = Lists.newLinkedList();\n\t\tfor (Path path : paths) {\n\t\t\tif (!pathContains(selector, path)) {\n\t\t\t\tmatchingPaths.add(path);\n\t\t\t}\n\t\t}\n\t\treturn new PathSelector(matchingPaths);\n\t}\n\n\tpublic void once() {\n\t\tAssert.assertEquals(1, paths.size());\n\t}\n\n\tpublic void never() {\n\t\tAssert.assertEquals(0, paths.size());\n\t}\n\n\tpublic void noOtherPaths() {\n\t\tAssert.assertEquals(paths.size(), PathVerifier.this.paths.size());\n\t}\n\n\tpublic void times(int i) {\n\t\tAssert.assertEquals(i, paths.size());\n\t}\n\n\tpublic void assertStack(Unit... callSites) {\n\t\tfor (Path path : paths) {\n\t\t\tfj.data.List<Object> callStack = path.getCallStack();\n\t\t\tAssert.assertTrue(Iterables.elementsEqual(callStack, Lists.newArrayList(callSites)));\n\t\t}\n\t}\n\n}" ]
import static flow.twist.test.util.selectors.UnitSelectorFactory.anyUnit; import static flow.twist.test.util.selectors.UnitSelectorFactory.unitByLabel; import static flow.twist.test.util.selectors.UnitSelectorFactory.unitInMethod; import static flow.twist.test.util.selectors.UnitSelectorFactory.unitWithoutLabel; import org.junit.Assert; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import flow.twist.test.util.PathVerifier.PathSelector; import flow.twist.util.MultipleAnalysisPlotter;
package flow.twist.test.util; public abstract class AbstractPathTests extends AbstractTaintAnalysisTest { protected PathVerifier pathVerifier; @Rule public TestWatcher watcher = new TestWatcher() { @Override public void failed(Throwable e, Description description) { StringBuilder builder = new StringBuilder(); builder.append("tmp/"); builder.append(AbstractPathTests.this.getClass().getSimpleName()); builder.append("_"); builder.append(description.getMethodName()); builder.append("_path"); MultipleAnalysisPlotter plotter = new MultipleAnalysisPlotter(); plotter.plotAnalysisResults(pathVerifier.getPaths(), "red"); plotter.writeFile(builder.toString()); } }; @Test public void aliasing() { runTest("java.lang.Aliasing"); pathVerifier.totalPaths(3); pathVerifier.startsAt(unitInMethod("nameInput(", unitByLabel("@parameter0"))).endsAt(unitByLabel("return")).once(); pathVerifier.startsAt(unitInMethod("nameInput(", unitByLabel("@parameter2"))).endsAt(unitByLabel("return")).once(); pathVerifier.startsAt(unitInMethod("nameInput2(", unitByLabel("@parameter0"))).endsAt(unitByLabel("return")).once(); } @Test public void backwardsIntoThrow() { runTest("java.lang.BackwardsIntoThrow"); pathVerifier.totalPaths(1); pathVerifier.startsAt(unitInMethod("foo", unitByLabel("@parameter0"))).endsAt(unitInMethod("foo", unitByLabel("return"))).once(); } @Test @Ignore("does not work without target for forName with classloader argument") public void beanInstantiator() { runTest("java.lang.BeanInstantiator"); pathVerifier.totalPaths(3);
PathSelector path = pathVerifier.startsAt(unitInMethod("findClass", unitByLabel("@parameter0"))).endsAt(
4
thirdy/durian
durian/src/main/java/qic/ui/SearchResultTable.java
[ "@SuppressWarnings(\"rawtypes\")\npublic class BeanPropertyTableModel<T> extends AbstractTableModel {\n\t\n\tprivate static final long serialVersionUID = 1L;\n\t\n\t/** class of the data in rows */\n\tprivate final Class beanClass;\n /** collection of table rows */\n private List<T> data = new ArrayList<T>();\n /** collections of column property descriptors and names */\n private List<PropertyDescriptor> columns = new ArrayList<PropertyDescriptor>();\n private List<String> columnNames = new ArrayList<String>();\n /** resource bundle used to get column names */\n private ResourceBundle resourceBundle;\n /** Prefix for resource bundle column names */\n private String resourcePrefix;\n /** set of properties of exclude */\n private Set<String> excludeProperties = new HashSet<String>();\n /** order of columns for this table */\n private List<String> orderedProperties = new ArrayList<String>();\n /** Order of properties to their table column indexes */\n private Map<String,Integer> propertiesIndexes = new HashMap<String,Integer>();\n\n public BeanPropertyTableModel(Class beanClass) {\n if (beanClass == null) {\n throw new IllegalArgumentException(\"Bean class required, cannot be null\");\n }\n this.beanClass = beanClass;\n addExcludedProperty(\"class\");\n }\n\n public List<T> getData() {\n return data;\n }\n\n public void setData(List<T> data) {\n this.data = data;\n fireTableDataChanged();\n }\n\n /**\n * Sets resource bundle to get the column names from.\n * @param resourceBundle Bundle with strings\n */\n public void setResourceBundle(ResourceBundle resourceBundle) {\n this.resourceBundle = resourceBundle;\n }\n\n /**\n *\n * @param resourcePrefix Resource prefix to search 'prefix.propertyName' as column name in the bundle\n */\n public void setResourcePrefix(String resourcePrefix) {\n this.resourcePrefix = resourcePrefix;\n }\n\n /**\n * Adds property not to show in the table\n * @param propertyName Property name to exclude\n */\n public void addExcludedProperty(String propertyName) {\n excludeProperties.add(propertyName);\n }\n\n /**\n * Sets order of properties in the table. Not all columns should be included,\n * columns that are not included added as after the ordered columns in undetermined order.\n *\n * @param orderedColumns List which contains order of properties to use when build columns\n */\n public void setOrderedProperties(List<String> orderedProperties) {\n this.orderedProperties = orderedProperties;\n }\n\n /**\n * Attempts to read ordered column names from plain text file, each column name on separate line.\n * File encoding is UTF-8.\n * All exceptions are converted to unchecked.\n * @param base Base class of resource\n * @param resourceName name of resource file\n */\n public void setOrderedPropertiesFromResource(Class base, String resourceName) {\n List<String> result = new ArrayList<String>();\n BufferedReader reader = null;\n try {\n reader = new BufferedReader(new InputStreamReader(base.getResourceAsStream(resourceName), \"UTF8\"));\n } catch (UnsupportedEncodingException ex) {\n throw new RuntimeException(ex);\n }\n String nextLine = null;\n try {\n while ((nextLine = reader.readLine()) != null) {\n result.add(nextLine.trim());\n }\n } catch (IOException ex) {\n throw new RuntimeException(ex);\n } finally {\n try {\n reader.close();\n } catch (IOException ex) {\n throw new RuntimeException(ex);\n }\n }\n // use result as ordered list\n setOrderedProperties(result);\n }\n\n @Override\n public int getRowCount() {\n return data.size();\n }\n\n @Override\n public int getColumnCount() {\n if ( columns.isEmpty() ) {\n // lazily create the column set\n populateColumns();\n }\n return columns.size();\n }\n\n @Override\n public Class<?> getColumnClass(int columnIndex) {\n return columns.get(columnIndex).getPropertyType();\n }\n\n @Override\n public String getColumnName(int column) {\n return columnNames.get(column);\n }\n\n @Override\n public Object getValueAt(int rowIndex, int columnIndex) {\n PropertyDescriptor descriptor = columns.get(columnIndex);\n T bean = data.get(rowIndex);\n return DynamicBeanUtils.getPropertyValue(bean, descriptor);\n }\n\n public void populateColumns() {\n // on initialize, parse the class and add all the properties as columns\n BeanInfo info = null;\n try {\n info = Introspector.getBeanInfo(beanClass);\n } catch (IntrospectionException ex) {\n throw new RuntimeException(\"Unable to introspect dynamic table data class\", ex);\n }\n PropertyDescriptor[] pds = info.getPropertyDescriptors();\n int columnIndex = 0;\n // first, add ordered columns\n for (String nextOrderedProp : orderedProperties) {\n for (PropertyDescriptor nextDescriptor : pds) {\n if (nextDescriptor.getName().equals(nextOrderedProp)) {\n // we've got the property, add it now\n if (addColumnFromProperty(nextDescriptor)) {\n propertiesIndexes.put(nextOrderedProp, columnIndex++);\n }\n }\n }\n }\n for (PropertyDescriptor nextDescriptor : pds) {\n // only add columns that are left unordered\n if (!propertiesIndexes.containsKey(nextDescriptor.getName())) {\n if (addColumnFromProperty(nextDescriptor)) {\n propertiesIndexes.put(nextDescriptor.getName(), columnIndex++);\n }\n }\n }\n }\n\n /** Adds new column binding from a given property descriptor */\n protected boolean addColumnFromProperty(PropertyDescriptor descriptor) {\n // check the property can be read and it's not specific types\n if (!excludeProperties.contains(descriptor.getName())\n && descriptor.getReadMethod() != null) {\n columns.add(descriptor);\n columnNames.add(getColumnName(descriptor.getName()));\n return true;\n }\n return false;\n }\n\n /** Attempts to construct column name depending on bundles available */\n protected String getColumnName(String propertyName) {\n if ( resourceBundle != null && resourcePrefix != null ) {\n // use bundle string if all is set and it's available\n String bundleString = resourcePrefix + \".\" + propertyName;\n if ( resourceBundle.containsKey(bundleString) )\n return resourceBundle.getString(bundleString);\n else\n Logger.getLogger(getClass().getName()).log(\n Level.WARNING, \"Resource bundle does not contain property name: {0}\", bundleString);\n }\n // use just a property name\n return convertPropertyToColumnName(propertyName);\n }\n\n /**\n * Primitively constructs display name out of Java bean property name\n * @param name Property name in camel case\n * @return Readable name\n */\n protected String convertPropertyToColumnName(String name) {\n // convert to primitive name\n String propertyNameCap = name.substring(0, 1).toUpperCase() + name.substring(1);\n String value = \"\";\n int lastIdx = 0;\n // i = 1 - skip first uppercase\n for (int i = 1; i < propertyNameCap.length(); i++) {\n if ( Character.isUpperCase(propertyNameCap.charAt(i)) ) {\n // split with space\n value = value + propertyNameCap.substring(lastIdx, i) + \" \";\n lastIdx = i;\n }\n }\n // add last portion\n value = value + propertyNameCap.substring(lastIdx, propertyNameCap.length());\n return value;\n }\n\n}", "\tpublic static class SearchResultItem {\n\t\t\n\t\tprivate final Logger logger = LoggerFactory.getLogger(this.getClass().getName());\n\t\t\n\t\tpublic String id; // the id in the search result html page\n\t\tpublic String buyout;\n\t\tpublic String name;\n\t\tpublic String ign;\n\t\tpublic boolean corrupted;\n\t\tpublic boolean identified;\n\t\tpublic Rarity rarity;\n\t\t\n\t\tpublic String dataHash; // use for verify\n\t\t\n\t\tpublic String socketsRaw;\n\t\tpublic String stackSize;\n\t\t\n\t\tpublic String quality;\n\t\t\n\t\tpublic String physDmgRangeAtMaxQuality;\n\t\tpublic String physDmgAtMaxQuality;\n\t\tpublic String eleDmgRange;\n\t\tpublic String attackSpeed;\n\t\tpublic String dmgAtMaxQuality;\n\t\tpublic String crit;\n\t\tpublic String level;\n\t\tpublic String eleDmg;\n\t\t\n\t\tpublic String armourAtMaxQuality;\n\t\tpublic String evasionAtMaxQuality;\n\t\tpublic String energyShieldAtMaxQuality;\n\t\tpublic String block;\n\t\t\n\t\tpublic String reqLvl;\n\t\tpublic String reqStr;\n\t\tpublic String reqInt;\n\t\tpublic String reqDex;\n\t\tpublic String mapQuantity;\n\n\t\tpublic String ageAndHighLvl;\n\t\tpublic String league;\n\t\tpublic String seller;\n\t\tpublic String thread;\n\t\tpublic String sellerid;\n\t\tpublic String threadUrl;\n\t\tpublic String online;\n\t\t\n\t\tpublic String imageUrl;\n\n\t\tpublic Mod implicitMod;\n\t\tpublic List<Mod> explicitMods = new ArrayList<>();\n\t\tpublic Verify verified = Verify.UKNOWN;\n\t\tpublic boolean guildItem = false;\n\t\tpublic String wtb = null;\n\t\tpublic String guildDiscount = null;\n\t\tpublic boolean newInAutomated = false;\n\t\t\n\t\tpublic List<Mod> getMods() {\n\t\t\tList<Mod> mods = explicitMods.stream().collect(Collectors.toList());\n\t\t\tif (implicitMod != null) {\n\t\t\t\tmods.add(0, new Mod(\"--------------\", null));\n\t\t\t\tmods.add(0, implicitMod);\n\t\t\t}\n\t\t\treturn mods;\n\t\t}\n\t\t\n\t\tpublic List<String> getReqs() {\n\t\t\treturn labelList(\n\t\t\t\t\tlabelVal(\"Lvl\", reqLvl), \n\t\t\t\t\tlabelVal(\"Str\", reqStr),\n\t\t\t\t\tlabelVal(\"Dex\", reqDex),\n\t\t\t\t\tlabelVal(\"Int\", reqInt));\n\t\t}\n\t\t\n\t\tpublic List<String> getItem() {\n\t\t\treturn labelList(\n\t\t\t\t\tlabelVal(\"No\", idFinal()),\n\t\t\t\t\tlabelVal(\"Name\", nameFinal()), \n\t\t\t\t\tlabelVal(\"League\", league),\n\t\t\t\t\tlabelVal(\"Quality\", quality), \n\t\t\t\t\tlabelVal(\"Identified\", String.valueOf(identified)), \n\t\t\t\t\tlabelVal(\"Corrupted\", String.valueOf(corrupted)), \n\t\t\t\t\tlabelVal(\"SocketsRaw\", socketsRaw),\n\t\t\t\t\tlabelVal(\"StackSize\", stackSize),\n\t\t\t\t\tlabelVal(\"MapQuantity\", mapQuantity));\n\t\t}\n\t\t\n\t\tpublic List<String> getOffense() {\n\t\t\treturn labelList(\n\t\t\t\t\tlabelVal(\"pDPS\", physDmgAtMaxQuality), \n\t\t\t\t\tlabelVal(\"eDPS\", eleDmg), \n\t\t\t\t\tlabelVal(\"DPS\", dmgAtMaxQuality), \n\t\t\t\t\tlabelVal(\"APS\", attackSpeed), \n\t\t\t\t\tlabelVal(\"ele\", eleDmgRange),\n\t\t\t\t\tlabelVal(\"phys\", physDmgRangeAtMaxQuality));\n\t\t}\n\t\t\n\t\tpublic List<String> getDefense() {\n\t\t\treturn labelList(\n\t\t\t\t\tlabelVal(\"Armour\", armourAtMaxQuality), \n\t\t\t\t\tlabelVal(\"Evasion\", evasionAtMaxQuality), \n\t\t\t\t\tlabelVal(\"ES\", energyShieldAtMaxQuality), \n\t\t\t\t\tlabelVal(\"Block\", block), \n\t\t\t\t\tlabelVal(\"Crit\", crit),\n\t\t\t\t\tlabelVal(\"Map-Gem Lvl\", level));\n\t\t}\n\t\t\n\t\tprivate List<String> labelList(String ... labels) {\n\t\t\treturn asList(labels).stream()\n\t\t\t\t\t.filter(Objects::nonNull)\n\t\t\t\t\t.collect(toList());\n\t\t}\n\n\t\tpublic List<String> getSeller() {\n\t\t\tString highestLvl = substringAfter(ageAndHighLvl, \"h\");\n\t\t\tString age = substringBetween(ageAndHighLvl, \"a\", \"h\");\n\t\t\tage = StringUtils.isNumeric(age) ? now().minusDays(parseInt(age)).format(ofPattern(\"MMM dd uuuu\")) : age;\n\t\t\treturn labelList(\n\t\t\t\t\tlabelVal(\"IGN\", ign),\n\t\t\t\t\tlabelVal(\"Joined\", age),\n\t\t\t\t\tlabelVal(\"HighestLvl\", highestLvl),\n\t\t\t\t\tlabelVal(\"Account\", seller),\n\t\t\t\t\tlabelVal(\"Thread\", thread),\n\t\t\t\t\tlabelVal(\"Verified\", verified.name()),\n//\t\t\t\t\tlabelVal(\"\", threadUrl),\n\t\t\t\t\tlabelVal(\"Online\", String.valueOf(containsIgnoreCase(online, \"online\"))));\n\t\t}\n\t\t\n\t\tprivate String labelVal(String label, String val) {\n\t\t\treturn trimToNull(val) == null ? null : label + \": \" + val;\n\t\t}\n\n\t\tpublic String wtb() {\n\t\t\tif (wtb != null) {\n\t\t\t\treturn wtb;\n\t\t\t}\n\t\t\treturn String.format(\n\t\t\t\t\t\"@%s Hi, WTB your \\\"%s\\\" listed for %s in %s league.\",\n\t\t\t\t\tign, name, buyout, league);\n\t\t}\n\t\t\n\t\tpublic void wtb(String wtb) {\n\t\t\tthis.wtb = wtb;\n\t\t}\n\t\t\n\t\tpublic void guildDiscount(String guildDiscount) {\n\t\t\tthis.guildDiscount = guildDiscount;\n\t\t}\n\t\t\n\t\tpublic String guildDiscount() {\n\t\t\treturn guildDiscount;\n\t\t}\n\t\t\n\t\tpublic boolean newInAutomated() {\n\t\t\treturn newInAutomated;\n\t\t}\n\n\t\t/**\n\t\t * @author thirdy\n\t\t *\n\t\t */\n\t\tpublic static class Mod {\n\t\t\tString name;\n\t\t\tString value;\n\t\t\tString forgottenMod;\n\n\t\t\tpublic Mod(String name, String value) {\n\t\t\t\tthis.name = name;\n\t\t\t\tthis.value = value;\n\t\t\t}\n\t\t\t\n\t\t\tpublic String getName() {\n\t\t\t\treturn name;\n\t\t\t}\n\n\t\t\tpublic String getValue() {\n\t\t\t\treturn value;\n\t\t\t}\n\t\t\t\n\t\t\tpublic String getForgottenMod() {\n\t\t\t\treturn forgottenMod;\n\t\t\t}\n\n\t\t\tpublic void setForgottenMod(String forgottenMod) {\n\t\t\t\tthis.forgottenMod = forgottenMod;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n//\t\t\t\treturn System.lineSeparator() + \"Mod [name=\" + name + \", value=\" + value + \"]\";\n\t\t\t\tif (forgottenMod != null) {\n\t\t\t\t\treturn forgottenMod;\n\t\t\t\t}\n\t\t\t\treturn toStringDisplay();\n\t\t\t}\n\n\t\t\t/* Convert the ff into human readable form:\n\t\t\t #Socketed Gems are Supported by level # Increased Area of Effect\n\t\t\t\t##% increased Physical Damage\n\t\t\t\t#+# to Strength\n\t\t\t\t#+# to Accuracy Rating\n\t\t\t\t#+# Mana Gained on Kill\n\t\t\t\t#+# to Weapon range\n\t\t\t */\n\t\t\tpublic String toStringDisplay() {\n\t\t\t\tString display = name;\n\t\t\t\tif (StringUtils.startsWith(name, \"#\") || StringUtils.startsWith(name, \"$\")) {\n\t\t\t\t\tdisplay = StringUtils.removeStart(display, \"#\");\n\t\t\t\t\tdisplay = StringUtils.removeStart(display, \"$\");\n\t\t\t\t\tString val = StringUtils.endsWith(value, \".0\") ? StringUtils.substringBefore(value, \".0\") : value;\n\t\t\t\t\tdisplay = StringUtils.replaceOnce(display, \"#\", val);\n\t\t\t\t}\n\t\t\t\treturn display;\n\t\t\t}\n\t\t\t\n\t\t\tpublic String toUUID() {\n\t\t\t\treturn name + \":\" + value;\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic String toDisplay(String newLine) {\n\t\t\tStringBuilder builder = new StringBuilder();\n\t\t\tString _quality = isNotBlank(quality) ? \" \" + quality + \"%\" : \"\";\n\t\t\tString linksocks = isNotBlank(socketsRaw) ? \" \" + socketsRaw : \"\";\n\t\t\tString strCorrupt = corrupted ? \" Corrupted \" : \"\";\n\t\t\tstrCorrupt += !identified ? \" Unidentified \" : \"\";\n\t\t\tbuilder.append(format(\"[%s] %s%s%s\", id, name, linksocks, _quality));\n\t\t\tbuilder.append(format(\"%s -----%s------ \", newLine, strCorrupt));\n\t\t\tbuilder.append(newLine);\n\t\t\tif (implicitMod != null) {\n\t\t\t\tbuilder.append(format(\"%s\", implicitMod.toStringDisplay()));\n\t\t\t\tbuilder.append(newLine + \" ----------- \" + newLine);\n\t\t\t}\n\t\t\tif (explicitMods.size() > 0) {\n\t\t\t\tfor (Mod mod : explicitMods) {\n\t\t\t\t\tbuilder.append(format(\"%s\", mod.toStringDisplay()));\n\t\t\t\t\tbuilder.append(newLine);\n\t\t\t\t}\n\t\t\t\tbuilder.append(\"-----------\" + newLine);\n\t\t\t}\n\t\t\tString _physDmg \t= isNotBlank(physDmgAtMaxQuality) ? (\"pDPS \" + physDmgAtMaxQuality) : \"\";\n\t\t\tString _eleDmg \t\t= isNotBlank(eleDmg) \t\t\t ? (\"eDPS \" + eleDmg) : \"\";\n\t\t\tString _attackSpeed = isNotBlank(attackSpeed) \t\t ? (\"APS \" + attackSpeed) : \"\";\n\t\t\tString _crit \t\t= isNotBlank(crit) \t\t\t\t ? (\"Cc \" + crit) : \"\";\n\t\t\tString offense = format(\"%s %s %s %s\", _physDmg, _eleDmg, _attackSpeed, _crit).trim();\n\t\t\toffense = offense.isEmpty() ? \"\" : (offense + newLine);\n\t\t\tbuilder.append(offense);\n\t\t\t\n\t\t\tString _armour \t\t= isNotBlank(armourAtMaxQuality) \t? (\"Ar \" + armourAtMaxQuality) : \"\";\n\t\t\tString _evasion \t= isNotBlank(evasionAtMaxQuality) \t? (\"Ev \" + evasionAtMaxQuality) : \"\";\n\t\t\tString _energyShield = isNotBlank(energyShieldAtMaxQuality) ? (\"Es \" + energyShieldAtMaxQuality) : \"\";\n\t\t\tString _block \t\t= isNotBlank(block) \t\t\t\t? (\"Bk \" + block) : \"\";\n\t\t\tString defense = format(\"%s %s %s %s\", _armour, _evasion, _energyShield, _block).trim();\n\t\t\tdefense = defense.isEmpty() ? \"\" : (defense + newLine);\n\t\t\tbuilder.append(defense);\n\t\t\t\n\t\t\tbuilder.append(format(\"%s IGN: %s\", buyout, ign));\n\t\t\treturn builder.toString();\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\tStringBuilder builder = new StringBuilder();\n\t\t\tString lineSeparator = System.lineSeparator();\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"id=\");\n\t\t\tbuilder.append(id);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"buyout=\");\n\t\t\tbuilder.append(buyout);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"name=\");\n\t\t\tbuilder.append(name);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"corrupted=\");\n\t\t\tbuilder.append(corrupted);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"identified=\");\n\t\t\tbuilder.append(identified);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"ign=\");\n\t\t\tbuilder.append(ign);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"socketsRaw=\");\n\t\t\tbuilder.append(socketsRaw);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"stackSize=\");\n\t\t\tbuilder.append(stackSize);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"quality=\");\n\t\t\tbuilder.append(quality);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"physDmgRangeAtMaxQuality=\");\n\t\t\tbuilder.append(physDmgRangeAtMaxQuality);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"physDmgAtMaxQuality=\");\n\t\t\tbuilder.append(physDmgAtMaxQuality);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"eleDmgRange=\");\n\t\t\tbuilder.append(eleDmgRange);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"attackSpeed=\");\n\t\t\tbuilder.append(attackSpeed);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"dmgAtMaxQuality=\");\n\t\t\tbuilder.append(dmgAtMaxQuality);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"crit=\");\n\t\t\tbuilder.append(crit);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"level=\");\n\t\t\tbuilder.append(level);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"eleDmg=\");\n\t\t\tbuilder.append(eleDmg);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"armourAtMaxQuality=\");\n\t\t\tbuilder.append(armourAtMaxQuality);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"evasionAtMaxQuality=\");\n\t\t\tbuilder.append(evasionAtMaxQuality);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"energyShieldAtMaxQuality=\");\n\t\t\tbuilder.append(energyShieldAtMaxQuality);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"block=\");\n\t\t\tbuilder.append(block);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"reqLvl=\");\n\t\t\tbuilder.append(reqLvl);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"reqStr=\");\n\t\t\tbuilder.append(reqStr);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"reqInt=\");\n\t\t\tbuilder.append(reqInt);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"reqDex=\");\n\t\t\tbuilder.append(reqDex);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"mapQuantity=\");\n\t\t\tbuilder.append(mapQuantity);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"ageAndHighLvl=\");\n\t\t\tbuilder.append(ageAndHighLvl);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"league=\");\n\t\t\tbuilder.append(league);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"seller=\");\n\t\t\tbuilder.append(seller);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"thread=\");\n\t\t\tbuilder.append(thread);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"sellerid=\");\n\t\t\tbuilder.append(sellerid);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"threadUrl=\");\n\t\t\tbuilder.append(threadUrl);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"imageUrl=\");\n\t\t\tbuilder.append(imageUrl);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"implicitMod=\");\n\t\t\tbuilder.append(implicitMod);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"explicitMods=\");\n\t\t\tbuilder.append(explicitMods);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\tbuilder.append(\"online=\");\n\t\t\tbuilder.append(online);\n\t\t\tbuilder.append(lineSeparator);\n\t\t\treturn builder.toString();\n\t\t}\n\n//\t\tpublic String getId() {\n//\t\t\treturn id;\n//\t\t}\n\n\t\tpublic String getBo() {\n\t\t\tString str = buyout;\n\t\t\tstr = StringUtils.replace(str, \"alteration\", \"alt\");\n\t\t\tstr = StringUtils.replace(str, \"fusing\", \"fuse\");\n\t\t\tstr = StringUtils.replace(str, \"jewellers\", \"jew\");\n\t\t\tstr = StringUtils.replace(str, \"exalted\", \"ex\");\n\t\t\tstr = StringUtils.replace(str, \"alchemy\", \"alch\");\n\t\t\tstr = StringUtils.replace(str, \"chaos\", \"ch\");\n\t\t\tstr = StringUtils.replace(str, \"chromatic\", \"chrm\");\n\t\t\tstr = StringUtils.replace(str, \"chance\", \"chan\");\n\t\t\treturn str;\n\t\t}\n\n//\t\tpublic String getPseudoEleResistance() {\n//\t\t\treturn getExplicitModValueByName(\"#(pseudo) +#% total Elemental Resistance\");\n//\t\t}\n//\n//\t\tpublic String getPseudoLife() {\n//\t\t\treturn getExplicitModValueByName(\"#(pseudo) (total) +# to maximum Life\");\n//\t\t}\n//\t\t\n//\t\tpublic String getFireRes() {\n//\t\t\treturn getExplicitModValueByName(\"#+#% to Fire Resistance\");\n//\t\t}\n//\t\t\n//\t\tpublic String getColdRes() {\n//\t\t\treturn getExplicitModValueByName(\"#+#% to Cold Resistance\");\n//\t\t}\n//\t\t\n//\t\tpublic String getLightRes() {\n//\t\t\treturn getExplicitModValueByName(\"#+#% to Light Resistance\");\n//\t\t}\n\t\t\n//\t\tprivate String getExplicitModValueByName(String name) {\n//\t\t\tfor (Mod mod : explicitMods) {\n//\t\t\t\tif (mod.getName().equalsIgnoreCase(name)) {\n//\t\t\t\t\treturn mod.getValue();\n//\t\t\t\t}\n//\t\t\t}\n//\t\t\treturn \"\";\n//\t\t}\n\n\t\t/**\n\t\t * Used for showing exceptions in the result table.\n\t\t */\n\t\tpublic static SearchResultItem exceptionItem(Exception e) {\n\t\t\tSearchResultItem item = new SearchResultItem();\n\t\t\titem.name = e.getMessage();\n\t\t\titem.ign = e.getClass().getName();\n\t\t\titem.socketsRaw = e.getCause().getMessage();\n\t\t\treturn item;\n\t\t}\n\n\t\tpublic String seller() {\n\t\t\treturn seller;\n\t\t}\n\t\t\n\t\tpublic String dataHash() {\n\t\t\treturn dataHash;\n\t\t}\n\t\t\n\t\tpublic String thread() {\n\t\t\treturn thread;\n\t\t}\n\n\t\tpublic String toShortDebugInfo() {\n\t\t\treturn String.format(\"id=%s name=%s account=%s thread=%s\", id, name, seller, thread);\n\t\t}\n\n\t\tpublic void verified(Verify verified) {\n\t\t\tthis.verified = verified;\n\t\t}\n\t\t\n\t\tpublic void guildItem(boolean guildItem) {\n\t\t\tthis.guildItem = guildItem;\n\t\t}\n\t\t\n\t\tpublic String nameFinal() {\n\t\t\treturn name;\n\t\t}\n\t\t\n\t\tpublic String idFinal() {\n\t\t\tif (corrupted) {\n\t\t\t\treturn id + \" [CORRUPTED]\";\n\t\t\t}\n\t\t\treturn id;\n\t\t}\n\t\t\n\t\tpublic ImageIcon getArt() {\n\t\t\tImageIcon imageIcon = null;\n\t\t\ttry {\n\t\t\t\tboolean artEnabled = Config.getBooleanProperty(Config.RESULT_TABLE_ART_ENABLED, true);\n\t\t\t\tif (artEnabled) {\n\t\t\t\t\tURL url = new URL(imageUrl);\n\t\t\t\t\timageIcon = ImageCache.getInstance().get(url.toString());\n\t\t\t\t}\n\t\t\t} catch (MalformedURLException e) {\n\t\t\t\tlogger.error(\"Error while grabbing art from: \" + imageUrl, e);\n\t\t\t}\n\t\t\treturn imageIcon;\n\t\t}\n\t\t\n\t\tpublic int toUUID() {\n\t\t\tString explicitModsUUID = explicitMods.stream().map(Mod::toUUID).collect(Collectors.joining(\":\"));\n\t\t\tString implicitModuuid = implicitMod != null ? implicitMod.toUUID() : null;\n\t\t\tList<String> uuidList = asList(thread, name, buyout, String.valueOf(corrupted), socketsRaw, quality, \n\t\t\t\t\tphysDmgRangeAtMaxQuality, physDmgAtMaxQuality, eleDmgRange, attackSpeed, dmgAtMaxQuality, crit, level, eleDmg,\n\t\t\t\t\tarmourAtMaxQuality, evasionAtMaxQuality, energyShieldAtMaxQuality, block, mapQuantity, implicitModuuid, explicitModsUUID);\n\t\t\tString uuid = uuidList.stream().collect(Collectors.joining(\":\"));\n\t\t\treturn Integer.valueOf(uuid.hashCode());\n\t\t}\n\t\t\n\t\tpublic boolean guildItem() {\n\t\t\treturn guildItem;\n\t\t}\n\n\t\tpublic static enum Rarity {\n\t\t\tnormal,\n\t\t\tmagic,\n\t\t\trare,\n\t\t\tunique,\n\t\t\tgem,\n\t\t\tcurrency,\n\t\t\tdivinationcard, \n\t\t\tunknown;\n\t\t\t\n\t\t\tpublic static Rarity valueOf(int ordinal) {\n\t\t\t\tfor (Rarity r : values()) {\n\t\t\t\t\tif (r.ordinal() == ordinal) return r;\n\t\t\t\t}\n\t\t\t\treturn unknown;\n\t\t\t}\n\t\t}\n\t}", "public class ArtColumnRenderer extends DefaultTableCellRenderer {\r\n\t\r\n\tprivate static final long serialVersionUID = 1L;\r\n\t\r\n\tprivate Color bgColor;\r\n\tprivate Color guildColor;\r\n\tprivate Color autoHighlightColor;\r\n\tprivate BeanPropertyTableModel<SearchResultItem> model;\r\n\r\n\r\n\tpublic ArtColumnRenderer(BeanPropertyTableModel<SearchResultItem> model, Color bgColor, Color guildColor, Color autoHighlightColor) {\r\n\t\tthis.bgColor = bgColor;\r\n\t\tthis.guildColor = guildColor;\r\n\t\tthis.autoHighlightColor = autoHighlightColor;\r\n\t\tthis.model = model;\r\n\t\tsetHorizontalAlignment(JLabel.CENTER);\r\n\t}\r\n\t\r\n\t@Override\r\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {\r\n super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\r\n setText(\"\");\r\n setIcon(null);\r\n \r\n\t\tif (isSelected) {\r\n\t\t\tsetBackground(table.getSelectionBackground());\r\n\t\t} else {\r\n\t\t\tsetBackground(bgColor != null ? bgColor : table.getBackground());\r\n\t\t\tif (!model.getData().isEmpty()) {\r\n\t\t\t\tSearchResultItem item = model.getData().get(row);\r\n\t\t\t\tif (item.newInAutomated()) {\r\n\t\t\t\t\tsetBackground(autoHighlightColor);\r\n\t\t\t\t} else if (item.guildItem()) {\r\n\t\t\t\t\tsetBackground(guildColor);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n boolean artEnabled = Config.getBooleanProperty(Config.RESULT_TABLE_ART_ENABLED, true);\r\n if (artEnabled && value != null) {\r\n// \tImageIcon image = defaultImage;\r\n// \tImageIcon img = ImageCache.getInstance().get(value.toString());\r\n// if (img != null) {\r\n// \timage = img;\r\n// \t\t}\r\n \tImageIcon image = (ImageIcon) value;\r\n setIcon(image);\r\n// table.setRowHeight(row, image.getIconHeight());\r\n\t\t}\r\n \r\n return this;\r\n }\r\n\r\n}\r", " public class MultiLineTableCellRenderer extends JTextArea implements TableCellRenderer {\r\nprivate static final long serialVersionUID = 1L;\r\n\t\r\nprivate List<List<Integer>> rowColHeight = new ArrayList<List<Integer>>();\r\nprivate static final EmptyBorder EMPTY_BORDER = new EmptyBorder(1, 2, 1, 2);\r\n\t\r\nprivate Color bgColor;\r\nprivate Color guildColor;\r\n private Color corruptedColor;\r\nprivate Color autoHighlightColor;\r\n\r\nprivate BeanPropertyTableModel<SearchResultItem> model;\r\n\r\n \r\n public MultiLineTableCellRenderer(BeanPropertyTableModel<SearchResultItem> model, Color bgColor, Color guildColor, Color corruptedColor, Color autoHighlightColor) {\r\n setLineWrap(true);\r\n setWrapStyleWord(true);\r\n setOpaque(true);\r\n this.bgColor = bgColor;\r\n this.guildColor = guildColor;\r\n this.corruptedColor=corruptedColor;\r\n this.autoHighlightColor = autoHighlightColor;\r\n this.model = model;\r\n }\r\n\r\npublic Component getTableCellRendererComponent(JTable table, Object value, \r\n\t\tboolean isSelected, boolean hasFocus, int row, int column) {\r\n\tif (isSelected) {\r\n\t\tsetForeground(table.getSelectionForeground());\r\n\t\tsetBackground(table.getSelectionBackground());\r\n\t} else {\r\n\t\tsetForeground(table.getForeground());\r\n\t\tsetBackground(bgColor != null ? bgColor : table.getBackground());\r\n\t\tif (!model.getData().isEmpty()) {\r\n\t\t\tSearchResultItem item = model.getData().get(row);\r\n\t\t\tif (item.newInAutomated()) {\r\n\t\t\t\tsetBackground(autoHighlightColor);\r\n\t\t\t} else if (item.guildItem()) {\r\n\t\t\t\tsetBackground(guildColor);\r\n\t\t\t}\r\n if(item.corrupted) {\r\n this.setForeground(corruptedColor);\r\n }\r\n\t\t}\r\n\t}\r\n\tsetFont(table.getFont());\r\n\r\n\tif (hasFocus) {\r\n\t\tsetBorder(UIManager.getBorder(\"Table.focusCellHighlightBorder\"));\r\n\t\tif (table.isCellEditable(row, column)) {\r\n\t\t\tsetForeground(UIManager.getColor(\"Table.focusCellForeground\"));\r\n\t\t\tsetBackground(UIManager.getColor(\"Table.focusCellBackground\"));\r\n\t\t}\r\n\t} else {\r\n\t\tsetBorder(EMPTY_BORDER);\r\n\t}\r\n\r\n\tif (value != null) {\r\n\t\tif (value instanceof List) {\r\n\t\t\t@SuppressWarnings(\"rawtypes\")\r\n\t\t\tList list = (List) value;\r\n\t\t\tString s = StringUtils.join(list, System.lineSeparator());\r\n\t\t\tsetText(s);\r\n\t\t} else {\r\n\t\t\tsetText(value.toString());\r\n\t\t}\r\n\t} else {\r\n\t\tsetText(\"\");\r\n\t}\r\n\r\n\tadjustRowHeight(table, row, column);\r\n\treturn this;\r\n}\r\n \r\n /**\r\n * Calculate the new preferred height for a given row, and sets the height on the table.\r\n */\r\n private void adjustRowHeight(JTable table, int row, int column) {\r\n //The trick to get this to work properly is to set the width of the column to the\r\n //textarea. The reason for this is that getPreferredSize(), without a width tries\r\n //to place all the text in one line. By setting the size with the with of the column,\r\n //getPreferredSize() returnes the proper height which the row should have in\r\n //order to make room for the text.\r\n int cWidth = table.getTableHeader().getColumnModel().getColumn(column).getWidth();\r\n setSize(new Dimension(cWidth, 1000));\r\n int prefH = getPreferredSize().height;\r\n while (rowColHeight.size() <= row) {\r\n rowColHeight.add(new ArrayList<Integer>(column));\r\n }\r\n List<Integer> colHeights = rowColHeight.get(row);\r\n while (colHeights.size() <= column) {\r\n colHeights.add(0);\r\n }\r\n colHeights.set(column, prefH);\r\n int maxH = prefH;\r\n for (Integer colHeight : colHeights) {\r\n if (colHeight > maxH) {\r\n maxH = colHeight;\r\n }\r\n }\r\n if (table.getRowHeight(row) < maxH) {\r\n table.setRowHeight(row, maxH);\r\n }\r\n }\r\n }", "public class VerifierTask extends SwingWorker<Integer, SearchResultItem> {\r\n\tprivate final Logger logger = LoggerFactory.getLogger(this.getClass().getName());\r\n\tprivate Consumer<Integer> resultConsumer;\r\n\tprivate Consumer<Exception> onException;\r\n\tprivate Consumer<List<SearchResultItem>> consumer;\r\n\tprivate List<SearchResultItem> itemResults;\r\n\tprivate long sleep = -1;\r\n\tprivate boolean skipIfSold = false;\r\n\r\n\tpublic VerifierTask(List<SearchResultItem> itemResults, Consumer<List<SearchResultItem>> consumer, Consumer<Integer> resultConsumer, Consumer<Exception> onException, long sleep, boolean skipIfSold) {\r\n\t\tthis.itemResults = itemResults;\r\n\t\tthis.consumer = consumer;\r\n\t\tthis.resultConsumer = resultConsumer;\r\n\t\tthis.onException = onException;\r\n\t\tthis.sleep = sleep;\r\n\t\tthis.skipIfSold = skipIfSold;\r\n\t}\r\n\t\r\n\tpublic VerifierTask(List<SearchResultItem> itemResults, Consumer<List<SearchResultItem>> consumer, Consumer<Integer> resultConsumer, Consumer<Exception> onException) {\r\n\t\tthis.itemResults = itemResults;\r\n\t\tthis.consumer = consumer;\r\n\t\tthis.resultConsumer = resultConsumer;\r\n\t\tthis.onException = onException;\r\n\t}\r\n\r\n\t@Override\r\n protected Integer doInBackground() {\r\n\t\tint countAfterVerify = runVerify(itemResults);\r\n return countAfterVerify;\r\n }\r\n\r\n\tprivate int runVerify(List<SearchResultItem> itemResults) {\r\n\t\treturn itemResults.stream()\r\n\t\t\t.mapToInt(item -> {\r\n\t\t\t\tint result = 0;\r\n\t\t\t\t\r\n\t\t\t\tlogger.info(format(\"Verifying item %s\", item.toShortDebugInfo()));\r\n\t\t\t\tVerify verified = DurianUtils.verify(item.thread(), item.dataHash());\r\n\t\t\t\titem.verified(verified);\r\n\t\t\t\tlogger.info(format(\"Verify result for item %s: %s\", item.toShortDebugInfo(), verified));\r\n\t\t\t\t\r\n\t\t\t\tboolean skip = skipIfSold && verified == SOLD;\r\n\t\t\t\tif (!skip) {\r\n\t\t\t\t\tpublish(item);\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif (verified == Verify.VERIFIED) {\r\n\t\t\t\t\tresult = 1;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif (sleep != -1) {\r\n\t\t\t\t\tlogger.info(format(\"Verify - now sleeping for %s millisec\", sleep));\r\n\t\t\t\t\tsleep(sleep);\r\n\t\t\t\t}\r\n\t\t\t\treturn result;\r\n\t\t\t}).sum();\r\n\t}\r\n\r\n @Override\r\n protected void process(List<SearchResultItem> itemResults) {\r\n \tconsumer.accept(itemResults);\r\n }\r\n \r\n @Override\r\n protected void done() {\r\n\t\ttry {\r\n\t\t\tresultConsumer.accept(get());\r\n\t\t} catch (Exception e) {\r\n\t\t\tonException.accept(e);\r\n\t\t}\r\n }\r\n}", "public class Config {\r\n\t\r\n\tpublic static final String CONFIG_PROPERTIES_FILENAME = \"config.properties\";\r\n\tpublic static final String GUILD_LIST_FILENAME = \"guild.txt\";\r\n\t\r\n\tpublic static final String AUTOMATED_SEARCH_WAIT_MINUTES = \"automated.search.wait.minutes\";\r\n\tpublic static final String AUTOMATED_SEARCH_INBETWEEN_WAIT_SECONDS = \"automated.search.inbetween.wait.seconds\";\r\n\tpublic static final String MANUAL_SEARCH_PREFIX = \"manual.search.prefix\";\r\n\tpublic static final String AUTOMATED_SEARCH_PREFIX = \"automated.search.prefix\";\r\n\tpublic static final String AUTOMATED_SEARCH_SOUND_FILENAME = \"automated.search.sound.filename\";\r\n\tpublic static final String AUTOMATED_SEARCH_SOUND_VOLUME = \"automated.search.sound.volume\";\r\n\tpublic static final String AUTOMATED_SEARCH_SOUND_MODE = \"automated.search.sound.mode\";\r\n\tpublic static final String AUTOMATED_SEARCH_ENABLED = \"automated.search.enabled\";\r\n\tpublic static final String AUTOMATED_SEARCH_NOTIFY_NEWONLY = \"automated.search.notify.newonly\";\r\n\tpublic static final String AUTOMATED_SEARCH_NOTIFY_NEWONLY_COLOR_HIGHLIGHT = \"automated.search.notify.newonly.color.highlight\";\r\n\tpublic static final String RESULT_TABLE_ART_ENABLED = \"result.table.art.enabled\";\r\n\tpublic static final String RESULT_TABLE_BG_COLOR = \"result.table.bg.color\";\r\n\t\r\n\tpublic static final String GUILD_DISCOUNT_STRING = \"guild.discount.string\";\r\n\tpublic static final String GUILD_COLOR_HIGHLIGHT = \"guild.color.highlight\";\r\n\tpublic static final String GUILD_DISCOUNT_STRING_DEFAULT = \"1ch\";\r\n\r\n\tpublic static final String CORRUPTED_COLOR_HIGHLIGHT = \"corrupted.color.highlight\";\r\n\t\r\n\tpublic static final String AUTOMATED_SEARCH_BLACKLIST = \"automated.search.blacklist\";\r\n\tpublic static final String MANUAL_SEARCH_BLACKLIST = \"manual.search.blacklist\";\r\n\t\r\n\tpublic static final String AUTOMATED_AUTO_VERIFY = \"automated.auto.verify\";\r\n\tpublic static final String MANUAL_AUTO_VERIFY = \"manual.auto.verify\";\r\n\t\r\n\tpublic static final String AUTOMATED_AUTO_VERIFY_SLEEP = \"automated.auto.verify.wait.millisec\";\r\n\tpublic static final String MANUAL_AUTO_VERIFY_SLEEP = \"manual.auto.verify.wait.millisec\";\r\n\r\n\tpublic static final String LOOK_AND_FEEL = \"lookandfeel\";\r\n\tpublic static final String LOOK_AND_FEEL_DECORATED = \"lookandfeel.decorated.enabled\";\r\n\r\n\tprivate static Properties config;\r\n\t\r\n\tpublic static void loadConfig() throws IOException, FileNotFoundException {\r\n\t\tconfig = new Properties();\r\n\t\ttry (BufferedReader br = new BufferedReader(new FileReader(new File(CONFIG_PROPERTIES_FILENAME)))) {\r\n\t\t\tconfig.load(br);\r\n\t\t}\r\n\t}\r\n \r\n public static String getPropety(String key, String defaultValue) {\r\n \treturn StringUtils.defaultIfBlank(config.getProperty(key, defaultValue), defaultValue);\r\n }\r\n\r\n\tpublic static boolean getBooleanProperty(String key, boolean defaultValue) {\r\n\t\tString propety = getPropety(key, String.valueOf(defaultValue));\r\n\t\treturn Boolean.parseBoolean(propety);\r\n\t}\r\n\r\n\tpublic static int getIntegerProperty(String key, int i) {\r\n\t\tString propety = getPropety(key, String.valueOf(i));\r\n\t\treturn Integer.parseInt(propety);\r\n\t}\r\n\t\r\n\tpublic static long getLongProperty(String key, long i) {\r\n\t\tString propety = getPropety(key, String.valueOf(i));\r\n\t\treturn Long.parseLong(propety);\r\n\t}\r\n\r\n\tpublic static double getDoubleProperty(String key, double i) {\r\n\t\tString propety = getPropety(key, String.valueOf(i));\r\n\t\treturn Double.parseDouble(propety);\r\n\t}\r\n\t\r\n\tpublic static SoundMode getSoundMode() {\r\n\t\tString propety = getPropety(AUTOMATED_SEARCH_SOUND_MODE, SoundMode.EACH_SEARCH.name());\r\n\t\treturn SoundMode.valueOf(propety);\r\n\t}\r\n\t\r\n\tpublic static enum SoundMode {\r\n\t\tEACH_SEARCH, ONCE\r\n\t}\r\n\r\n\tpublic static Properties getProperties() {\r\n\t\treturn config;\r\n\t}\r\n}\r", "public class SwingUtil {\n\t\n\tpublic static void openUrlViaBrowser(String url) {\n\t\tString s = url;\n\t\tif (Desktop.isDesktopSupported()) {\n\t\t\ttry {\n\t\t\t\tDesktop.getDesktop().browse(new URI(s));\n\t\t\t} catch (Exception e) {\n\t\t\t\tshowError(new BlackmarketException(\n\t\t\t\t\t\t\"Error on opening browser, address: \" + s + \": \" + e.getMessage(), e\n\t\t\t\t\t\t\t));\n\t\t\t}\n\t\t} else {\n\t\t\tshowError(new BlackmarketException(\"Launch browser failed, please manually visit: \" + s));\n\t\t}\n\t}\n\t\n\tpublic static void copyToClipboard(String s) {\n\t\tStringSelection stringSelection = new StringSelection(s);\n\t\t\tClipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();\n\t\t\tclpbrd.setContents(stringSelection, null);\n\t}\n\n\tpublic static void showError(Throwable e) {\n\t\tnew qic.util.SimpleExceptionHandler().uncaughtException(Thread.currentThread(), e);\n\t}\n\n}" ]
import static java.lang.String.format; import static java.util.Arrays.asList; import java.awt.Color; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.List; import java.util.function.Consumer; import javax.swing.ImageIcon; import javax.swing.JTable; import javax.swing.SwingUtilities; import javax.swing.table.TableColumnModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.porty.swing.table.model.BeanPropertyTableModel; import qic.SearchPageScraper.SearchResultItem; import qic.ui.extra.ArtColumnRenderer; import qic.ui.extra.MultiLineTableCellRenderer; import qic.ui.extra.VerifierTask; import qic.util.Config; import qic.util.SwingUtil;
/* * Copyright (C) 2015 thirdy * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package qic.ui; /** * @author thirdy * */ public class SearchResultTable extends JTable { private static final long serialVersionUID = 1L; private final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); private BeanPropertyTableModel<SearchResultItem> model; private VerifierTask autoVerifierTask; public SearchResultTable() { model = new BeanPropertyTableModel<>(SearchResultItem.class); model.setOrderedProperties( asList("art", "bo", "item", "seller", "reqs", "mods", "offense", "defense")); this.setModel(model); setupColumnWidths(); this.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { JTable table =(JTable) me.getSource(); Point p = me.getPoint(); int row = table.rowAtPoint(p); if (row > -1) { if (SwingUtilities.isLeftMouseButton(me)) { SearchResultItem searchResultItem = model.getData().get(row); SwingUtil.copyToClipboard(searchResultItem.wtb()); } if (SwingUtilities.isRightMouseButton(me)) { SearchResultItem searchResultItem = model.getData().get(row); VerifierTask manualVerifierTask = new VerifierTask(asList(searchResultItem), results -> updateData(row), verified -> {}, ex -> { logger.error("Error while running manual verify", ex); }); manualVerifierTask.execute(); } } } }); Color bgColor = Color.decode(Config.getPropety(Config.RESULT_TABLE_BG_COLOR, null)); Color guildColor = Color.decode(Config.getPropety(Config.GUILD_COLOR_HIGHLIGHT, "#f6b67f")); Color corruptedColor = Color.decode(Config.getPropety(Config.CORRUPTED_COLOR_HIGHLIGHT, "#000000")); Color autoHighlightColor = Color.decode( Config.getPropety(Config.AUTOMATED_SEARCH_NOTIFY_NEWONLY_COLOR_HIGHLIGHT, "#ccff99"));
this.setDefaultRenderer(List.class, new MultiLineTableCellRenderer(model, bgColor, guildColor, corruptedColor, autoHighlightColor));
3
realrolfje/anonimatron
src/main/java/com/rolfje/anonimatron/Anonimatron.java
[ "public class AnonymizerService {\n\tprivate static final Logger LOG = Logger.getLogger(AnonymizerService.class);\n\n\tprivate Map<String, Anonymizer> customAnonymizers = new HashMap<>();\n\tprivate Map<String, String> defaultTypeMapping = new HashMap<>();\n\n\tprivate SynonymCache synonymCache;\n\n\tprivate Set<String> seenTypes = new HashSet<>();\n\n\tpublic AnonymizerService() throws Exception {\n\t\tthis.synonymCache = new SynonymCache();\n\n\t\t// Custom anonymizers which produce more life-like data\n\t\tregisterAnonymizer(new StringAnonymizer());\n\t\tregisterAnonymizer(new UUIDAnonymizer());\n\t\tregisterAnonymizer(new RomanNameGenerator());\n\t\tregisterAnonymizer(new ElvenNameGenerator());\n\t\tregisterAnonymizer(new EmailAddressAnonymizer());\n\t\tregisterAnonymizer(new DutchBSNAnononymizer());\n\t\tregisterAnonymizer(new DutchBankAccountAnononymizer());\n\t\tregisterAnonymizer(new DutchZipCodeAnonymizer());\n\t\tregisterAnonymizer(new DigitStringAnonymizer());\n\t\tregisterAnonymizer(new CharacterStringAnonymizer());\n\t\tregisterAnonymizer(new CharacterStringPrefetchAnonymizer());\n\t\tregisterAnonymizer(new DateAnonymizer());\n\t\tregisterAnonymizer(new IbanAnonymizer());\n\n\t\tregisterAnonymizer(new CountryCodeAnonymizer());\n\n\t\t// Default anonymizers for plain Java objects. If we really don't\n\t\t// know or care how the data looks like.\n\t\tdefaultTypeMapping.put(String.class.getName(), new StringAnonymizer().getType());\n\t\tdefaultTypeMapping.put(Date.class.getName(), new DateAnonymizer().getType());\n\t}\n\n\tpublic AnonymizerService(SynonymCache synonymCache) throws Exception {\n\t\tthis();\n\t\tthis.synonymCache = synonymCache;\n\t}\n\n\tpublic void registerAnonymizers(List<String> anonymizers) {\n\t\tif (anonymizers == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tfor (String anonymizer : anonymizers) {\n\t\t\ttry {\n\t\t\t\t@SuppressWarnings(\"rawtypes\")\n\t\t\t\tClass anonymizerClass = Class.forName(anonymizer);\n\t\t\t\tregisterAnonymizer((Anonymizer)anonymizerClass.newInstance());\n\t\t\t} catch (Exception e) {\n\t\t\t\tLOG.fatal(\n\t\t\t\t\t\"Could not instantiate class \"\n\t\t\t\t\t\t\t+ anonymizer\n\t\t\t\t\t\t\t+ \". Please make sure that the class is on the classpath, \"\n\t\t\t\t\t\t\t+ \"and it has a default public constructor.\", e);\n\t\t\t}\n\t\t}\n\n\t\tLOG.info(anonymizers.size()+\" anonymizers registered.\");\n\t}\n\n\tpublic Set<String> getCustomAnonymizerTypes() {\n\t\treturn Collections.unmodifiableSet(customAnonymizers.keySet());\n\t}\n\n\tpublic Set<String> getDefaultAnonymizerTypes() {\n\t\treturn Collections.unmodifiableSet(defaultTypeMapping.keySet());\n\t}\n\n\tpublic Synonym anonymize(Column column, Object from) {\n\t\tif (from == null) {\n\t\t\treturn new NullSynonym(column.getType());\n\t\t}\n\n\t\t// Find for regular type\n\t\tSynonym synonym = getSynonym(column, from);\n\n\t\tif (synonym == null) {\n Anonymizer anonymizer = getAnonymizer(column.getType());\n synonym = anonymizer.anonymize(from, column.getSize(), column.isShortLived(), column.getParameters());\n\n\t\t\tsynonymCache.put(synonym);\n\t\t}\n\t\treturn synonym;\n\t}\n\n\tprivate Synonym getSynonym(Column c, Object from) {\n\t\tif (c.isShortLived()){\n\t\t\treturn null;\n\t\t}\n\n\t\tSynonym synonym = synonymCache.get(c.getType(), from);\n\t\tif (synonym == null) {\n\t\t\t// Fallback for default type\n\t\t\tsynonym = synonymCache.get(defaultTypeMapping.get(c.getType()), from);\n\t\t}\n\t\treturn synonym;\n\t}\n\n\tprivate void registerAnonymizer(Anonymizer anonymizer) {\n\t\tif (customAnonymizers.containsKey(anonymizer.getType())) {\n\t\t\t// Do not allow overriding Anonymizers\n\t\t\tthrow new UnsupportedOperationException(\n\t\t\t\t\t\"Could not register anonymizer with type \"\n\t\t\t\t\t\t\t+ anonymizer.getType()\n\t\t\t\t\t\t\t+ \" and class \"\n\t\t\t\t\t\t\t+ anonymizer.getClass().getName()\n\t\t\t\t\t\t\t+ \" because there is already an anonymizer registered for type \"\n\t\t\t\t\t\t\t+ anonymizer.getType());\n\t\t}\n\n\t\tcustomAnonymizers.put(anonymizer.getType(), anonymizer);\n\t}\n\n\n\n\tprivate Anonymizer getAnonymizer(String type) {\n\t\tif (type == null) {\n\t\t\tthrow new UnsupportedOperationException(\n\t\t\t\t\t\"Can not anonymyze without knowing the column type.\");\n\t\t}\n\n\t\tAnonymizer anonymizer = customAnonymizers.get(type);\n\t\tif (anonymizer == null) {\n\n\t\t\tif (!seenTypes.contains(type)) {\n\t\t\t\t// Log this unknown type\n\t\t\t\tLOG.warn(\"Unknown type '\" + type\n\t\t\t\t\t\t+ \"', trying fallback to default anonymizer for this type.\");\n\t\t\t\tseenTypes.add(type);\n\t\t\t}\n\n\t\t\t// Fall back to default if we don't know how to handle this\n\t\t\tanonymizer = customAnonymizers.get(defaultTypeMapping.get(type));\n\t\t}\n\n\t\tif (anonymizer == null) {\n\t\t\t// Fall back did not work, give up.\n\t\t\tthrow new UnsupportedOperationException(\n\t\t\t\t\t\"Do not know how to anonymize type '\" + type\n\t\t\t\t\t\t\t+ \"'.\");\n\t\t}\n\t\treturn anonymizer;\n\t}\n\n\tpublic boolean prepare(String type, Object databaseColumnValue) {\n\t\tAnonymizer anonymizer = getAnonymizer(type);\n\t\tif (anonymizer != null && anonymizer instanceof Prefetcher){\n\t\t\t((Prefetcher)anonymizer).prefetch(databaseColumnValue);\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tpublic SynonymCache getSynonymCache() {\n\t\treturn synonymCache;\n\t}\n}", "public class Hasher {\n\n\t// Ideally more iterations mean better protection against brute\n\t// force attacks. Since synonyms are accross the while dataset,\n\t// an attacker would only know the generated synonym type based\n\t// on the synonym file, but not the source date type or location.\n\tprivate static final int ITERATIONS = 64;\n\n\t// Roughly same space as version 4 UUID, more than 5 undecillion combinations,\n\t// very unlikely to generate collisions.\n\tprivate static final int SIZE = 128;\n\n\tprivate static final String ALGORITHM = \"PBKDF2WithHmacSHA1\";\n\tpublic static final Charset CHARSET = StandardCharsets.UTF_8;\n\tprivate byte[] salt;\n\n\tpublic Hasher(String salt) {\n\t\tthis.salt = salt.getBytes();\n\t}\n\n\tpublic String base64Hash(Object object) {\n\t\tbyte[] serialize = serialize(object);\n\t\tchar[] chars = toCharArray(serialize);\n\t\treturn new String(Base64Encoder.encode(pbkdf2(chars)));\n\t}\n\n\tpublic String base64Hash(String object) {\n\t\tbyte[] hash = pbkdf2(object.toCharArray());\n\t\treturn new String(Base64Encoder.encode(hash));\n\t}\n\n\tprivate char[] toCharArray(byte[] bytes) {\n\t\treturn new String(bytes, CHARSET).toCharArray();\n\t}\n\n\tprivate byte[] serialize(Object object) {\n\t\ttry {\n\t\t\tByteArrayOutputStream out = new ByteArrayOutputStream();\n\t\t\tObjectOutputStream objectOutputStream = new ObjectOutputStream(out);\n\t\t\tobjectOutputStream.writeObject(object);\n\t\t\tobjectOutputStream.close();\n\t\t\treturn out.toByteArray();\n\t\t} catch (IOException e) {\n\t\t\tthrow new RuntimeException(\"Unexpected problem serializing object.\", e);\n\t\t}\n\t}\n\n\tprivate byte[] pbkdf2(char[] password) {\n\t\tKeySpec spec = new PBEKeySpec(password, salt, ITERATIONS, SIZE);\n\t\ttry {\n\t\t\tSecretKeyFactory f = SecretKeyFactory.getInstance(ALGORITHM);\n\t\t\treturn f.generateSecret(spec).getEncoded();\n\t\t} catch (NoSuchAlgorithmException ex) {\n\t\t\tthrow new IllegalStateException(\"Missing algorithm: \" + ALGORITHM, ex);\n\t\t} catch (InvalidKeySpecException ex) {\n\t\t\tthrow new IllegalStateException(\"Invalid SecretKeyFactory\", ex);\n\t\t}\n\t}\n\n}", "public class SynonymCache {\n\n private Map<String, Map<Object, Synonym>> synonymCache = new HashMap<>();\n private Hasher hasher;\n private long size = 0;\n\n public SynonymCache() {\n }\n\n /**\n * Reads the synonyms from the specified file and (re-)initializes the\n * {@link #synonymCache} with it.\n *\n * @param synonymXMLfile the xml file containing the synonyms, as written by\n * {@link #toFile(File)}\n * @return Synonyms as the were stored on last run.\n * @throws MappingException When synonyms can not be read from file.\n * @throws IOException When synonyms can not be read from file.\n * @throws XMLException When synonyms can not be read from file.\n */\n public static SynonymCache fromFile(File synonymXMLfile) throws MappingException, IOException, XMLException {\n\n SynonymCache synonymCache = new SynonymCache();\n List<Synonym> synonymsFromFile = SynonymMapper\n .readFromFile(synonymXMLfile.getAbsolutePath());\n\n for (Synonym synonym : synonymsFromFile) {\n synonymCache.put(synonym);\n }\n\n return synonymCache;\n }\n\n /**\n * Writes all known {@link Synonym}s in the cache out to the specified file\n * in XML format.\n *\n * @param synonymXMLfile an empty writeable xml file to write the synonyms\n * to.\n * @throws XMLException When there is a problem writing the synonyms to file.\n * @throws IOException When there is a problem writing the synonyms to file.\n * @throws MappingException When there is a problem writing the synonyms to file.\n */\n public void toFile(File synonymXMLfile) throws XMLException, IOException, MappingException {\n List<Synonym> allSynonyms = new ArrayList<>();\n\n // Flatten the type -> From -> Synonym map.\n Collection<Map<Object, Synonym>> allObjectMaps = synonymCache.values();\n for (Map<Object, Synonym> typeMap : allObjectMaps) {\n allSynonyms.addAll(typeMap.values());\n }\n\n SynonymMapper\n .writeToFile(allSynonyms, synonymXMLfile.getAbsolutePath());\n }\n\n /**\n * Stores the given {@link Synonym} in the synonym cache, except when the\n * given synonym is short-lived. Short-lived synonyms are not stored or\n * re-used.\n *\n * @param synonym to store\n */\n public void put(Synonym synonym) {\n if (synonym.isShortLived()) {\n return;\n }\n\n Map<Object, Synonym> map = synonymCache.computeIfAbsent(synonym.getType(), k -> new HashMap<>());\n\n if (hasher != null) {\n // Hash sensitive data before storing\n Synonym hashed = new HashedFromSynonym(hasher, synonym);\n if (map.put(hashed.getFrom(), hashed) == null) {\n size++;\n }\n } else {\n // Store as-is\n if (map.put(synonym.getFrom(), synonym) == null) {\n size++;\n }\n }\n }\n\n public Synonym get(String type, Object from) {\n Map<Object, Synonym> typemap = synonymCache.get(type);\n if (typemap == null) {\n return null;\n }\n\n if (hasher != null) {\n return typemap.get(hasher.base64Hash(from));\n } else {\n return typemap.get(from);\n }\n }\n\n public void setHasher(Hasher hasher) {\n this.hasher = hasher;\n }\n\n public long size() {\n return size;\n }\n}", "public class CommandLine {\n\n private static final String OPT_JDBCURL = \"jdbcurl\";\n private static final String OPT_USERID = \"userid\";\n private static final String OPT_PASSWORD = \"password\";\n private static final String OPT_CONFIGFILE = \"config\";\n private static final String OPT_SYNONYMFILE = \"synonyms\";\n private static final String OPT_DRYRUN = \"dryrun\";\n private static final String OPT_CONFIGEXAMPLE = \"configexample\";\n\n private static final Options options = new Options()\n .addOption(OPT_CONFIGFILE, true,\n \"The XML Configuration file describing what to anonymize.\")\n .addOption(OPT_SYNONYMFILE, true,\n \"The XML file to read/write synonyms to. \"\n + \"If the file does not exist it will be created.\")\n .addOption(OPT_CONFIGEXAMPLE, false,\n \"Prints out a demo/template configuration file.\")\n .addOption(OPT_DRYRUN, false, \"Do not make changes to the database.\")\n .addOption(OPT_JDBCURL, true,\n \"The JDBC URL to connect to. \" +\n \"If provided, overrides the value in the config file.\")\n .addOption(OPT_USERID, true,\n \"The user id for the database connection. \" +\n \"If provided, overrides the value in the config file.\")\n .addOption(OPT_PASSWORD, true,\n \"The password for the database connection. \" +\n \"If provided, overrides the value in the config file.\");\n\n private final org.apache.commons.cli.CommandLine clicommandLine;\n\n public CommandLine(String[] arguments) throws ParseException {\n CommandLineParser parser = new DefaultParser();\n clicommandLine = parser.parse(options, arguments);\n }\n\n public static void printHelp() {\n System.out\n .println(\"\\nThis is Anonimatron \" + VERSION + \", a command line tool to consistently \\n\"\n + \"replace live data in your database or data files with data data which \\n\"\n + \"can not easily be traced back to the original data.\\n\"\n + \"You can use this tool to transform a dump from a production \\n\"\n + \"database into a large representative dataset you can \\n\"\n + \"share with your development and test team.\\n\"\n + \"The tool can also read files with sensitive data and write\\n\"\n + \"consistently anonymized versions of those files to a different location.\\n\"\n + \"Use the -configexample command line option to get an idea of\\n\"\n + \"what your configuration file needs to look like.\\n\\n\");\n\n HelpFormatter helpFormatter = new HelpFormatter();\n helpFormatter.printHelp(\"java -jar anonimatron.jar\", options);\n }\n\n public String getJdbcurl() {\n return clicommandLine.getOptionValue(CommandLine.OPT_JDBCURL);\n }\n\n public String getUserid() {\n return clicommandLine.getOptionValue(CommandLine.OPT_USERID);\n }\n\n public String getPassword() {\n return clicommandLine.getOptionValue(CommandLine.OPT_PASSWORD);\n }\n\n public String getConfigfileName() {\n return clicommandLine.getOptionValue(CommandLine.OPT_CONFIGFILE);\n }\n\n public String getSynonymfileName() {\n return clicommandLine.getOptionValue(CommandLine.OPT_SYNONYMFILE);\n }\n\n public boolean isDryrun() {\n return clicommandLine.hasOption(CommandLine.OPT_DRYRUN);\n }\n\n public boolean isConfigExample() {\n return clicommandLine.hasOption(CommandLine.OPT_CONFIGEXAMPLE);\n }\n}", "public class Configuration {\n\tprivate static final Logger LOG = Logger.getLogger(Configuration.class);\n\n\tprivate String jdbcurl;\n\tprivate String userid;\n\tprivate String password;\n\n\tprivate String salt;\n\n\tprivate List<Table> tables;\n\tprivate List<DataFile> files;\n\tprivate List<String> anonymizerClasses;\n\tprivate List<String> fileFilters;\n\tprivate boolean dryrun = false;\n\tpublic boolean isDryrun() {\n\t\treturn dryrun;\n\t}\n\n\tpublic void setDryrun(boolean dryrun) {\n\t\tthis.dryrun = dryrun;\n\t}\n\n\tpublic static Configuration readFromFile(String filename) throws Exception {\n\t\tMapping mapping = getMapping();\n\t\tUnmarshaller unmarshaller = new Unmarshaller(mapping);\n\n\t\tFile file = new File(filename);\n\t\tReader reader = new FileReader(file);\n\t\tConfiguration configuration = (Configuration)unmarshaller.unmarshal(reader);\n\t\tLOG.info(\"Configuration read from \" + file.getAbsoluteFile());\n\n\t\tconfiguration.sanityCheck();\n\t\treturn configuration;\n\t}\n\n\tprivate void sanityCheck(){\n\t\tif (getFiles() != null) {\n\t\t\tfor (DataFile dataFile : getFiles()) {\n\t\t\t\tif (dataFile.getColumns() == null || dataFile.getColumns().isEmpty()) {\n\t\t\t\t\tLOG.info(\n\t\t\t\t\t\t\tString.format(\"No column definitions for input %s, lines will be passed through.\",\n\t\t\t\t\t\t\t\t\tdataFile.getInFile()));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static Mapping getMapping() throws IOException, MappingException {\n\t\tURL url = Configuration.class.getResource(\"castor-config-mapping.xml\");\n\t\tMapping mapping = new Mapping();\n\t\tmapping.loadMapping(url);\n\t\treturn mapping;\n\t}\n\n\tpublic static String getDemoConfiguration() throws Exception {\n\t\tMapping mapping = getMapping();\n\n\t\tStringWriter stringWriter = new StringWriter();\n\t\tMarshaller marshaller = new Marshaller(stringWriter);\n\t\t// I have no idea why this does not work, so I added a castor.properties\n\t\t// file in the root as workaround.\n\t\t// marshaller.setProperty(\"org.exolab.castor.indent\", \"true\");\n\t\tmarshaller.setMapping(mapping);\n\t\tmarshaller.marshal(createConfiguration());\n\t\treturn stringWriter.toString();\n\t}\n\n\tpublic void setAnonymizerClasses(List<String> anonymizerClasses) {\n\t\tthis.anonymizerClasses = anonymizerClasses;\n\t}\n\n\tpublic List<String> getAnonymizerClasses() {\n\t\treturn anonymizerClasses;\n\t}\n\n\tpublic String getJdbcurl() {\n\t\treturn jdbcurl;\n\t}\n\n\tpublic void setJdbcurl(String jdbcurl) {\n\t\tthis.jdbcurl = jdbcurl;\n\t}\n\n\tpublic String getUserid() {\n\t\treturn userid;\n\t}\n\n\tpublic void setUserid(String userid) {\n\t\tthis.userid = userid;\n\t}\n\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\n\tpublic void setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\n\tpublic List<Table> getTables() {\n\t\treturn tables;\n\t}\n\n\tpublic void setTables(List<Table> tables) {\n\t\tthis.tables = tables;\n\t}\n\n\tpublic void setFiles(List<DataFile> files) {\n\t\tthis.files = files;\n\t}\n\n\tpublic List<DataFile> getFiles() {\n\t\treturn files;\n\t}\n\n\tpublic List<String> getFileFilters() {\n\t\treturn fileFilters;\n\t}\n\n\tpublic void setFileFilters(List<String> fileFilters) {\n\t\tthis.fileFilters = fileFilters;\n\t}\n\n\tpublic String getSalt() {\n\t\treturn salt;\n\t}\n\n\tpublic void setSalt(String salt) {\n\t\tthis.salt = salt;\n\t}\n\n\tprivate static Configuration createConfiguration() throws Exception {\n\t\tConfiguration conf = new Configuration();\n\n\t\tconf.setSalt(\"examplesalt\");\n\n\t\tList<String> anonymizers = new ArrayList<>();\n\t\tanonymizers.add(\"my.demo.java.SmurfAnonymizer\");\n\t\tanonymizers.add(\"org.sf.anonimatron.CommunityAnonymizer\");\n\t\tconf.setAnonymizerClasses(anonymizers);\n\n\t\tList<Table> tables = new ArrayList<>();\n\t\ttables.add(getTable(\"CUSTOM_TYPES_TABLE\", getColumns()));\n\t\ttables.add(getTable(\"DEFAULT_TYPES_TABLE\", getDefaultColumns()));\n\t\ttables.add(getDiscriminatorExample());\n\n\t\tconf.setTables(tables);\n\n\t\tList<DataFile> dataFiles = new ArrayList<>();\n\t\tdataFiles.add(getDataFile(\"mydatafile.in.csv\", \"mydatafile.out.csv\", getFileColumns()));\n\t\tdataFiles.add(getDataFile(\"default_types.in.csv\", \"default_types.out.csv\", getDefaultColumns()));\n\t\tdataFiles.add(getDataFile(\"nocolumns.in.csv\",\"nocolumns.out.csv\", null));\n\n\t\tconf.setFiles(dataFiles);\n\n\t\tconf.setUserid(\"userid\");\n\t\tconf.setPassword(\"password\");\n\t\tconf.setJdbcurl(\"jdbc:oracle:thin:@[HOST]:[PORT]:[SID]\");\n\t\treturn conf;\n\t}\n\n\tprivate static DataFile getDataFile(String inFile, String outFile, List<Column> columns) {\n\t\tDataFile t = new DataFile();\n\t\tt.setInFile(inFile);\n\t\tt.setReader(CsvFileReader.class.getCanonicalName());\n\n\t\tt.setOutFile(outFile);\n\t\tt.setWriter(CsvFileWriter.class.getCanonicalName());\n\n\t\tt.setColumns(columns);\n\t\treturn t;\n\t}\n\n\tprivate static Table getDiscriminatorExample() {\n\t\t// Build example table with a discriminator\n\t\tTable discriminatortable = new Table();\n\t\tdiscriminatortable.setName(\"DISCRIMINATOR_DEMO_TABLE\");\n\n\t\t// The default column contains a \"phone number\" of some sort\n\t\tList<Column> defaultcolumns = new ArrayList<>();\n\t\tColumn defaultColumn = new Column();\n\t\tdefaultColumn.setName(\"CONTACTINFO\");\n\t\tdefaultColumn.setType(\"RANDOMDIGITS\");\n\t\tdefaultcolumns.add(defaultColumn);\n\t\tdiscriminatortable.setColumns(defaultcolumns);\n\n\t\t// The specific column contains an \"email address\"\n\t\tList<Column> discriminatecolumns = new ArrayList<>();\n\t\tColumn discriminateColumn = new Column();\n\t\tdiscriminateColumn.setName(\"CONTACTINFO\");\n\t\tdiscriminateColumn.setType(\"EMAIL_ADDRESS\");\n\t\tdiscriminatecolumns.add(discriminateColumn);\n\n\t\t// This is the discriminator which overrides the phone number with an\n\t\t// email address\n\t\tDiscriminator discriminator = new Discriminator();\n\t\tdiscriminator.setColumnName(\"CONTACTTYPE\");\n\t\tdiscriminator.setValue(\"email address\");\n\t\tdiscriminator.setColumns(discriminatecolumns);\n\n\t\tList<Discriminator> discriminators = new ArrayList<>();\n\t\tdiscriminators.add(discriminator);\n\n\t\tdiscriminatortable.setDiscriminators(discriminators);\n\t\treturn discriminatortable;\n\t}\n\n\tprivate static Table getTable(String tablename, List<Column> columns) {\n\t\tTable t = new Table();\n\t\tt.setName(tablename);\n\t\tt.setColumns(columns);\n\t\treturn t;\n\t}\n\n\n\tprivate static List<Column> getFileColumns() throws Exception {\n\t\tList<Column> columns = new ArrayList<>();\n\n\t\tAnonymizerService as = new AnonymizerService();\n\t\tString[] types = as.getCustomAnonymizerTypes().toArray(new String[]{});\n\n\t\t// For csv files, indexed column names are the more common example\n\t\tfor (int i = 0; i < types.length; i++) {\n\t\t\tColumn c = new Column();\n\t\t\tc.setName(String.valueOf(i+1));\n\t\t\tc.setType(types[i]);\n\t\t\tcolumns.add(c);\n\t\t}\n\n\t\treturn columns;\n\t}\n\n\tprivate static List<Column> getColumns() throws Exception {\n\t\tList<Column> columns = new ArrayList<>();\n\n\t\tAnonymizerService as = new AnonymizerService();\n\t\tSet<String> types = as.getCustomAnonymizerTypes();\n\n\t\tfor (String type : types) {\n\t\t\tColumn c = new Column();\n\t\t\tc.setName(\"A_\" + type.toUpperCase() + \"_COLUMN\");\n\t\t\tc.setType(type);\n\t\t\tcolumns.add(c);\n\t\t}\n\n\t\t// Add a demo configuration for a shortlived (non-stored) column.\n\t\t{\n\t\t\tColumn c = new Column();\n\t\t\tc.setName(\"A_SHORTLIVED_COLUMN\");\n\t\t\tc.setType(new StringAnonymizer().getType());\n\t\t\tc.setShortlived(true);\n\t\t\tcolumns.add(c);\n\t\t}\n\n\t\t// Add a demo configuration for a column with configuration parameters\n\t\t{\n\t\t\tColumn c = new Column();\n\t\t\tc.setName(\"A_PARAMETERIZED_COLUMN\");\n\t\t\tc.setType(new CharacterStringAnonymizer().getType());\n\n\t\t\tHashMap<String, String> parameters = new HashMap<>();\n\t\t\tparameters.put(CharacterStringAnonymizer.PARAMETER, \"ABC123!*&\");\n\t\t\tc.setParameters(parameters);\n\n\t\t\tcolumns.add(c);\n\t\t}\n\n\n\t\treturn columns;\n\t}\n\n\tprivate static List<Column> getDefaultColumns() throws Exception {\n\t\tList<Column> columns = new ArrayList<>();\n\n\t\tAnonymizerService as = new AnonymizerService();\n\t\tSet<String> types = as.getDefaultAnonymizerTypes();\n\n\t\tfor (String type : types) {\n\t\t\tColumn c = new Column();\n\t\t\tc.setName(\"A_\" + type.toUpperCase().replace('.', '_') + \"_COLUMN\");\n\t\t\tc.setType(type);\n\t\t\tcolumns.add(c);\n\t\t}\n\t\treturn columns;\n\t}\n}", "public class FileAnonymizerService {\n private final Logger LOG = Logger.getLogger(FileAnonymizerService.class);\n\n private Configuration config;\n private AnonymizerService anonymizerService;\n private Progress progress;\n\n\n public FileAnonymizerService(Configuration config, AnonymizerService anonymizerService) {\n this.config = config;\n this.anonymizerService = anonymizerService;\n }\n\n\n public void printConfigurationInfo() {\n System.out.println(\"\\nAnonymization process started\\n\");\n System.out.println(\"To do : \" + config.getFiles().size() + \" files.\\n\");\n }\n\n\n public void anonymize() throws Exception {\n List<DataFile> files = expandDirectories(config.getFiles());\n System.out.println(\"Files to process: \" + files.size());\n\n List<FileFilter> fileFilters = getFileFilters();\n\n long totalBytes = 0;\n for (DataFile file : files) {\n totalBytes += new File(file.getInFile()).length();\n }\n\n progress = new Progress();\n progress.setTotalitemstodo(totalBytes);\n\n ProgressPrinter printer = new ProgressPrinter(progress);\n printer.setPrintIntervalMillis(1000);\n\n// \t\tEnable this when printing is better tested.\n//\t\tprinter.start();\n\n for (DataFile file : files) {\n File infile = new File(file.getInFile());\n\n boolean process = true;\n for (FileFilter fileFilter : fileFilters) {\n if (!fileFilter.accept(infile)) {\n // Skip file\n process = false;\n progress.incItemsCompleted(infile.length());\n // TODO possible bug: Which loop do we want to break out of?\n continue;\n }\n }\n\n if (!process || new File(file.getOutFile()).exists()) {\n System.out.println(\"Skipping \" + file.getInFile());\n progress.incItemsCompleted(infile.length());\n continue;\n }\n\n System.out.println(\"Anonymizing from \" + file.getInFile());\n System.out.println(\" to \" + file.getOutFile());\n\n RecordReader reader = createReader(file);\n RecordWriter writer = createWriter(file);\n\n Map<String, Column> columns = toMap(file.getColumns());\n\n anonymize(\n reader,\n writer,\n columns\n );\n\n reader.close();\n writer.close();\n progress.incItemsCompleted(infile.length());\n }\n printer.stop();\n\n System.out.println(\"\\nAnonymization process completed.\\n\");\n }\n\n private List<FileFilter> getFileFilters() throws Exception {\n List<FileFilter> fileFilters = new ArrayList<>();\n List<String> fileFilterStrings = config.getFileFilters();\n if (fileFilterStrings != null) {\n for (String fileFilterString : fileFilterStrings) {\n fileFilters.add(createFileFilter(fileFilterString));\n }\n }\n return fileFilters;\n }\n\n private List<DataFile> expandDirectories(List<DataFile> files) {\n ArrayList<DataFile> allFiles = new ArrayList<>();\n\n if (files == null || files.isEmpty()) {\n return allFiles;\n }\n\n for (DataFile dataFile : files) {\n\n // Get all input files\n List<File> inFiles = getInputFiles(dataFile);\n\n // Check that we don't overwrite output files\n for (File inFile : inFiles) {\n\n File outFile = new File(dataFile.getOutFile());\n if (outFile.exists() && outFile.isDirectory()) {\n outFile = new File(outFile, inFile.getName());\n }\n\n if (outFile.exists()) {\n throw new RuntimeException(\"Output file exists: \" + outFile.getAbsolutePath());\n }\n\n DataFile newDataFile = new DataFile();\n newDataFile.setColumns(dataFile.getColumns());\n newDataFile.setReader(dataFile.getReader());\n newDataFile.setWriter(dataFile.getWriter());\n newDataFile.setInFile(inFile.getAbsolutePath());\n newDataFile.setOutFile(outFile.getAbsolutePath());\n newDataFile.setDiscriminators(dataFile.getDiscriminators());\n allFiles.add(newDataFile);\n }\n }\n\n preventDataFileCollisions(allFiles);\n return allFiles;\n }\n\n void preventDataFileCollisions(List<DataFile> allFiles) {\n HashSet<String> inFiles = new HashSet<>();\n for (DataFile dataFile : allFiles) {\n inFiles.add(dataFile.getInFile());\n }\n\n HashSet<String> outFiles = new HashSet<>();\n for (DataFile dataFile : allFiles) {\n if (dataFile.getOutFile().equals(dataFile.getInFile())) {\n throw new RuntimeException(\"File used as both input and output: \" + dataFile.getInFile() + \".\");\n }\n\n if (outFiles.contains(dataFile.getOutFile())) {\n throw new RuntimeException(\"Configuration will write twice to the same file \" + dataFile.getOutFile() + \".\");\n }\n\n if (inFiles.contains(dataFile.getOutFile())) {\n throw new RuntimeException(\"Configuration will overwrite input file \" + dataFile.getOutFile() + \".\");\n }\n\n outFiles.add(dataFile.getOutFile());\n }\n }\n\n List<File> getInputFiles(DataFile dataFile) {\n List<File> inFiles = new ArrayList<>();\n File inFile = new File(dataFile.getInFile());\n\n if (inFile.exists() && inFile.isDirectory()) {\n File[] inputFiles = inFile.listFiles();\n\n for (File inputFile : inputFiles) {\n if (inputFile.isFile()) {\n inFiles.add(inputFile);\n }\n }\n\n } else if (inFile.exists() && inFile.isFile()) {\n inFiles.add(inFile);\n } else {\n throw new RuntimeException(\"Input file does not exist: \" + inFile.getAbsolutePath());\n }\n return inFiles;\n }\n\n void anonymize(RecordReader reader, RecordWriter writer, Map<String, Column> columns) throws Exception {\n while (reader.hasRecords()) {\n Record read = reader.read();\n\n if (read != null) {\n Record anonymized = anonymize(read, columns);\n writer.write(anonymized);\n }\n }\n }\n\n Record anonymize(Record record, Map<String, Column> columns) {\n Object[] values = new Object[record.getValues().length];\n for (int i = 0; i < record.getNames().length; i++) {\n String name = record.getNames()[i];\n Object value = record.getValues()[i];\n\n if (columns.containsKey(name)) {\n Column column = columns.get(name);\n Synonym synonym = anonymizerService.anonymize(column, value);\n values[i] = synonym.getTo();\n } else {\n values[i] = value;\n }\n }\n\n Record outputRecord = new Record(record.getNames(), values);\n\n if (LOG.isTraceEnabled()) {\n LOG.trace(record);\n LOG.trace(outputRecord);\n }\n return outputRecord;\n }\n\n private Map<String, Column> toMap(List<Column> columns) {\n HashMap<String, Column> map = new HashMap<>();\n\n if (columns == null || columns.isEmpty()) {\n return map;\n }\n\n for (Column column : columns) {\n map.put(column.getName(), column);\n }\n return map;\n }\n\n private RecordReader createReader(DataFile file) throws Exception {\n try {\n Class clazz = Class.forName(file.getReader());\n Constructor constructor = clazz.getConstructor(String.class);\n return (RecordReader) constructor.newInstance(file.getInFile());\n } catch (Exception e) {\n throw new RuntimeException(\"Problem creating reader \" + file.getReader() + \" for input file \" + file.getInFile() + \".\", e);\n }\n }\n\n private RecordWriter createWriter(DataFile file) throws Exception {\n try {\n Class clazz = Class.forName(file.getWriter());\n Constructor constructor = clazz.getConstructor(String.class);\n return (RecordWriter) constructor.newInstance(file.getOutFile());\n } catch (Exception e) {\n throw new RuntimeException(\"Problem creating writer \" + file.getWriter() + \" for output file \" + file.getOutFile() + \".\", e);\n }\n }\n\n private FileFilter createFileFilter(String fileFilterClass) throws Exception {\n try {\n Class clazz = Class.forName(fileFilterClass);\n Constructor constructor = clazz.getConstructor();\n return (FileFilter) constructor.newInstance();\n } catch (Exception e) {\n throw new RuntimeException(\"Problem creating file filter \" + fileFilterClass + \".\", e);\n }\n }\n\n}", "public class JdbcAnonymizerService {\n Logger LOG = Logger.getLogger(JdbcAnonymizerService.class);\n\n private Configuration config;\n private Connection connection;\n private AnonymizerService anonymizerService;\n private Progress progress;\n\n private Map<String, String> supportedJdbcUrls = new HashMap<>();\n\n public JdbcAnonymizerService() {\n registerDrivers();\n }\n\n public JdbcAnonymizerService(Configuration config, AnonymizerService anonymizerService) throws Exception {\n this();\n this.config = config;\n this.anonymizerService = anonymizerService;\n setConnection();\n }\n\n public void printConfigurationInfo() {\n System.out.println(\"\\nAnonymization process started\\n\");\n System.out.println(\"Jdbc url : \" + config.getJdbcurl());\n System.out.println(\"Database user : \" + config.getUserid());\n System.out.println(\"To do : \" + config.getTables().size()\n + \" tables.\\n\");\n }\n\n public void anonymize() throws SQLException {\n printConfigurationInfo();\n\n // Get records to do\n List<Table> tables = config.getTables();\n int totalRows = 0;\n for (Table table : tables) {\n // Get the total number of records to process\n long numberofRows = getRowCount(table);\n table.setNumberOfRows(numberofRows);\n totalRows += numberofRows;\n LOG.info(\"Table \" + table.getName() + \" has \" + numberofRows + \" rows to process.\");\n }\n\n progress = new Progress();\n progress.setTotalitemstodo(totalRows);\n\n ProgressPrinter printer = new ProgressPrinter(progress);\n printer.setPrintIntervalMillis(1000);\n printer.start();\n\n try {\n for (Table table : tables) {\n printer.setMessage(\"Pre-scanning table '\" + table.getName()\n + \"', total progress \");\n preScanTable(table);\n }\n\n progress.reset();\n\n for (Table table : tables) {\n printer.setMessage(\"Anonymizing table '\" + table.getName()\n + \"', total progress \");\n anonymizeTableInPlace(table);\n }\n } finally {\n printer.stop();\n }\n\n System.out.println(\"\\nAnonymization process completed.\\n\");\n }\n\n private void setConnection() throws SQLException {\n String jdbcurl = config.getJdbcurl();\n String userid = config.getUserid();\n String password = config.getPassword();\n\n connection = DriverManager.getConnection(jdbcurl, userid, password);\n connection.setAutoCommit(false);\n\n LOG.info(\"Conected to '\" + jdbcurl + \"' with user '\" + userid + \"'.\");\n }\n\n /**\n * Runs through the table data, feeds it to the Synonyms which implement\n * {@link Prefetcher}, so that they can analyze the source data to base\n * their synonym algorithm on.\n */\n private void preScanTable(Table table) {\n ColumnWorker worker = (results, column, databaseColumnValue) -> anonymizerService.prepare(column.getType(),\n databaseColumnValue);\n\n processTableColumns(table, worker, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);\n }\n\n private void anonymizeTableInPlace(Table table) {\n ColumnWorker worker = (results, column, databaseColumnValue) -> {\n Synonym synonym = anonymizerService.anonymize(column,\n databaseColumnValue);\n\n if (results.getConcurrency() == ResultSet.CONCUR_UPDATABLE) {\n // Update the contents of this row with the given Synonym\n results.updateObject(column.getName(), synonym.getTo());\n }\n\n return true;\n };\n\n int resultsetConcurrency = getAnonimizerResultSetConcurrency();\n\n processTableColumns(table, worker, ResultSet.TYPE_FORWARD_ONLY, resultsetConcurrency);\n }\n\n private int getAnonimizerResultSetConcurrency() {\n if (config.isDryrun()) {\n return ResultSet.CONCUR_READ_ONLY;\n } else {\n return ResultSet.CONCUR_UPDATABLE;\n }\n }\n\n private void processTableColumns(Table table, final ColumnWorker columnWorker, int resultSetType, int resultSetConcurrency) {\n // Create an updatable resultset for the rows.\n Statement statement = null;\n ResultSet results = null;\n long rowsleft = table.getNumberOfRows();\n try {\n NDC.push(\"Table '\" + table.getName() + \"'\");\n String select = getSelectStatement(table);\n LOG.debug(select);\n\n statement = connection.createStatement(resultSetType, resultSetConcurrency);\n if (table.getFetchSize() != null) {\n statement.setFetchSize(table.getFetchSize());\n }\n statement.execute(select);\n results = statement.getResultSet();\n ResultSetMetaData resultsMetaData = results.getMetaData();\n\n if (results.getConcurrency() != resultSetConcurrency) {\n LOG.warn(\"The resultset concurrency was \" + results.getConcurrency() + \" while we tried to set it to \" + resultSetConcurrency);\n }\n\n boolean processNextRecord = true;\n while (results.next() && processNextRecord) {\n Collection<Column> columnsAsList = getDiscriminatedColumnConfiguration(table, results);\n\n /*\n * If any of the calls to the worker indicate that\n * we need to continue, we'll fetch the next result (see below).\n * If we had no columns to do because we had no columns and no discriminators firing,\n * we assume that we do need to process the next record.\n * TODO This is now a strange way to stop the loop on synonym depletion and needs refactoring.\n */\n processNextRecord = false || columnsAsList.isEmpty();\n\n for (Column column : columnsAsList) {\n // Build a synonym for each column in this row\n NDC.push(\"Column '\" + column.getName() + \"'\");\n\n String columnType = column.getType();\n if (columnType == null) {\n columnType = resultsMetaData.getColumnClassName(results.findColumn(column.getName()));\n column.setType(columnType);\n }\n\n NDC.push(\"Type '\" + columnType + \"'\");\n\n int columnDisplaySize = resultsMetaData.getColumnDisplaySize(results.findColumn(column.getName()));\n column.setSize(columnDisplaySize);\n\n Object databaseColumnValue = results.getObject(column.getName());\n\n /* If any call returns true, process the next record. */\n processNextRecord = columnWorker.processColumn(results, column, databaseColumnValue)\n || processNextRecord;\n\n NDC.pop(); // type\n NDC.pop(); // column\n }\n\n // Do not update for read-only resultsets or if the list of columns to update is empty\n // If the list is empty, some JDBC implementations (namely Informix) will throw a syntax error.\n if (results.getConcurrency() == ResultSet.CONCUR_UPDATABLE && !columnsAsList.isEmpty()) {\n results.updateRow();\n }\n\n rowsleft--;\n progress.incItemsCompleted(1);\n }\n\n /*\n * Makes sure that we update the progress monitor even if we have\n * broken out of the loop, effectively skipping the rest of the rows\n */\n progress.incItemsCompleted(rowsleft);\n\n if (!processNextRecord) {\n LOG.debug(\"The Anonimizer service has indicated that it can skip the rest of table \"\n + table.getName() + \" in this pass.\");\n }\n\n } catch (Exception e) {\n LOG.fatal(\"Anonymyzation stopped because of fatal error.\", e);\n throw new RuntimeException(e);\n } finally {\n NDC.remove();\n commitAndClose(connection, statement, results);\n }\n }\n\n private void commitAndClose(Connection conn, Statement statement, ResultSet results) {\n try {\n /*\n * TODO: Figure out why we need to do a commit even if the resultset\n * is *not* updatable.\n */\n // if (!conn.getAutoCommit() && results.getConcurrency() ==\n // ResultSet.CONCUR_UPDATABLE) {\n\n if (!conn.getAutoCommit()) {\n conn.commit();\n }\n } catch (SQLException e) {\n LOG.error(\"Could not commit\", e);\n }\n\n try {\n if (results != null) results.close();\n } catch (SQLException e) {\n LOG.error(\"Could not close resultset.\", e);\n }\n\n try {\n if (statement != null) statement.close();\n } catch (SQLException e) {\n LOG.error(\"Could not close statement.\", e);\n }\n }\n\n private Collection<Column> getDiscriminatedColumnConfiguration(Table table, ResultSet results) throws SQLException {\n List<Discriminator> discriminators = table.getDiscriminators();\n if (discriminators == null) {\n // No discriminators, carry on with default columns\n return table.getColumns();\n }\n\n // Get default columns as a map\n Map<String, Column> columnsAsMap = Table.getColumnsAsMap(table.getColumns());\n\n // Overwrite/add columns in the map based on discriminators\n for (Discriminator discriminator : discriminators) {\n\n String columnName = discriminator.getColumnName();\n if (columnName == null) {\n throw new IllegalArgumentException(\"A discriminator in the configuration for table \" + table.getName() + \" did not concain a column name.\");\n }\n Object value = results.getObject(columnName);\n\n if ((discriminator.getValue() != null && discriminator.getValue().equals(value))\n || (discriminator.getValue() == null) && (value == null)) {\n // Overload standard column definition\n Map<String, Column> discrColumns = Table.getColumnsAsMap(discriminator.getColumns());\n columnsAsMap.putAll(discrColumns);\n }\n }\n\n return columnsAsMap.values();\n }\n\n private long getRowCount(Table table) throws SQLException {\n String select = \"select count(1) from \" + table.getName();\n Statement statement = null;\n ResultSet results = null;\n\n try {\n statement = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);\n statement.execute(select);\n results = statement.getResultSet();\n\n if (results.getConcurrency() != ResultSet.CONCUR_READ_ONLY) {\n LOG.warn(\"Could not set this resultset to be read-only.\");\n }\n\n results.next();\n /*\n * Please note that \"getLong\" does not work correctly for large\n * numbers in MySQL. That's why we're using a BigDecimal and get the\n * long value from that.\n */\n return results.getBigDecimal(1).longValue();\n } finally {\n commitAndClose(connection, statement, results);\n }\n }\n\n private String getSelectStatement(Table table) throws SQLException {\n Set<String> columnNames = new HashSet<>();\n if (table.getColumns() != null) {\n for (Column column : table.getColumns()) {\n columnNames.add(column.getName());\n }\n }\n\n if (table.getDiscriminators() != null) {\n // Add all columns involved in discriminator selection and its column definitions\n for (Discriminator discriminator : table.getDiscriminators()) {\n columnNames.add(discriminator.getColumnName());\n columnNames.addAll(\n discriminator.getColumns()\n .stream()\n .map(Column::getName)\n .collect(Collectors.toList())\n );\n }\n }\n\n String primaryKeys = getPrimaryKeys(table, columnNames);\n\n String select = \"select \" + primaryKeys;\n\n for (String columnName : columnNames) {\n select += columnName + \", \";\n }\n\n select = select.substring(0, select.lastIndexOf(\", \"));\n select += \" from \" + table.getName();\n return select;\n }\n\n /**\n * @param table The table to fetch the primary keys for.\n * @param columnNames The column names in the configuration that need to be anonimyzed or are\n * used as a discriminator column\n * @return A comma separated list of primary keys which are not part of any discriminator\n * or anonimyzation column.\n * @throws SQLException\n * @throws RuntimeException When there is a problem with the configuration or precondition.\n */\n private String getPrimaryKeys(Table table, Set<String> columnNames) throws SQLException {\n\n String schema = null;\n String tablename = table.getName();\n String[] split = table.getName().split(\"\\\\.\");\n if (split.length == 2) {\n schema = split[0];\n tablename = split[1];\n }\n\n try (ResultSet resultset = connection.getMetaData().getPrimaryKeys(connection.getCatalog(), schema, tablename)) {\n String primaryKeys = \"\";\n while (resultset.next()) {\n String columnName = resultset.getString(\"COLUMN_NAME\");\n if (columnNames.contains(columnName)) {\n String msg = \"Column \" + columnName + \" in table \" + table.getName()\n + \" can not be anonimyzed because it is also a primary key.\";\n LOG.error(msg);\n throw new RuntimeException(msg);\n } else {\n primaryKeys += columnName + \", \";\n }\n }\n\n if (primaryKeys.length() < 1) {\n String msg = \"Table \" + table.getName() + \" does not contain a primary key and can not be anonymyzed.\";\n LOG.error(msg);\n throw new RuntimeException(msg);\n }\n\n return primaryKeys;\n }\n }\n\n /**\n * Registers all database drivers which can be found on the classpath\n */\n private void registerDrivers() {\n // Array of arrays. Each array is a jdb-url and classname combo.\n String[][] drivers = {\n {\"jdbc:oracle:thin:@[HOST]:[PORT]:[SID]\", \"oracle.jdbc.driver.OracleDriver\"},\n {\"jdbc:db2://[HOST]:[PORT]/[DB]\", \"COM.ibm.db2.jdbc.app.DB2Driver\"},\n {\"jdbc:weblogic:mssqlserver4:[DB]@[HOST]:[PORT]\", \"weblogic.jdbc.mssqlserver4.Driver\"},\n {\"jdbc:pointbase://embedded[:[PORT]]/[DB]\", \"com.pointbase.jdbc.jdbcUniversalDriver\"},\n {\"jdbc:cloudscape:[DB]\", \"COM.cloudscape.core.JDBCDriver\"},\n {\"jdbc:rmi://[HOST]:[PORT]/jdbc:cloudscape:[DB]\", \"RmiJdbc.RJDriver\"},\n {\"jdbc:firebirdsql:[//[HOST][:[PORT]]/][DB]\", \"org.firebirdsql.jdbc.FBDriver\"},\n {\"jdbc:ids://[HOST]:[PORT]/conn?dsn='[ODBC_DSN_NAME]'\", \"ids.sql.IDSDriver\"},\n {\"jdbc:informix-sqli://[HOST]:[PORT]/[DB]:INFORMIXSERVER=[SERVER_NAME]\", \"com.informix.jdbc.IfxDriver\"},\n {\"jdbc:idb:[DB]\", \"jdbc.idbDriver\"},\n {\"jdbc:idb:[DB]\", \"org.enhydra.instantdb.jdbc.idbDriver\"},\n {\"jdbc:interbase://[HOST]/[DB]\", \"interbase.interclient.Driver\"},\n {\"jdbc:HypersonicSQL:[DB]\", \"hSql.hDriver\"},\n {\"jdbc:HypersonicSQL:[DB]\", \"org.hsqldb.jdbcDriver\"},\n {\"jdbc:JTurbo://[HOST]:[PORT]/[DB]\", \"com.ashna.jturbo.driver.Driver\"},\n {\"jdbc:inetdae:[HOST]:[PORT]?database=[DB]\", \"com.inet.tds.TdsDriver\"},\n {\"jdbc:microsoft:sqlserver://[HOST]:[PORT][;DatabaseName=[DB]]\", \"com.microsoft.sqlserver.jdbc.SQLServerDriver\"},\n {\"jdbc:sqlserver://[HOST]:[PORT][;DatabaseName=[DB]]\", \"com.microsoft.sqlserver.jdbc.SQLServerDriver\"},\n {\"jdbc:mysql://[HOST]:[PORT]/[DB]\", \"org.gjt.mm.mysql.Driver\"},\n {\"jdbc:oracle:oci8:@[SID]\", \"oracle.jdbc.driver.OracleDriver\"},\n {\"jdbc:oracle:oci:@[SID]\", \"oracle.jdbc.driver.OracleDriver\"},\n {\"jdbc:postgresql://[HOST]:[PORT]/[DB]\", \"postgresql.Driver\"},\n {\"jdbc:postgresql://[HOST]:[PORT]/[DB]\", \"org.postgresql.Driver\"},\n {\"jdbc:sybase:Tds:[HOST]:[PORT]\", \"com.sybase.jdbc.SybDriver\"},\n {\"jdbc:sybase:Tds:[HOST]:[PORT]/[DB]\", \"net.sourceforge.jtds.jdbc.Driver\"},\n };\n\n for (String[] urlClassCombo : drivers) {\n String driverURL = urlClassCombo[0];\n String driverClassName = urlClassCombo[1];\n try {\n @SuppressWarnings(\"rawtypes\")\n Class driverClass = Class.forName(driverClassName);\n DriverManager\n .registerDriver((Driver) driverClass.newInstance());\n supportedJdbcUrls.put(driverURL, driverClassName);\n } catch (Exception e) {\n // Skipping this driver.\n }\n }\n }\n\n public Map<String, String> getSupportedDriverURLs() {\n return Collections.unmodifiableMap(supportedJdbcUrls);\n }\n\n public Progress getProgress() {\n return progress;\n }\n}" ]
import com.rolfje.anonimatron.anonymizer.AnonymizerService; import com.rolfje.anonimatron.anonymizer.Hasher; import com.rolfje.anonimatron.anonymizer.SynonymCache; import com.rolfje.anonimatron.commandline.CommandLine; import com.rolfje.anonimatron.configuration.Configuration; import com.rolfje.anonimatron.file.FileAnonymizerService; import com.rolfje.anonimatron.jdbc.JdbcAnonymizerService; import org.apache.commons.cli.UnrecognizedOptionException; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Map; import java.util.Map.Entry; import java.util.Set;
package com.rolfje.anonimatron; /** * Start of a beautiful anonymized new world. * */ public class Anonimatron { public static String VERSION = "UNKNOWN"; static { try { InputStream resourceAsStream = Anonimatron.class.getResourceAsStream("version.txt"); InputStreamReader inputStreamReader = new InputStreamReader(resourceAsStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); VERSION = bufferedReader.readLine(); bufferedReader.close(); inputStreamReader.close(); resourceAsStream.close(); } catch (IOException e) { throw new RuntimeException("Could not determine version. " + e.getMessage()); } } public static void main(String[] args) throws Exception { try { CommandLine commandLine = new CommandLine(args); if (commandLine.getConfigfileName() != null) { Configuration config = getConfiguration(commandLine); anonymize(config, commandLine.getSynonymfileName()); } else if (commandLine.isConfigExample()) { printDemoConfiguration(); } else { CommandLine.printHelp(); } } catch (UnrecognizedOptionException e) { System.err.println(e.getMessage()); CommandLine.printHelp(); } } private static Configuration getConfiguration(CommandLine commandLine) throws Exception { // Load configuration Configuration config = Configuration.readFromFile(commandLine.getConfigfileName()); if (commandLine.getJdbcurl() != null) { config.setJdbcurl(commandLine.getJdbcurl()); } if (commandLine.getUserid() != null) { config.setUserid(commandLine.getUserid()); } if (commandLine.getPassword() != null) { config.setPassword(commandLine.getPassword()); } config.setDryrun(commandLine.isDryrun()); return config; } private static void anonymize(Configuration config, String synonymFile) throws Exception { // Load Synonyms from disk if present.
SynonymCache synonymCache = getSynonymCache(synonymFile);
2
cm-heclouds/JAVA-HTTP-SDK
javaSDK/src/main/java/cmcc/iot/onenet/javasdk/api/datapoints/GetDatapointsListApi.java
[ "public abstract class AbstractAPI<T> {\n public String key;\n public String url;\n public Method method;\n public ObjectMapper mapper = initObjectMapper();\n\n private ObjectMapper initObjectMapper() {\n ObjectMapper objectMapper = new ObjectMapper();\n //关闭字段不识别报错\n objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);\n //调整默认时区为北京时间\n TimeZone timeZone = TimeZone.getTimeZone(\"GMT+8\");\n DateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.CHINA);\n dateFormat.setTimeZone(timeZone);\n objectMapper.setDateFormat(dateFormat);\n objectMapper.setTimeZone(timeZone);\n return objectMapper;\n }\n}", "public class OnenetApiException extends RuntimeException {\n\t private String message = null;\n\t public String getMessage() {\n\t\treturn message;\n\t}\n\t\tpublic OnenetApiException( String message) {\n\t this.message = message;\n\t }\n}", "public class HttpGetMethod extends BasicHttpMethod {\n\n\tprivate final Logger logger = LoggerFactory.getLogger(this.getClass());\n\tHttpGet httpGet;\n\n\tpublic HttpGetMethod(Method method) {\n\t\tsuper(method);\n\n\t}\n\n\tpublic HttpResponse execute() throws Exception {\n\t\tHttpResponse httpResponse = null;\n\t\thttpClient = HttpClients.createDefault();\n\n\t\thttpResponse = httpClient.execute(httpRequestBase);\n\t\tint statusCode = httpResponse.getStatusLine().getStatusCode();\n\t\tif (statusCode != HttpStatus.SC_OK && statusCode != 221) {\n\t\t\tString response = EntityUtils.toString(httpResponse.getEntity());\n\t\t\tlogger.error(\"request failed status:{}, response::{}\",statusCode, response);\n\t\t\tthrow new OnenetApiException(\"request failed: \" + response);\n\t\t}\n\n\t\treturn httpResponse;\n\t}\n}", "public enum Method{\n POST,GET,DELETE,PUT\n}", "public class BasicResponse<T> {\n\tpublic int errno;\n\tpublic String error;\n @JsonProperty(\"data\")\n public Object dataInternal;\n public T data;\n @JsonIgnore\n public String json;\n\n\tpublic String getJson() {\n\t\treturn json;\n\t}\n\n\tpublic void setJson(String json) {\n\t\tthis.json = json;\n\t}\n\n\tpublic int getErrno() {\n return errno;\n }\n\n public void setErrno(int errno) {\n this.errno = errno;\n }\n\n public String getError() {\n return error;\n }\n\n public void setError(String error) {\n this.error = error;\n }\n\n @JsonGetter(\"data\")\n public Object getDataInternal() {\n return dataInternal;\n }\n @JsonSetter(\"data\")\n public void setDataInternal(Object dataInternal) {\n this.dataInternal = dataInternal;\n }\n\n public T getData() {\n return data;\n }\n\n public void setData(T data) {\n this.data = data;\n }\n}", "public class DatapointsList {\n\t@JsonProperty(\"count\")\n\tprivate String count;\n\t@JsonProperty(\"cursor\")\n\tprivate String cursor;\n\t\n\tpublic String getCursor() {\n\t\treturn cursor;\n\t}\n\tpublic void setCursor(String cursor) {\n\t\tthis.cursor = cursor;\n\t}\n\tpublic String getCount() {\n\t\treturn count;\n\t}\n\tpublic void setCount(String count) {\n\t\tthis.count = count;\n\t}\n\n\tpublic ArrayList<DatastreamsItem> getDevices() {\n\t\treturn devices;\n\t}\n\n\n\n\n\tpublic void setDevices(ArrayList<DatastreamsItem> devices) {\n\t\tthis.devices = devices;\n\t}\n\n\n\n\n\t@JsonProperty(\"datastreams\")\n\tprivate ArrayList<DatastreamsItem> devices;\n\t\n\t\n\t\n\t@JsonCreator\n\tpublic DatapointsList(@JsonProperty(\"count\")String count, @JsonProperty(\"datastreams\")ArrayList<DatastreamsItem> devices) {\n\t\tsuper();\n\t\tthis.count = count;\n\t\tthis.devices = devices;\n\t}\n\n\n\n\n\tpublic static class DatastreamsItem{\n\t\t@JsonProperty(\"id\")\n\t\tpublic String id;\n\t\tpublic String getId() {\n\t\t\treturn id;\n\t\t}\n\n\n\n\t\tpublic void setId(String id) {\n\t\t\tthis.id = id;\n\t\t}\n\n\n\n\t\tpublic List<DatapointsItem> getDatapoints() {\n\t\t\treturn datapoints;\n\t\t}\n\n\n\n\t\tpublic void setDatapoints(List<DatapointsItem> datapoints) {\n\t\t\tthis.datapoints = datapoints;\n\t\t}\n\n\n\n\t\t@JsonProperty(\"datapoints\")\n\t\tpublic List<DatapointsItem>datapoints;\n\t\t\n\t\t\n\t\t@JsonCreator\n\t\tpublic DatastreamsItem(@JsonProperty(\"id\")String id, @JsonProperty(\"datapoints\")List<DatapointsItem> datapoints) {\n\t\t\tsuper();\n\t\t\tthis.id = id;\n\t\t\tthis.datapoints = datapoints;\n\t\t}\n\n\n\n\t\tpublic static class DatapointsItem{\n\t\t\t@JsonProperty(\"at\")\n\t\t\tprivate String at;\n\t\t\tpublic String getAt() {\n\t\t\t\treturn at;\n\t\t\t}\n\n\t\t\tpublic void setAt(String at) {\n\t\t\t\tthis.at = at;\n\t\t\t}\n\n\t\t\tpublic Object getValue() {\n\t\t\t\treturn value;\n\t\t\t}\n\n\t\t\tpublic void setValue(Object value) {\n\t\t\t\tthis.value = value;\n\t\t\t}\n\n\t\t\t@JsonProperty(\"value\")\n\t\t\tprivate Object value;\n\t\t\n\t\t\t@JsonCreator\n\t\t\tpublic DatapointsItem(@JsonProperty(\"at\")String at, @JsonProperty(\"value\")Object value) {\n\t\t\t\tsuper();\n\t\t\t\tthis.at = at;\n\t\t\t\tthis.value = value;\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\t\t\n}", "public class DatastreamsResponse {\n\t@JsonProperty(\"id\")\n\tprivate String id;\n\t@JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n\t@JsonProperty(\"create_time\")\n\tprivate Date createTime;\n\t@JsonProperty(\"tags\")\n\tprivate List<String> tags;\n\t@JsonProperty(\"unit\")\n\tprivate String unit;\n\t@JsonProperty(\"unit_symbol\")\n\tprivate String unitSymbol;\n\t@JsonProperty(\"current_value\")\n\tprivate Object currentValue;\n\t@JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n\t@JsonProperty(\"update_at\")\n\tprivate Date updateAt;\n\t@JsonProperty(\"formula\")\n\tprivate String formula;\n\t@JsonProperty(\"interval\")\n\tprivate int interval;\n\t@JsonProperty(\"cmd\")\n\tprivate String cmd;\n\t@JsonProperty(\"uuid\")\n\tprivate String uuid;\n\t@JsonCreator\n\tpublic DatastreamsResponse(@JsonProperty(\"id\")String id, @JsonProperty(\"create_time\")Date createTime, @JsonProperty(\"tags\")List<String> tags, @JsonProperty(\"unit\")String unit, @JsonProperty(\"unit_symbol\")String unitSymbol,\n\t\t\t@JsonProperty(\"current_value\") Object currentValue,@JsonProperty(\"update_at\")Date updateAt,@JsonProperty(\"formula\")String formula,@JsonProperty(\"interval\")int interval,@JsonProperty(\"cmd\")String cmd,@JsonProperty(\"uuid\")String uuid) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.createTime = createTime;\n\t\tthis.tags = tags;\n\t\tthis.unit = unit;\n\t\tthis.unitSymbol = unitSymbol;\n\t\tthis.currentValue = currentValue;\n\t\tthis.updateAt = updateAt;\n\t\tthis.formula=formula;\n\t\tthis.interval=interval;\n\t\tthis.cmd=cmd;\n\t\tthis.uuid=uuid;\n\t}\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\tpublic void setId(String id) {\n\t\tthis.id = id;\n\t}\n\tpublic Date getCreateTime() {\n\t\treturn createTime;\n\t}\n\tpublic void setCreateTime(Date createTime) {\n\t\tthis.createTime = createTime;\n\t}\n\tpublic List<String> getTags() {\n\t\treturn tags;\n\t}\n\tpublic void setTags(List<String> tags) {\n\t\tthis.tags = tags;\n\t}\n\tpublic String getUnit() {\n\t\treturn unit;\n\t}\n\tpublic void setUnit(String unit) {\n\t\tthis.unit = unit;\n\t}\n\tpublic String getUnitSymbol() {\n\t\treturn unitSymbol;\n\t}\n\tpublic void setUnitSymbol(String unitSymbol) {\n\t\tthis.unitSymbol = unitSymbol;\n\t}\n\tpublic Object getCurrentValue() {\n\t\treturn currentValue;\n\t}\n\tpublic void setCurrentValue(Object currentValue) {\n\t\tthis.currentValue = currentValue;\n\t}\n\tpublic Date getUpdateAt() {\n\t\treturn updateAt;\n\t}\n\tpublic String getFormula() {\n\t\treturn formula;\n\t}\n\tpublic void setFormula(String formula) {\n\t\tthis.formula = formula;\n\t}\n\tpublic int getInterval() {\n\t\treturn interval;\n\t}\n\tpublic void setInterval(int interval) {\n\t\tthis.interval = interval;\n\t}\n\tpublic String getCmd() {\n\t\treturn cmd;\n\t}\n\tpublic void setCmd(String cmd) {\n\t\tthis.cmd = cmd;\n\t}\n\tpublic String getUuid() {\n\t\treturn uuid;\n\t}\n\tpublic void setUuid(String uuid) {\n\t\tthis.uuid = uuid;\n\t}\n\tpublic void setUpdateAt(Date updateAt) {\n\t\tthis.updateAt = updateAt;\n\t}\n\t/*public static class CurrentValue{\n\t\t@JsonProperty(\"index\")\n\t\tprivate String index;\n\n\t\n\t\tpublic String getIndex() {\n\t\t\treturn index;\n\t\t}\n\n\n\t\tpublic void setIndex(String index) {\n\t\t\tthis.index = index;\n\t\t}\n\n\n\t\t@JsonCreator\n\t\tpublic CurrentValue(@JsonProperty(\"index\")String index) {\n\t\t\tsuper();\n\t\t\tthis.index = index;\n\t\t}\n\t}*/\n\t\n}", "public class Config {\n\tprivate final static Properties properties;\n private static org.slf4j.Logger logger = LoggerFactory.getLogger(Config.class);\n\tstatic {\n//\t\tLogger.getRootLogger().setLevel(Level.OFF);\n\t\tInputStream in = Config.class.getClassLoader().getResourceAsStream(\"config.properties\");\n\t\tproperties = new Properties();\n\t\ttry {\n\t\t\tproperties.load(in);\n\t\t} catch (IOException e) {\n\t\t\tlogger.error(\"init config error\", e);\n\t\t}\n\t}\n\n\t/**\n\t * 读取以逗号分割的字符串,作为字符串数组返回\n\t *\n\t * @param conf\n\t * @return\n\t */\n\tpublic static List<String> getStringList(String conf) {\n\t\treturn Arrays.asList(StringUtils.split(properties.getProperty(conf), \",\"));\n\t}\n\n\t/**\n\t * 读取字符串\n\t *\n\t * @param conf\n\t * @return\n\t */\n\tpublic static String getString(String conf) {\n\t\treturn properties.getProperty(conf);\n\t}\n\n\t/**\n\t * 读取整数\n\t *\n\t * @param conf\n\t * @return\n\t */\n\tpublic static int getInt(String conf) {\n\t\tint ret = 0;\n\t\ttry {\n\t\t\tret = Integer.parseInt(getString(conf));\n\t\t} catch (NumberFormatException e) {\n\t\t\tlogger.error(\"format error\", e);\n\t\t}\n\t\treturn ret;\n\t}\n\n\t/**\n\t * 读取布尔值\n\t *\n\t * @param conf\n\t * @return\n\t */\n\tpublic static boolean getBoolean(String conf) {\n\t\treturn Boolean.parseBoolean(getString(conf));\n\t}\n}" ]
import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.HttpResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import cmcc.iot.onenet.javasdk.api.AbstractAPI; import cmcc.iot.onenet.javasdk.exception.OnenetApiException; import cmcc.iot.onenet.javasdk.http.HttpGetMethod; import cmcc.iot.onenet.javasdk.request.RequestInfo.Method; import cmcc.iot.onenet.javasdk.response.BasicResponse; import cmcc.iot.onenet.javasdk.response.datapoints.DatapointsList; import cmcc.iot.onenet.javasdk.response.datastreams.DatastreamsResponse; import cmcc.iot.onenet.javasdk.utils.Config;
package cmcc.iot.onenet.javasdk.api.datapoints; public class GetDatapointsListApi extends AbstractAPI{ private HttpGetMethod HttpMethod; private String datastreamIds; private String start; private String end; private String devId; private Integer duration; private Integer limit; private String cursor; private Integer interval; private String metd; private Integer first; private String sort; private final Logger logger = LoggerFactory.getLogger(this.getClass()); /** * 数据点查询 * @param datastreamIds:查询的数据流,多个数据流之间用逗号分隔(可选),String * @param start:提取数据点的开始时间(可选),String * @param end:提取数据点的结束时间(可选),String * @param devId:设备ID,String * @param duration:查询时间区间(可选,单位为秒),Integer * start+duration:按时间顺序返回从start开始一段时间内的数据点 * end+duration:按时间倒序返回从end回溯一段时间内的数据点 * @param limit:限定本次请求最多返回的数据点数,0<n<=6000(可选,默认1440),Integer * @param cursor:指定本次请求继续从cursor位置开始提取数据(可选),String * @param interval:通过采样方式返回数据点,interval值指定采样的时间间隔(可选),Integer,参数已废弃 * @param metd:指定在返回数据点时,同时返回统计结果,可能的值为(可选),String * @param first:返回结果中最值的时间点。1-最早时间,0-最近时间,默认为1(可选),Integer * @param sort:值为DESC|ASC时间排序方式,DESC:倒序,ASC升序,默认升序,String * @param key:masterkey 或者 设备apikey */ public GetDatapointsListApi(String datastreamIds, String start, String end, String devId, Integer duration, Integer limit, String cursor, @Deprecated Integer interval, String metd, Integer first, String sort,String key) { super(); this.datastreamIds = datastreamIds; this.start = start; this.end = end; this.devId = devId; this.duration = duration; this.limit = limit; this.cursor = cursor; this.interval = interval; this.metd = metd; this.first = first; this.sort = sort; this.key=key;
this.method= Method.GET;
3
LyashenkoGS/analytics4github
src/main/java/com/rhcloud/analytics4github/service/UniqueContributorsService.java
[ "public enum GitHubApiEndpoints {\n COMMITS, STARGAZERS\n}", "public class Author {\n private final String name;\n private final String email;\n\n /**\n * @param name represent author name. Add an empty String of zero length, if not present\n * @param email represent author email. Add an empty String of zero length, if not present\n */\n public Author(String name, String email) {\n this.email = email;\n this.name = name;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n Author author = (Author) o;\n\n if (name != null ? !name.equals(author.name) : author.name != null) return false;\n return email != null ? email.equals(author.email) : author.email == null;\n\n }\n\n @Override\n public int hashCode() {\n int result = name != null ? name.hashCode() : 0;\n result = 31 * result + (email != null ? email.hashCode() : 0);\n return result;\n }\n\n public String getName() {\n return name;\n }\n\n public String getEmail() {\n return email;\n }\n\n @Override\n public String toString() {\n final StringBuilder sb = new StringBuilder(\"Author{\");\n sb.append(\"name='\").append(name).append('\\'');\n sb.append(\", email='\").append(email).append('\\'');\n sb.append('}');\n return sb.toString();\n }\n}", "@ApiModel\npublic class RequestFromFrontendDto {\n @ApiParam(required = true, example = \"mewo2\", value = \"a repository author. Example: mewo2\")\n private String author;\n @ApiParam(required = true, example = \"terrain\", value = \"a repository author. Example: terrain\")\n private String repository;\n @ApiParam(required = true, example = \"2016-08-10\", value = \"a data to start analyze from. Example: 2016-08-10\")\n @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)\n private LocalDate startPeriod;\n @ApiParam(required = true, example = \"2016-08-17\", value = \"a data until analyze. Example: 2016-08-17\")\n @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)\n private LocalDate endPeriod;\n\n public RequestFromFrontendDto() {\n }\n\n public String getAuthor() {\n return author;\n }\n\n public void setAuthor(String author) {\n this.author = author;\n }\n\n public String getRepository() {\n return repository;\n }\n\n public void setRepository(String repository) {\n this.repository = repository;\n }\n\n public LocalDate getStartPeriod() {\n return startPeriod;\n }\n\n public void setStartPeriod(LocalDate startPeriod) {\n this.startPeriod = startPeriod;\n }\n\n public LocalDate getEndPeriod() {\n return endPeriod;\n }\n\n public void setEndPeriod(LocalDate endPeriod) {\n this.endPeriod = endPeriod;\n }\n}", "@ApiModel\npublic class ResponceForFrontendDto {\n private String name;\n private int requestsLeft;\n private List<Integer> data;\n public ResponceForFrontendDto() {\n }\n\n public ResponceForFrontendDto(String name, List<Integer> data) {\n this.name = name;\n this.data = data;\n }\n\n public ResponceForFrontendDto(String name, List<Integer> data, int requestsLeft) {\n this.name = name;\n this.data = data;\n this.requestsLeft = requestsLeft;\n }\n\n @Override\n public String toString() {\n return \"ResponceForFrontendDto{\" +\n \"name='\" + name + '\\'' +\n \", requestsLeft=\" + requestsLeft +\n \", data=\" + data +\n '}';\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public List<Integer> getData() {\n return data;\n }\n\n public void setData(List<Integer> data) {\n this.data = data;\n }\n\n public Integer getRequestsLeft() {\n return requestsLeft;\n }\n\n public void setRequestsLeft(Integer requestsLeft) {\n this.requestsLeft = requestsLeft;\n }\n}", "public class GitHubRESTApiException extends Exception {\n\n public GitHubRESTApiException(String message, Throwable cause) {\n super(message, cause);\n }\n}", "public class GitHubApiIterator implements Iterator<JsonNode> {\n private static Logger LOG = LoggerFactory.getLogger(GitHubApiIterator.class);\n\n private final int numberOfPages;\n private final String projectName;\n private final GitHubApiEndpoints githubEndpoint;\n private final RestTemplate restTemplate;\n private final ExecutorService executor = Executors.newFixedThreadPool(5);\n private Instant since = null;\n private Instant until = null;\n private String author;\n private volatile AtomicInteger counter = new AtomicInteger();\n public static int requestsLeft;\n\n public GitHubApiIterator(String projectName, RestTemplate restTemplate, GitHubApiEndpoints endpoint\n ) throws URISyntaxException, GitHubRESTApiException {\n this.restTemplate = restTemplate;\n this.projectName = projectName;\n this.githubEndpoint = endpoint;\n this.numberOfPages = getLastPageNumber(projectName);\n this.counter.set(numberOfPages);\n }\n\n public GitHubApiIterator(String projectName, String author, RestTemplate restTemplate, GitHubApiEndpoints endpoint\n ) throws URISyntaxException, GitHubRESTApiException {\n this.author = author;\n this.restTemplate = restTemplate;\n this.projectName = projectName;\n this.githubEndpoint = endpoint;\n this.numberOfPages = getLastPageNumber(projectName);\n this.counter.set(numberOfPages);\n }\n\n public GitHubApiIterator(String projectName, RestTemplate restTemplate, GitHubApiEndpoints endpoint,\n Instant since, Instant until) throws URISyntaxException, GitHubRESTApiException {\n this.since = since;\n this.until = until;\n this.restTemplate = restTemplate;\n this.projectName = projectName;\n this.githubEndpoint = endpoint;\n this.numberOfPages = getLastPageNumber(projectName);\n this.counter.set(numberOfPages);\n }\n\n public int getNumberOfPages() {\n return numberOfPages;\n }\n\n public String getProjectName() {\n return projectName;\n }\n\n public int getLastPageNumber(String projectName) throws URISyntaxException, GitHubRESTApiException {\n return Utils.getLastPageNumber(projectName, restTemplate, githubEndpoint, author, since, until);\n }\n\n public synchronized boolean hasNext() {\n return counter.get() > 0;\n }\n\n /**\n * Performs side efects (parsing a header and updating the static field\n * @return JsonNode that represents a stargazers list\n *\n */\n public JsonNode next() {\n if (counter.get() > 0) {\n String basicURL = \"https://api.github.com/repos/\" + projectName + \"/\" + githubEndpoint.toString().toLowerCase();\n UriComponents page;\n\n if (since != null && until!=null) {\n page = UriComponentsBuilder.fromHttpUrl(basicURL)\n .queryParam(\"page\", counter.getAndDecrement())\n .queryParam(\"since\", since)\n .queryParam(\"until\",until)\n .build();\n } else if (since != null){\n page = UriComponentsBuilder.fromHttpUrl(basicURL)\n .queryParam(\"page\", counter.getAndDecrement())\n .queryParam(\"since\", since)\n .build();\n } else if (author != null) {\n page = UriComponentsBuilder.fromHttpUrl(basicURL)\n .queryParam(\"page\", counter.getAndDecrement())\n .queryParam(\"author\", author)\n .build();\n } else {\n page = UriComponentsBuilder.fromHttpUrl(basicURL)\n .queryParam(\"page\", counter.getAndDecrement())\n .build();\n }\n String URL = page.encode().toUriString();\n LOG.debug(URL);\n //sent request\n HttpEntity entity = restTemplate.getForEntity(URL, JsonNode.class);\n initializeRequestsLeft(restTemplate);\n JsonNode node = new ObjectMapper().convertValue(entity.getBody(), JsonNode.class);\n LOG.debug(node.toString());\n return node;\n } else throw new IndexOutOfBoundsException(\"there is no next element\");\n }\n\n public static void initializeRequestsLeft(RestTemplate restTemplate){\n try{\n HttpEntity entity = restTemplate.getForEntity(\"https://api.github.com/users/whatever\", JsonNode.class);\n HttpHeaders headers = entity.getHeaders();\n GitHubApiIterator.requestsLeft = Integer.parseInt(headers.get(\"X-RateLimit-Remaining\").get(0));\n } catch (Exception e){\n LOG.debug(e.getMessage());\n }\n }\n\n /**\n * @param batchSize number of numberOfPages to return\n * @return list of stargazer numberOfPages according to batchSize\n * @throws IndexOutOfBoundsException if there is no elements left to return\n */\n public List<JsonNode> next(int batchSize) throws ExecutionException, InterruptedException {\n int reliableBatchSize = batchSize;\n if (batchSize > counter.get()) {\n LOG.warn(\"batch size is bigger then number of elements left, decrease batch size to \" + counter);\n reliableBatchSize = counter.get();\n }\n\n List<CompletableFuture<JsonNode>> completableFutures = IntStream.range(0, reliableBatchSize)\n .mapToObj(\n e -> CompletableFuture\n .supplyAsync(this::next, executor)\n ).collect(Collectors.toList());\n\n CompletableFuture<List<JsonNode>> result = CompletableFuture\n .allOf(completableFutures\n .toArray(new CompletableFuture[completableFutures.size()]))\n .thenApply(v -> completableFutures.stream()\n .map(CompletableFuture::join)\n .collect(Collectors.toList()));//compose all in one task\n List<JsonNode> jsonNodes = result.get();//\n LOG.debug(\"batch completed, counter:\" + counter.get());\n return jsonNodes;\n }\n\n /**\n * invoke explicitly after every class usage to close ThreadPool correctly\n */\n public void close() {\n this.executor.shutdown();\n }\n}", "public class Utils {\n static String HTTPS_API_GITHUB_COM_REPOS = \"https://api.github.com/repos/\";\n private static Logger LOG = LoggerFactory.getLogger(Utils.class);\n private Utils() {\n }\n\n /**\n * Assert that given Date is in the range from current monday to sunday\n * include border values.\n * Must return true for all days from this week include monday and sunday.\n */\n public static boolean isWithinThisWeekRange(LocalDate timestamp) {\n LOG.debug(\"Check is the \" + timestamp + \" is within this week range\");\n LocalDate today = LocalDate.now();\n LocalDate monday = today.with(previousOrSame(MONDAY));\n LocalDate sunday = today.with(nextOrSame(SUNDAY));\n boolean isWithinThisWeekRange = (timestamp.isAfter(monday.minusDays(1))) && timestamp.isBefore(sunday.plusDays(1));\n LOG.debug(String.valueOf(isWithinThisWeekRange));\n return isWithinThisWeekRange;\n }\n\n /**\n *\n * @param timestamp String representing date and time in ISO 8601 YYYY-MM-DDTHH:MM:SSZ\n * @param requestFromFrontendDto DTO came from frontend\n * @return if commit is withing analitics period\n */\n public static boolean isWithinThisMonthRange(LocalDate timestamp, RequestFromFrontendDto requestFromFrontendDto) {\n LOG.debug(\"Check is the \" + timestamp + \" is within this month range\");\n LocalDate monthStart = requestFromFrontendDto.getStartPeriod();\n LocalDate monthEnd = requestFromFrontendDto.getEndPeriod();\n\n boolean isWithinThisMonthRange = (timestamp.isAfter(monthStart) || timestamp.isEqual(monthStart))\n && (timestamp.isBefore(monthEnd) || timestamp.isEqual(monthEnd));\n LOG.debug(String.valueOf(isWithinThisMonthRange));\n return isWithinThisMonthRange;\n }\n\n /**\n * @param timestamp String representing date and time in ISO 8601 YYYY-MM-DDTHH:MM:SSZ\n * @return LocalDate parsed from the given @param. Example (2007-12-03)\n */\n public static LocalDate parseTimestamp(String timestamp) {\n return LocalDate.parse(timestamp, DateTimeFormatter.ISO_DATE_TIME);\n }\n\n public static Instant getThisMonthBeginInstant() {\n LocalDateTime localDate = LocalDateTime.now().withSecond(0).withHour(0).withMinute(0)\n .with(TemporalAdjusters.firstDayOfMonth()).truncatedTo(ChronoUnit.SECONDS);\n return localDate.toInstant(ZoneOffset.UTC);\n }\n\n public static Instant getPeriodInstant(LocalDate localDate) {\n LocalDateTime localDateTime = localDate.atStartOfDay();\n return localDateTime.toInstant(ZoneOffset.UTC);\n }\n\n public static Instant getThisWeekBeginInstant() {\n LocalDateTime localDate = LocalDateTime.now().withSecond(0).withHour(0).withMinute(0)\n .with((MONDAY)).truncatedTo(ChronoUnit.SECONDS);\n return localDate.toInstant(ZoneOffset.UTC);\n }\n\n public static ResponceForFrontendDto buildJsonForFrontend(List<Integer> stargazersFrequencyList) throws IOException, ClassNotFoundException {\n ResponceForFrontendDto outputDto = new ResponceForFrontendDto();\n outputDto.setName(\"Stars\");\n outputDto.setData(stargazersFrequencyList);\n return outputDto;\n }\n\n public static List<Integer> parseWeekStargazersMapFrequencyToWeekFrequencyList(TreeMap<LocalDate, Integer> weekStargazersFrequenyMap) {\n LOG.debug(\"parseWeekStargazersMapFrequencyToWeekFrequencyList\");\n List<Integer> output = new ArrayList<>();\n for (DayOfWeek dayOfWeek : DayOfWeek.values()) {\n LOG.debug(dayOfWeek.toString());\n Optional<LocalDate> optional = weekStargazersFrequenyMap.keySet().stream()\n .filter(e -> DayOfWeek.from(e).equals(dayOfWeek))\n .findFirst();\n if (optional.isPresent()) {\n LOG.debug(\"match \" + optional.get() + \" with frequency \" + weekStargazersFrequenyMap.get(optional.get()));\n output.add(weekStargazersFrequenyMap.get(optional.get()));\n } else {\n LOG.debug(\"no match from \" + weekStargazersFrequenyMap.keySet());\n LOG.debug(\"add 0\");\n output.add(0);\n }\n\n }\n LOG.debug(\"Output is\" + output.toString());\n return output;\n }\n\n public static List<Integer> parseMonthFrequencyMapToFrequencyLIst(TreeMap<LocalDate, Integer> mockWeekStargazersFrequencyMap) throws IOException {\n int lastDayOfMonth = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth()).getDayOfMonth();\n LOG.debug(String.valueOf(lastDayOfMonth));\n List<Integer> monthStargazersFrequency = new ArrayList<>(lastDayOfMonth);\n for (int dayOfMonth = 1; dayOfMonth < lastDayOfMonth + 1; dayOfMonth++) {\n LOG.debug(\"day of month: \" + dayOfMonth);\n Optional<Integer> frequency = Optional.empty();\n for (LocalDate localDate : mockWeekStargazersFrequencyMap.keySet()) {\n if (dayOfMonth == localDate.getDayOfMonth()) {\n frequency = Optional.of(mockWeekStargazersFrequencyMap.get(localDate));\n }\n }\n if (frequency.isPresent()) {\n monthStargazersFrequency.add(frequency.get());\n } else {\n monthStargazersFrequency.add(0);\n }\n LOG.debug(monthStargazersFrequency.toString());\n }\n return monthStargazersFrequency;\n }\n\n\n public static TreeMap<LocalDate, Integer> buildStargazersFrequencyMap(List<LocalDate> stargazersList) throws IOException, URISyntaxException, ExecutionException, InterruptedException {\n //temporary set\n Set<LocalDate> stargazersDateSet = new HashSet<>(stargazersList);\n Map<LocalDate, Integer> stargazersFrequencyMap = stargazersDateSet.stream().collect(Collectors\n .toMap(Function.identity(), e -> Collections.frequency(stargazersList, e)));\n TreeMap<LocalDate, Integer> localDateIntegerNavigableMap = new TreeMap<>(stargazersFrequencyMap);\n LOG.debug(\"stargazers week/month frequency map:\" + localDateIntegerNavigableMap.toString());\n return localDateIntegerNavigableMap;\n }\n\n public static int getLastPageNumber(String repository, RestTemplate restTemplate, GitHubApiEndpoints githubEndpoint, String author, Instant since, Instant until) throws GitHubRESTApiException{\n String url;\n try {\n if (since != null) {\n url = UriComponentsBuilder.fromHttpUrl(HTTPS_API_GITHUB_COM_REPOS)\n .path(repository).path(\"/\" + githubEndpoint.toString().toLowerCase())\n .queryParam(\"since\", since)\n .queryParam(\"until\", until)\n .build().encode()\n .toUriString();\n } else if (author != null) {\n url = UriComponentsBuilder.fromHttpUrl(HTTPS_API_GITHUB_COM_REPOS)\n .path(repository).path(\"/\" + githubEndpoint.toString().toLowerCase())\n .queryParam(\"author\", author)\n .queryParam(\"until\", until)\n .build().encode()\n .toUriString();\n } else {\n url = UriComponentsBuilder.fromHttpUrl(HTTPS_API_GITHUB_COM_REPOS)\n .path(repository).path(\"/\" + githubEndpoint.toString().toLowerCase())\n .build().encode()\n .toUriString();\n }\n LOG.debug(\"URL to get the last commits page number:\" + url);\n HttpHeaders headers = restTemplate.headForHeaders(url);\n String link = headers.getFirst(\"Link\");\n LOG.debug(\"Link: \" + link);\n LOG.debug(\"parse link by regexp\");\n Pattern p = Pattern.compile(\"page=(\\\\d*)>; rel=\\\"last\\\"\");\n int lastPageNum = 0;\n try {\n Matcher m = p.matcher(link);\n if (m.find()) {\n lastPageNum = Integer.valueOf(m.group(1));\n LOG.debug(\"parse result: \" + lastPageNum);\n }\n } catch (NullPointerException npe) {\n // npe.printStackTrace();\n LOG.info(\"Propably \" + repository + \"commits consists from only one page\");\n return 1;\n }\n return lastPageNum;\n } catch (Exception e) {\n throw new GitHubRESTApiException(\" Can't access GitHub REST \", e);\n }\n }\n}" ]
import com.fasterxml.jackson.databind.JsonNode; import com.rhcloud.analytics4github.config.GitHubApiEndpoints; import com.rhcloud.analytics4github.domain.Author; import com.rhcloud.analytics4github.dto.RequestFromFrontendDto; import com.rhcloud.analytics4github.dto.ResponceForFrontendDto; import com.rhcloud.analytics4github.exception.GitHubRESTApiException; import com.rhcloud.analytics4github.util.GitHubApiIterator; import com.rhcloud.analytics4github.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; import java.io.IOException; import java.net.URISyntaxException; import java.time.Instant; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import java.util.stream.StreamSupport;
LOG.debug("No commits by an author name: " + author.getName() + " untill " + uniqueSince); LOG.debug("Recheck by the author email: " + author.getEmail()); String queryByAuthorEmail = UriComponentsBuilder.fromHttpUrl("https://api.github.com/repos/") .path(repository) .path("/" + GitHubApiEndpoints.COMMITS.toString().toLowerCase()) .queryParam("author", author.getEmail()) .queryParam("until", uniqueSince) .build().encode() .toUriString(); LOG.debug(queryByAuthorEmail); commitsPage = restTemplate.getForObject(queryByAuthorEmail, JsonNode.class); LOG.debug(commitsPage.toString()); return !commitsPage.has(0);//return true if a commits page look like [] } else return false; } List<JsonNode> getCommits(String repository, Instant since, Instant until) throws URISyntaxException, ExecutionException, InterruptedException, GitHubRESTApiException { GitHubApiIterator gitHubApiIterator = new GitHubApiIterator(repository, restTemplate, GitHubApiEndpoints.COMMITS, since, until); List<JsonNode> commitPages = new ArrayList<>(); List<JsonNode> commits = new ArrayList<>(); while (gitHubApiIterator.hasNext()) { List<JsonNode> commitPagesBatch = gitHubApiIterator.next(5); commitPages.addAll(commitPagesBatch); } gitHubApiIterator.close(); LOG.debug(commitPages.toString()); for (JsonNode page : commitPages) { for (JsonNode commit : page) { commits.add(commit); LOG.debug(commit.toString()); } } return commits; } Set<Author> getAuthorNameAndEmail(List<JsonNode> commits) { Set<Author> authors = new HashSet<>(); for (JsonNode commit : commits) { JsonNode authorEmail = commit.get("commit") .get("author").get("email"); JsonNode authorName = commit.get("commit") .get("author").get("name"); LOG.debug(authorEmail.textValue()); LOG.debug(authorName.textValue()); Author author = new Author(authorName.textValue(), authorEmail.textValue()); authors.add(author); } LOG.debug("Authors : " + authors); return authors; } Set<Author> getUniqueContributors(String projectName, Instant uniqueSince, Instant uniqueUntil) throws InterruptedException, ExecutionException, URISyntaxException, GitHubRESTApiException { Set<Author> authorsPerPeriod = getAuthorNameAndEmail(getCommits(projectName, uniqueSince, uniqueUntil)); Set<Author> newAuthors = authorsPerPeriod.parallelStream() .filter(author -> isUniqueContributor(projectName, author, uniqueSince)) .collect(Collectors.toSet()); LOG.debug("since" + uniqueSince + " are " + newAuthors.size() + " new authors: " + newAuthors.toString()); return newAuthors; } LocalDate getFirstContributionDate(Author author, String repository) throws GitHubRESTApiException { int reliableLastPageNumber = 0; String URL; if (author.getEmail() != null && !author.getEmail().isEmpty()) { reliableLastPageNumber = Utils.getLastPageNumber(repository, restTemplate, GitHubApiEndpoints.COMMITS, author.getEmail(), null, null); URL = UriComponentsBuilder .fromHttpUrl("https://api.github.com/repos/") .path(repository).path("/" + GitHubApiEndpoints.COMMITS.toString().toLowerCase()) .queryParam("page", reliableLastPageNumber) .queryParam("author", author.getEmail()) .build().encode() .toUriString(); } else { reliableLastPageNumber = Utils.getLastPageNumber(repository, restTemplate, GitHubApiEndpoints.COMMITS, author.getName(), null, null); URL = UriComponentsBuilder .fromHttpUrl("https://api.github.com/repos/") .path(repository).path("/" + GitHubApiEndpoints.COMMITS.toString().toLowerCase()) .queryParam("page", reliableLastPageNumber) .queryParam("author", author.getName()) .build().encode() .toUriString(); } LOG.debug(String.valueOf(reliableLastPageNumber)); LOG.info(URL); JsonNode commitsPage = restTemplate.getForObject(URL, JsonNode.class); for (JsonNode commit : commitsPage) { LOG.debug(commit.toString()); } List<JsonNode> commits = StreamSupport.stream(commitsPage.spliterator(), false).collect(Collectors.toList()); JsonNode commit; try { commit = commits.get(commits.size() - 1); LOG.info("First commit by " + author + " : " + commit.toString()); String date = commit.get("commit").get("author").get("date").textValue(); LOG.debug(date); LocalDate firstContributionDate = Utils.parseTimestamp(date); LOG.info(firstContributionDate.toString()); return firstContributionDate; } catch (ArrayIndexOutOfBoundsException ex) { LOG.error("Cant properly get commits for :" + author); ex.printStackTrace(); throw ex; } } List<LocalDate> getFirstAuthorCommitFrequencyList(String repository, Instant since, Instant until) throws InterruptedException, ExecutionException, URISyntaxException, GitHubRESTApiException { Set<Author> uniqueContributors = getUniqueContributors(repository, since, until); List<LocalDate> firstAuthorCommitFrequencyList = new ArrayList<>(); for (Author author : uniqueContributors) { try { firstAuthorCommitFrequencyList.add(getFirstContributionDate(author, repository)); } catch (ArrayIndexOutOfBoundsException ex) { LOG.error("cant properly getFirstContributionDate :" + author); LOG.error("don't add any to firstAuthorCommitFrequencyList for " + repository); } } LOG.info(firstAuthorCommitFrequencyList.toString()); return firstAuthorCommitFrequencyList; }
public ResponceForFrontendDto getUniqueContributorsFrequency(RequestFromFrontendDto requestFromFrontendDto) throws IOException, ClassNotFoundException, InterruptedException, ExecutionException, URISyntaxException, GitHubRESTApiException {
2
rwitzel/streamflyer
streamflyer-core/src/test/java/com/github/rwitzel/streamflyer/regex/addons/tokens/MyTokenProcessorTest.java
[ "public interface Modifier {\r\n\r\n /**\r\n * Processes the characters in the given character buffer, i.e. deletes or replaces or inserts characters, or keeps\r\n * the characters as they are.\r\n * \r\n * @param characterBuffer\r\n * The next characters provided from the modifiable stream. It contains the modifiable characters,\r\n * (optionally) preceded by unmodifiable characters.\r\n * <p>\r\n * The modifier can modify the content of the buffer as appropriate the modifier must not modify the\r\n * unmodifiable characters, i.e. the characters before position\r\n * <code>firstModifiableCharacterInBufferIndex</code> must not be modified.\r\n * <p>\r\n * Your modifier should manage the {@link StringBuilder#capacity() capacity} of the buffer on its own -\r\n * as the optimal management of the capacity depends on the specific purpose of the modifier.\r\n * <p>\r\n * The given buffer must be never null.\r\n * @param firstModifiableCharacterInBuffer\r\n * index of the first modifiable character in the buffer. The index of the first character in the buffer\r\n * is zero. If there is not modifiable character in the buffer, then this value is equal the length of\r\n * the buffer.\r\n * @param endOfStreamHit\r\n * True if no more characters can be read from the stream, i.e. the character buffer contains the all the\r\n * characters up to the end of the stream.\r\n * @return Returns an object that defines how {@link ModifyingReader} or {@link ModifyingWriter} shall behave before\r\n * calling {@link Modifier#modify(StringBuilder, int, boolean)} again.\r\n */\r\n public AfterModification modify(StringBuilder characterBuffer, int firstModifiableCharacterInBuffer,\r\n boolean endOfStreamHit);\r\n}\r", "public class ModifyingReader extends Reader {\r\n\r\n //\r\n // injected properties\r\n //\r\n\r\n /**\r\n * The reader that the reads from the underlying character stream.\r\n */\r\n protected Reader delegate;\r\n\r\n /**\r\n * The modifier thats replaces, deletes, inserts characters of the underlying stream, and manages the buffer size.\r\n */\r\n private Modifier modifier;\r\n\r\n //\r\n // properties that represent the mutable state\r\n //\r\n\r\n /**\r\n * At its begin the buffer contains unmodifiable characters (might be needed for look-behind matches as known from\r\n * regular expression matching). After the unmodifiable characters the buffer holds the modifiable characters. See\r\n * {@link #firstModifiableCharacterInBuffer}.\r\n */\r\n private StringBuilder characterBuffer;\r\n\r\n /**\r\n * The position of the first character in the {@link #characterBuffer input buffer} that is modifiable.\r\n * <p>\r\n * This character and the following characters in {@link #characterBuffer} can be modified by the {@link #modifier}.\r\n */\r\n private int firstModifiableCharacterInBuffer;\r\n\r\n /**\r\n * The value is taken from {@link AfterModification#getNewMinimumLengthOfLookBehind()} after\r\n * {@link Modifier#modify(StringBuilder, int, boolean)} is called. The value is <em>requested</em> by the\r\n * {@link Modifier}.\r\n * <p>\r\n * If this value is greater than {@link #firstModifiableCharacterInBuffer}, the modifier is probably faulty.\r\n */\r\n private int minimumLengthOfLookBehind;\r\n\r\n /**\r\n * The value is the sum of {@link AfterModification#getNewMinimumLengthOfLookBehind()} and\r\n * {@link AfterModification#getNewNumberOfChars()} after {@link Modifier#modify(StringBuilder, int, boolean)} is\r\n * called. The value is <em>requested</em> by the {@link Modifier}.\r\n */\r\n private int requestedNumCharactersInBuffer;\r\n\r\n /**\r\n * The value is initially taken from {@link AfterModification#getNumberOfCharactersToSkip()} after\r\n * {@link Modifier#modify(StringBuilder, int, boolean)} is called. Then during reading characters from the reader\r\n * this value is decremented.\r\n */\r\n private int numberOfCharactersToSkip;\r\n\r\n /**\r\n * True if the end of stream was detected.\r\n */\r\n private boolean endOfStreamHit = false;\r\n\r\n /**\r\n * The holds the last {@link AfterModification} provided by the {@link #modifier}. This property serves debugging\r\n * purposes only.\r\n */\r\n private AfterModification lastAfterModificationForDebuggingOnly = null;\r\n\r\n /**\r\n * @param reader\r\n * The underlying reader that provides the original, not modified characters. For optimal performance\r\n * choose a {@link BufferedReader}.\r\n * @param modifier\r\n * the object that modifies the stream.\r\n */\r\n public ModifyingReader(Reader reader, Modifier modifier) {\r\n super();\r\n\r\n this.delegate = reader;\r\n\r\n // take injected properties\r\n this.modifier = modifier;\r\n\r\n // initialize the mutable state\r\n this.numberOfCharactersToSkip = 0;\r\n this.minimumLengthOfLookBehind = 0; // we cannot do anything else\r\n this.firstModifiableCharacterInBuffer = 0;\r\n this.requestedNumCharactersInBuffer = 1; // any value\r\n this.characterBuffer = new StringBuilder(requestedNumCharactersInBuffer);\r\n adjustCapacityOfBuffer();\r\n }\r\n\r\n /**\r\n * Updates the input buffer according to {@link #minimumLengthOfLookBehind} and\r\n * {@link #requestedNumCharactersInBuffer}, and then fills the buffer up to its capacity.\r\n */\r\n private void updateBuffer() throws IOException {\r\n\r\n removeCharactersInBufferNotNeededAnyLonger();\r\n\r\n adjustCapacityOfBuffer();\r\n\r\n fill();\r\n }\r\n\r\n /**\r\n * Deletes those characters at the start of the buffer we do not need any longer.\r\n */\r\n private void removeCharactersInBufferNotNeededAnyLonger() {\r\n\r\n int charactersToDelete = firstModifiableCharacterInBuffer - minimumLengthOfLookBehind;\r\n\r\n if (charactersToDelete > 0) {\r\n characterBuffer.delete(0, charactersToDelete);\r\n firstModifiableCharacterInBuffer -= charactersToDelete;\r\n } else if (charactersToDelete < 0) {\r\n onFaultyModifier(-52, charactersToDelete + \" characters to delete but this is not possible (\"\r\n + firstModifiableCharacterInBuffer + \",\" + minimumLengthOfLookBehind + \")\");\r\n }\r\n }\r\n\r\n /**\r\n * Adjusts the capacity of the buffer.\r\n */\r\n protected void adjustCapacityOfBuffer() {\r\n\r\n // is the current capacity not big enough?\r\n if (characterBuffer.capacity() < requestedNumCharactersInBuffer) {\r\n\r\n // increase the capacity (we delegate to the default behavior of\r\n // StringBuffer)\r\n characterBuffer.ensureCapacity(requestedNumCharactersInBuffer);\r\n\r\n }\r\n\r\n }\r\n\r\n /**\r\n * Reads more characters into the input buffer. This method will block until the buffer is filled with\r\n * {@link #requestedNumCharactersInBuffer} characters , or an I/O error occurs, or the end of the stream is reached.\r\n */\r\n private void fill() throws IOException {\r\n\r\n int length = requestedNumCharactersInBuffer - characterBuffer.length();\r\n if (length <= 0) {\r\n // nothing to do\r\n return;\r\n }\r\n\r\n char[] buffer = new char[length];\r\n int offset = 0;\r\n\r\n while (length > 0) {\r\n\r\n int readChars = delegate.read(buffer, offset, length);\r\n if (readChars != -1) {\r\n characterBuffer.append(buffer, offset, readChars);\r\n offset += readChars;\r\n length -= readChars;\r\n } else {\r\n endOfStreamHit = true;\r\n break;\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n protected void onFaultyModifier(int errorCode, String errorMessage) {\r\n // should we silently ignore any errors and fallback to a meaningful\r\n // behavior? No because a faulty modifier should be fixed by a\r\n // ValidModifier, i.e. the user must take the responsibility for the\r\n // errors and deal with them. Therefore, we throw an exception here.\r\n\r\n // (1) collect the current state of the involved objects\r\n Map<String, Object> description = new HashMap<String, Object>();\r\n\r\n // describe arguments\r\n description.put(\"argument errorCode\", errorCode);\r\n description.put(\"argument errorMessage\", errorMessage);\r\n\r\n // describe reader\r\n description.put(\"this\", this);\r\n\r\n // (2) create an error message\r\n List<String> keys = new ArrayList<String>(description.keySet());\r\n Collections.sort(keys);\r\n StringBuilder sb = new StringBuilder();\r\n for (String key : keys) {\r\n sb.append(\"\\n\" + key + \": \" + description.get(key));\r\n }\r\n\r\n // (3) throw exception\r\n throw new FaultyModifierException(sb.toString(), description);\r\n }\r\n\r\n //\r\n // interface Reader\r\n //\r\n\r\n /**\r\n * TODO more doc\r\n * \r\n * @see java.io.Reader#read(char[], int, int)\r\n */\r\n @Override\r\n public int read(char[] cbuf, int off, int len) throws IOException {\r\n int index = 0;\r\n int read = 0;\r\n while (index < len && (read = readCharacter()) != -1) {\r\n cbuf[off + index] = (char) read;\r\n index++;\r\n }\r\n\r\n if (index == 0 && read == -1) {\r\n return -1;\r\n } else {\r\n return index;\r\n }\r\n }\r\n\r\n /**\r\n * Contract is similar to {@link java.io.Reader#read()}.\r\n * <p>\r\n * TODO more doc\r\n */\r\n protected int readCharacter() throws IOException {\r\n\r\n if (numberOfCharactersToSkip == 0) {\r\n\r\n boolean modifyAgainImmediately = false;\r\n\r\n AfterModification afterModification = null;\r\n do {\r\n\r\n updateBuffer();\r\n\r\n afterModification = modifier.modify(characterBuffer, firstModifiableCharacterInBuffer, endOfStreamHit);\r\n\r\n lastAfterModificationForDebuggingOnly = afterModification;\r\n\r\n // update minimumLengthOfLookBehind\r\n minimumLengthOfLookBehind = afterModification.getNewMinimumLengthOfLookBehind();\r\n if (minimumLengthOfLookBehind > firstModifiableCharacterInBuffer\r\n + afterModification.getNumberOfCharactersToSkip()) {\r\n onFaultyModifier(-11, \"Requested Look Behind\" + \" is impossible because there are not enough \"\r\n + \"characters in the stream.\");\r\n }\r\n\r\n // update requestedNumCharactersInBuffer\r\n requestedNumCharactersInBuffer = minimumLengthOfLookBehind + afterModification.getNewNumberOfChars();\r\n if (requestedNumCharactersInBuffer < minimumLengthOfLookBehind + 1) {\r\n onFaultyModifier(-13, \"Requested Capacity\" + \" is two small because there must at least one\"\r\n + \" unread characters available after the \" + \"look behind characters characters in the\"\r\n + \" stream.\");\r\n }\r\n\r\n modifyAgainImmediately = false;\r\n // do we have to read at least a single character as there is no\r\n // modifiable character left in the character buffer?\r\n if (firstModifiableCharacterInBuffer >= characterBuffer.length() && !endOfStreamHit) {\r\n // yes, we need fresh input ->\r\n modifyAgainImmediately = true;\r\n }\r\n // has the modifier requested a modification at the current\r\n // position?\r\n else if (afterModification.isModifyAgainImmediately()) {\r\n modifyAgainImmediately = true;\r\n }\r\n\r\n } while (modifyAgainImmediately);\r\n\r\n numberOfCharactersToSkip = afterModification.getNumberOfCharactersToSkip();\r\n\r\n if (!afterModification.isModifyAgainImmediately() && numberOfCharactersToSkip == 0 && !endOfStreamHit) {\r\n onFaultyModifier(-16, \"Not a single characters shall be \" + \"skipped but this is not possible of \"\r\n + \"modifyAgain() returns false and the end of \" + \"stream is not reached yet.\");\r\n }\r\n numberOfCharactersToSkip--;\r\n } else {\r\n numberOfCharactersToSkip--;\r\n }\r\n\r\n // is the end of the stream reached?\r\n if (firstModifiableCharacterInBuffer >= characterBuffer.length()) {\r\n // yes -> return -1\r\n return -1;\r\n } else {\r\n // no -> return the next unread character\r\n char result = characterBuffer.charAt(firstModifiableCharacterInBuffer);\r\n\r\n firstModifiableCharacterInBuffer++;\r\n\r\n return result;\r\n }\r\n }\r\n\r\n //\r\n // override Object.*\r\n //\r\n\r\n /**\r\n * @see java.lang.Object#toString()\r\n */\r\n @Override\r\n public String toString() {\r\n StringBuilder builder = new StringBuilder();\r\n builder.append(\"ModifyingReader [\\ncharacterBuffer=\");\r\n builder.append(characterBuffer);\r\n builder.append(\", \\nnextUnreadCharacterInBuffer=\");\r\n builder.append(firstModifiableCharacterInBuffer);\r\n builder.append(\", \\nmodifier=\");\r\n builder.append(modifier);\r\n builder.append(\", \\nminimumLengthOfLookBehind=\");\r\n builder.append(minimumLengthOfLookBehind);\r\n builder.append(\", \\nrequestedCapacityOfCharacterBuffer=\");\r\n builder.append(requestedNumCharactersInBuffer);\r\n builder.append(\", \\nlockedCharacters=\");\r\n builder.append(numberOfCharactersToSkip);\r\n builder.append(\", \\nendOfStreamHit=\");\r\n builder.append(endOfStreamHit);\r\n builder.append(\", \\nlastModificationForDebuggingOnly=\");\r\n builder.append(lastAfterModificationForDebuggingOnly);\r\n builder.append(\"]\");\r\n return builder.toString();\r\n }\r\n\r\n //\r\n // delegating methods\r\n //\r\n\r\n /**\r\n * @see java.io.Reader#close()\r\n */\r\n @Override\r\n public void close() throws IOException {\r\n delegate.close();\r\n }\r\n\r\n // What do I need this delegating method for? As long I don't know I don't\r\n // delegate.\r\n // /**\r\n // * @see java.io.Reader#ready()\r\n // */\r\n // @Override\r\n // public boolean ready() throws IOException {\r\n // return delegate.ready();\r\n // }\r\n\r\n}\r", "public class RegexModifier implements Modifier {\r\n\r\n // * <p>\r\n // * <h2>A summary of the internal algorithm (some details are left\r\n // out)</h2>\r\n // * <p>\r\n // * Is there a match in the buffer?\r\n // * <ul>\r\n // * <li>we found a match\r\n // * <ul>\r\n // * <li>entire buffer matches and end of stream not hit yet -> the match\r\n // might\r\n // * change with more input -> FETCH_MORE_INPUT (<i>match_open</i>)\r\n // * <li>replace the matched content, and then\r\n // * <ul>\r\n // * <li>the match processor decides that no skip is needed yet -> continue\r\n // with\r\n // * the existing buffer content -> try another match\r\n // (<i>match_n_continue</i>)\r\n // * <li>skip needed but no characters left in the buffer after the\r\n // replacement ->\r\n // * MODIFY_AGAIN_IMMEDIATELY is only thing we can do\r\n // (<i>match_n_refill</i>)\r\n // * <li>skip needed and there are characters left in the buffer -> SKIP\r\n // * (<i>match_n_skip</i>)\r\n // * </ul>\r\n // * </ul>\r\n // * <li>we haven't found a match.\r\n // * <ul>\r\n // * <li>By looking for matches (including the empty string) that start in\r\n // the\r\n // * range [from, maxFrom], the end of the buffer is hit.\r\n // * <ul>\r\n // * <li>end of stream hit -> no match possible -> SKIP the entire buffer\r\n // * (<i>nomatch_eos</i>)\r\n // * <li>end of stream not hit -> match might be possible or end of buffer\r\n // is hit\r\n // * -> FETCH_MORE_INPUT cannot be wrong (<i>nomatch_fetch</i>)\r\n // * </ul>\r\n // * <li>We did not match a single character or the empty string -> SKIP the\r\n // * entire buffer (<i>nomatch_skip</i>)\r\n // * </ul>\r\n // * </ul>\r\n\r\n //\r\n // injected\r\n //\r\n\r\n protected ModificationFactory factory;\r\n\r\n protected MatchProcessor matchProcessor;\r\n\r\n /**\r\n * The compiled representation of a regular expression. If the regular expression matches, then a modification shall\r\n * be carried out.\r\n */\r\n protected OnStreamMatcher matcher;\r\n\r\n protected int newNumberOfChars = -1;\r\n\r\n //\r\n // state\r\n //\r\n\r\n /**\r\n * The number of characters that shall be skipped automatically if the modifier is called the next time.\r\n * <p>\r\n * This property is either zero or one (not greater). If this property is one, then the modifier tries to match\r\n * behind the first modifiable character. If this property is zero, then the modifier tries to match before the\r\n * first modifiable character.\r\n */\r\n private int unseenCharactersToSkip = 0;\r\n\r\n //\r\n // constructors\r\n //\r\n\r\n /**\r\n * Only for subclasses.\r\n */\r\n protected RegexModifier() {\r\n super();\r\n }\r\n\r\n /**\r\n * Like {@link RegexModifier#RegexModifier(String, int, String, int, int)} but uses defaults for\r\n * <code>minimumLengthOfLookBehind</code> (1) and <code>newNumberOfChars</code> (2048).\r\n */\r\n public RegexModifier(String regex, int flags, String replacement) {\r\n this(regex, flags, replacement, 1, 2048);\r\n }\r\n\r\n /**\r\n * Creates a modifier that matches a regular expression on character streams and replaces the matches.\r\n * <p>\r\n * This modifier uses {@link OnStreamStandardMatcher} which is not the fastest implementation of\r\n * {@link OnStreamMatcher}. If you want to use a faster matcher, use\r\n * {@link #RegexModifier(OnStreamMatcher, MatchProcessor, int, int)} instead.\r\n * <p>\r\n * A more convenient use of a {@link RegexModifier} is provided by the {@link ModifyingReaderFactory} respectively\r\n * {@link ModifyingWriterFactory}.\r\n * \r\n * @param regex\r\n * the regular expression that describe the text that shall be replaced. See\r\n * {@link Pattern#compile(String, int)}.\r\n * @param flags\r\n * the flags that are to use when the regex is applied on the character stream. See\r\n * {@link Pattern#compile(String, int)}.\r\n * @param replacement\r\n * the replacement for the text that is matched via <code>regex</code>. See\r\n * {@link Matcher#appendReplacement(StringBuffer, String)}.\r\n * @param minimumLengthOfLookBehind\r\n * See {@link RegexModifier#RegexModifier(OnStreamMatcher, MatchProcessor, int, int)} .\r\n * @param newNumberOfChars\r\n * See {@link RegexModifier#RegexModifier(OnStreamMatcher, MatchProcessor, int, int)} .\r\n */\r\n public RegexModifier(String regex, int flags, String replacement, int minimumLengthOfLookBehind,\r\n int newNumberOfChars) {\r\n this(regex, flags, new ReplacingProcessor(replacement), minimumLengthOfLookBehind, newNumberOfChars);\r\n }\r\n\r\n /**\r\n * See {@link #RegexModifier(String, int, String, int, int)}.\r\n */\r\n public RegexModifier(String regex, int flags, MatchProcessor matchProcessor, int minimumLengthOfLookBehind,\r\n int newNumberOfChars) {\r\n\r\n Matcher jdkMatcher = Pattern.compile(regex, flags).matcher(\"\");\r\n jdkMatcher.useTransparentBounds(true);\r\n jdkMatcher.useAnchoringBounds(false);\r\n init(new OnStreamStandardMatcher(jdkMatcher), matchProcessor, minimumLengthOfLookBehind, newNumberOfChars);\r\n }\r\n\r\n /**\r\n * Creates a modifier that matches a regular expression on character streams and does 'something' if matches are\r\n * found.\r\n * <p>\r\n * \r\n * @param matcher\r\n * Matches a regular expression on a <code>CharSequence</code>.\r\n * @param matchProcessor\r\n * Defines what to do if the regular expression matches some text in the stream.\r\n * @param minimumLengthOfLookBehind\r\n * See {@link AfterModification#getNewMinimumLengthOfLookBehind()}.\r\n * @param newNumberOfChars\r\n * See {@link AfterModification#getNewNumberOfChars()}. This should not be smaller than the length of the\r\n * characters sequence the pattern needs to match properly. In case you want to match more than once, the\r\n * value should be higher.\r\n */\r\n public RegexModifier(OnStreamMatcher matcher, MatchProcessor matchProcessor, int minimumLengthOfLookBehind,\r\n int newNumberOfChars) {\r\n\r\n init(matcher, matchProcessor, minimumLengthOfLookBehind, newNumberOfChars);\r\n }\r\n\r\n @SuppressWarnings(\"hiding\")\r\n protected void init(OnStreamMatcher matcher, MatchProcessor matchProcessor, int minimumLengthOfLookBehind,\r\n int newNumberOfChars) {\r\n\r\n this.factory = new ModificationFactory(minimumLengthOfLookBehind, newNumberOfChars);\r\n this.matchProcessor = matchProcessor;\r\n this.matcher = matcher;\r\n this.newNumberOfChars = newNumberOfChars;\r\n }\r\n\r\n //\r\n // interface Modifier\r\n //\r\n\r\n /**\r\n * @see com.github.rwitzel.streamflyer.core.Modifier#modify(java.lang.StringBuilder, int, boolean)\r\n */\r\n @Override\r\n public AfterModification modify(StringBuilder characterBuffer, int firstModifiableCharacterInBuffer,\r\n boolean endOfStreamHit) {\r\n\r\n // the first position we will match from.\r\n Integer minFrom = null;\r\n\r\n while (true) {\r\n\r\n // determine the range [minFrom, maxFrom] that will contain the\r\n // first character of the matching string\r\n\r\n if (minFrom == null) {\r\n minFrom = firstModifiableCharacterInBuffer;\r\n\r\n if (unseenCharactersToSkip > 0) {\r\n\r\n // is there at least one modifiable character in the buffer?\r\n if (minFrom + unseenCharactersToSkip > characterBuffer.length()) {\r\n // no -> we need more input to skip the characters\r\n\r\n if (endOfStreamHit) {\r\n // -> stop\r\n return factory.stop(characterBuffer, firstModifiableCharacterInBuffer, endOfStreamHit);\r\n } else {\r\n // -> fetch more input\r\n return factory.fetchMoreInput(0, characterBuffer, firstModifiableCharacterInBuffer,\r\n endOfStreamHit);\r\n }\r\n\r\n } else {\r\n // yes -> increase the *minFrom*\r\n minFrom += unseenCharactersToSkip;\r\n unseenCharactersToSkip = 0;\r\n }\r\n }\r\n }\r\n\r\n // we have to restrict maxFrom in order to prevent that the\r\n // requested number of characters increases more and more\r\n int maxFrom = firstModifiableCharacterInBuffer + newNumberOfChars;\r\n\r\n // adjust maxFrom if it is bigger than the given buffer\r\n if (maxFrom > characterBuffer.length()) {\r\n // this is NOT set to characterBuffer.length() -1 by intention\r\n // as a regular expression might match on the zero length string\r\n // (but with positive look-behind)!\r\n maxFrom = characterBuffer.length();\r\n }\r\n\r\n // find first match\r\n // (as the match processor might have modified the buffer, we reset\r\n // the matcher inside the loop instead of outside of the loop)\r\n matcher.reset(characterBuffer);\r\n boolean matchFound = matcher.findUnlessHitEnd(minFrom, maxFrom);\r\n\r\n if (matchFound) {\r\n // we found a match\r\n\r\n // could change this positive match into a negative one\r\n // (matcher.requireEnd()) or into a longer one (greedy\r\n // operator)?\r\n if (matcher.hitEnd() && !endOfStreamHit) {\r\n // (match_open) yes, it could -> we need more input\r\n\r\n int numberOfCharactersToSkip = matcher.lastFrom() - firstModifiableCharacterInBuffer;\r\n\r\n // read more input (skip some characters if possible)\r\n AfterModification mod = factory.fetchMoreInput(numberOfCharactersToSkip, characterBuffer,\r\n firstModifiableCharacterInBuffer, endOfStreamHit);\r\n\r\n assert __checkpoint( //\r\n \"name\", \"match_open\", //\r\n \"minLen\", firstModifiableCharacterInBuffer, //\r\n \"characterBuffer\", characterBuffer, //\r\n \"endOfStreamHit\", endOfStreamHit, //\r\n \"afterModification\", mod);\r\n\r\n return mod;\r\n } else {\r\n // no -> thus we can use this match -> process the match\r\n\r\n // process the match\r\n MatchResult matchResult = matcher; // .toMatchResult()?\r\n // (I could pass firstModifiableCharacterInBuffer instead of\r\n // minFrom as well)\r\n MatchProcessorResult matchProcessorResult = matchProcessor.process(characterBuffer, minFrom,\r\n matchResult);\r\n minFrom = matchProcessorResult.getFirstModifiableCharacterInBuffer();\r\n\r\n // match again without skip? (even for minFrom == maxFrom we\r\n // try a match) (minFrom <= maxFrom is needed so that the\r\n // buffer does not increase if the replacement is longer\r\n // than the replaced string, i.e. minFrom > maxFrom means\r\n // that a SKIP is needed)\r\n // (I (rwoo) think an earlier SKIP (minFrom < maxFrom\r\n // instead of minFrom <= maxFrom) would also be possible.\r\n // This has no impact on the matching and only minimal\r\n // impact on the performance)\r\n if (minFrom <= maxFrom && matchProcessorResult.isContinueMatching()) {\r\n // (match_n_continue) no skip needed yet -> continue\r\n // matching on the existing buffer content\r\n\r\n assert __checkpoint( //\r\n \"name\", \"match_n_continue\", //\r\n \"minLen\", firstModifiableCharacterInBuffer, //\r\n \"characterBuffer\", characterBuffer, //\r\n \"endOfStreamHit\", endOfStreamHit, //\r\n \"minFrom\", minFrom);\r\n\r\n // We try the next match on the modified input, i.e.\r\n // not match only once -> next loop\r\n continue;\r\n } else {\r\n\r\n // we shall not continue matching on the\r\n // existing buffer content but skip (keep the buffer\r\n // small)\r\n\r\n int numberOfCharactersToSkip;\r\n if (minFrom > characterBuffer.length()) {\r\n // this happens when we avoid endless loops after\r\n // we matched an empty string\r\n unseenCharactersToSkip = minFrom - characterBuffer.length();\r\n ZzzAssert.isTrue(unseenCharactersToSkip == 1, \"unseenCharactersToSkip must be one but was \"\r\n + unseenCharactersToSkip);\r\n numberOfCharactersToSkip = characterBuffer.length() - firstModifiableCharacterInBuffer;\r\n } else {\r\n numberOfCharactersToSkip = minFrom - firstModifiableCharacterInBuffer;\r\n }\r\n\r\n if (numberOfCharactersToSkip == 0) {\r\n\r\n // (match_n_refill) there are no characters left in\r\n // the buffer after the replacement ->\r\n // MODIFY_AGAIN_IMMEDIATELY is only thing we can do\r\n // (the match processor implementation must not\r\n // cause an endless loop)\r\n\r\n // (passing false for endOfStreamHit is ugly!!!)\r\n // we should offer a new method in\r\n // ModificationFactory, something like\r\n // continueAfterModification(...) that chooses the\r\n // appropriate action. the following code is always\r\n // a MODIFY_AGAIN_IMMEDIATELY\r\n AfterModification mod = factory.fetchMoreInput(numberOfCharactersToSkip, characterBuffer,\r\n firstModifiableCharacterInBuffer, false);\r\n\r\n assert __checkpoint( //\r\n \"name\", \"match_n_refill\", //\r\n \"minLen\", firstModifiableCharacterInBuffer, //\r\n \"characterBuffer\", characterBuffer, //\r\n \"endOfStreamHit\", endOfStreamHit, //\r\n \"afterModification\", mod);\r\n\r\n return mod;\r\n } else {\r\n // (match_n_skip) there are characters left in\r\n // the buffer -> SKIP\r\n\r\n AfterModification mod = factory.skipOrStop(numberOfCharactersToSkip, characterBuffer,\r\n firstModifiableCharacterInBuffer, endOfStreamHit);\r\n\r\n assert __checkpoint( //\r\n \"name\", \"match_n_skip\", //\r\n \"minLen\", firstModifiableCharacterInBuffer, //\r\n \"characterBuffer\", characterBuffer, //\r\n \"endOfStreamHit\", endOfStreamHit, //\r\n \"afterModification\", mod);\r\n\r\n return mod;\r\n }\r\n }\r\n\r\n }\r\n } else {\r\n // we haven't found a match\r\n\r\n // By looking for matches (including the empty string) that\r\n // start in the range [from, maxFrom], is the end of the buffer\r\n // hit?\r\n if (matcher.lastFrom() <= maxFrom) {\r\n // yes, the end of the buffer was hit\r\n\r\n // can we get more input?\r\n if (endOfStreamHit) {\r\n // (nomatch_eos) no, in the entire stream we will not\r\n // found more matches that start in range [from,\r\n // maxFrom] -> skip the characters from range [from,\r\n // maxFrom]\r\n\r\n int numberOfCharactersToSkip = maxFrom - firstModifiableCharacterInBuffer;\r\n AfterModification mod = factory.skipOrStop(numberOfCharactersToSkip, characterBuffer,\r\n firstModifiableCharacterInBuffer, endOfStreamHit);\r\n\r\n assert __checkpoint( //\r\n \"name\", \"nomatch_eos\", //\r\n \"minLen\", firstModifiableCharacterInBuffer, //\r\n \"characterBuffer\", characterBuffer, //\r\n \"endOfStreamHit\", endOfStreamHit, //\r\n \"afterModification\", mod);\r\n\r\n return mod;\r\n\r\n } else {\r\n // (nomatch_fetch) yes > we should fetch more input\r\n // (because end of stream is not hit yet)\r\n\r\n // if maxFrom == characterBuffer.length() and lastFrom()\r\n // == maxFrom we cannot decide whether this is really an\r\n // open match or rather a not a match at all. But by\r\n // skipping the characters in front of lastFrom() and\r\n // fetching more input we cannot do anything wrong\r\n\r\n int numberOfCharactersToSkip = matcher.lastFrom() - firstModifiableCharacterInBuffer;\r\n AfterModification mod = factory.fetchMoreInput(numberOfCharactersToSkip, characterBuffer,\r\n firstModifiableCharacterInBuffer, endOfStreamHit);\r\n\r\n assert __checkpoint( //\r\n \"name\", \"nomatch_fetch\", //\r\n \"minLen\", firstModifiableCharacterInBuffer, //\r\n \"characterBuffer\", characterBuffer, //\r\n \"endOfStreamHit\", endOfStreamHit, //\r\n \"afterModification\", mod);\r\n\r\n return mod;\r\n }\r\n\r\n } else { // matcher.lastFrom() == maxFrom + 1\r\n\r\n // (nomatch_skip) no, we are matching not a single character\r\n\r\n // -> skip the characters from range [from, maxFrom]\r\n int numberOfCharactersToSkip = maxFrom - firstModifiableCharacterInBuffer;\r\n AfterModification mod = factory.skipOrStop(numberOfCharactersToSkip, characterBuffer,\r\n firstModifiableCharacterInBuffer, endOfStreamHit);\r\n\r\n assert __checkpoint( //\r\n \"name\", \"nomatch_skip\", //\r\n \"minLen\", firstModifiableCharacterInBuffer, //\r\n \"characterBuffer\", characterBuffer, //\r\n \"endOfStreamHit\", endOfStreamHit, //\r\n \"afterModification\", mod);\r\n\r\n return mod;\r\n }\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * This method is called if a certain line of code is reached (\"checkpoint\").\r\n * <p>\r\n * This method should be called only if the modifier is tested. Otherwise you might experience performance\r\n * penalties.\r\n * \r\n * @param checkpointDescription\r\n * A list of objects describing the checkpoint. The objects should be given as name-value-pairs.\r\n * @return Returns true. This allows you to use this method as side-effect in Java assertions.\r\n */\r\n protected boolean __checkpoint(Object... checkpointDescription) {\r\n // nothing to do here\r\n return true;\r\n }\r\n\r\n //\r\n // override Object.*\r\n //\r\n\r\n /**\r\n * @see java.lang.Object#toString()\r\n */\r\n @Override\r\n public String toString() {\r\n StringBuilder builder = new StringBuilder();\r\n builder.append(\"RegexModifier [\\nfactory=\");\r\n builder.append(factory);\r\n builder.append(\", \\nreplacement=\");\r\n builder.append(matchProcessor);\r\n builder.append(\", \\nmatcher=\");\r\n builder.append(matcher);\r\n builder.append(\", \\nnewNumberOfChars=\");\r\n builder.append(newNumberOfChars);\r\n builder.append(\"]\");\r\n return builder.toString();\r\n }\r\n\r\n //\r\n // injected\r\n //\r\n\r\n /**\r\n * @param matchProcessor\r\n * The {@link #matchProcessor} to set.\r\n */\r\n public void setMatchProcessor(MatchProcessor matchProcessor) {\r\n this.matchProcessor = matchProcessor;\r\n }\r\n\r\n}\r", "public class Token {\r\n\r\n /**\r\n * An ID for the token. The ID shall be unique among all tokens used with the {@link TokenProcessor}. Immutable.\r\n */\r\n private String name;\r\n\r\n /**\r\n * This regular expression describes how a token can be matched. Flags should be embedded via\r\n * {@link EmbeddedFlagUtil}. Immutable.\r\n */\r\n private String regex;\r\n\r\n /**\r\n * The number of capturing groups that are contained in the {@link #regex}. Immutable.\r\n * <p>\r\n * Calculated from {@link #regex} and saved here to improve the performance of a {@link TokenProcessor}.\r\n */\r\n private int capturingGroupCount;\r\n\r\n /**\r\n * This object processes the match if the token is matched.\r\n */\r\n private MatchProcessor matchProcessor;\r\n\r\n /**\r\n * This constructor should be used only in tests!\r\n * \r\n * @param regex\r\n * The regex describes how a token can be matched. Embed flags via {@link EmbeddedFlagUtil}.\r\n */\r\n public Token(String regex) {\r\n this(\"\" + System.currentTimeMillis(), regex, new DoNothingProcessor());\r\n }\r\n\r\n /**\r\n * This token matches the given regex but the match processor does {@link DoNothingProcessor nothing}.\r\n * \r\n * @param name\r\n * See {@link #name}.\r\n * @param regex\r\n * The regex describes how a token can be matched. Embed flags via {@link EmbeddedFlagUtil}.\r\n */\r\n public Token(String name, String regex) {\r\n this(name, regex, new DoNothingProcessor());\r\n }\r\n\r\n /**\r\n * This token matches the given regex and {@link ReplacingProcessor replaces} the match with the replacement.\r\n * \r\n * @param name\r\n * See {@link #name}.\r\n * @param regex\r\n * The regex describes how a token can be matched. Embed flags via {@link EmbeddedFlagUtil}.\r\n * @param replacement\r\n */\r\n public Token(String name, String regex, String replacement) {\r\n this(name, regex, new ReplacingProcessor(replacement));\r\n }\r\n\r\n /**\r\n * This token matches the given regex and the match will be processed with the given {@link MatchProcessor}.\r\n * \r\n * @param name\r\n * See {@link #name}\r\n * @param regex\r\n * The regex describes how a token can be matched. Embed flags via {@link EmbeddedFlagUtil}.\r\n * @param matchProcessor\r\n */\r\n public Token(String name, String regex, MatchProcessor matchProcessor) {\r\n super();\r\n\r\n ZzzValidate.notNull(matchProcessor, \"matchProcessor must not be null\");\r\n\r\n this.name = name;\r\n this.regex = regex;\r\n this.matchProcessor = matchProcessor;\r\n this.capturingGroupCount = Pattern.compile(regex).matcher(\"\").groupCount();\r\n }\r\n\r\n public String getName() {\r\n return name;\r\n }\r\n\r\n public String getRegex() {\r\n return regex;\r\n }\r\n\r\n public int getCapturingGroupCount() {\r\n return capturingGroupCount;\r\n }\r\n\r\n public MatchProcessor getMatchProcessor() {\r\n return matchProcessor;\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return \"Token [name=\" + name + \", regex=\" + regex + \", capturingGroupCount=\" + capturingGroupCount\r\n + \", matchProcessor=\" + matchProcessor + \"]\";\r\n }\r\n\r\n}\r", "public class TokenProcessor implements MatchProcessor {\r\n\r\n /**\r\n * The tokens to process.\r\n */\r\n private List<Token> tokens;\r\n\r\n public TokenProcessor(List<Token> tokens) {\r\n super();\r\n\r\n ZzzValidate.isNotEmpty(tokens, \"tokens\");\r\n\r\n this.tokens = tokens;\r\n }\r\n\r\n @Override\r\n public MatchProcessorResult process(StringBuilder characterBuffer, int firstModifiableCharacterInBuffer,\r\n MatchResult matchResult) {\r\n\r\n // find out which token is matched\r\n int groupOffset = 1;\r\n for (Token token : tokens) {\r\n int groupsInToken = token.getCapturingGroupCount();\r\n\r\n String matchedGroup = matchResult.group(groupOffset);\r\n if (matchedGroup != null) {\r\n // this token is matched! -> process this token + return the result\r\n return processToken(token, characterBuffer, firstModifiableCharacterInBuffer,\r\n new MatchResultWithOffset(matchResult, groupOffset));\r\n }\r\n\r\n groupOffset += groupsInToken + 1;\r\n }\r\n\r\n throw new RuntimeException(\"never to happen if used with \" + TokensMatcher.class);\r\n }\r\n\r\n /**\r\n * Processes the matched token using {@link Token#getMatchProcessor()}. The token can be found in the match result\r\n * at the given group offset.\r\n */\r\n protected MatchProcessorResult processToken(Token token, StringBuilder characterBuffer,\r\n int firstModifiableCharacterInBuffer, MatchResult matchResult) {\r\n\r\n return token.getMatchProcessor().process(characterBuffer, firstModifiableCharacterInBuffer, matchResult);\r\n }\r\n\r\n}\r", "public class TokensMatcher extends DelegatingMatcher {\r\n\r\n /**\r\n * This constructor is only for unit tests.\r\n */\r\n public TokensMatcher() {\r\n super();\r\n }\r\n\r\n public TokensMatcher(List<Token> tokens) {\r\n super();\r\n setDelegate(createMatcher(createRegexThatMatchesAnyToken(tokens)));\r\n }\r\n\r\n /**\r\n * @return Returns a regular expression that matches all tokens.\r\n */\r\n String createRegexThatMatchesAnyToken(List<Token> tokens) {\r\n String regex = null;\r\n for (Token token : tokens) {\r\n if (regex == null) {\r\n regex = \"(\" + token.getRegex() + \")\";\r\n } else {\r\n regex = regex + \"|(\" + token.getRegex() + \")\";\r\n }\r\n }\r\n return regex;\r\n }\r\n\r\n /**\r\n * @return Returns the matcher that can be used with a {@link RegexModifier} to match an alternative of tokens\r\n */\r\n protected OnStreamMatcher createMatcher(String regexTokenAlternatives) {\r\n // use the default implementation\r\n Matcher matcher = Pattern.compile(regexTokenAlternatives, 0).matcher(\"\");\r\n matcher.useTransparentBounds(true);\r\n matcher.useAnchoringBounds(false);\r\n return new OnStreamStandardMatcher(matcher);\r\n }\r\n\r\n}\r" ]
import com.github.rwitzel.streamflyer.regex.addons.tokens.TokensMatcher; import static org.junit.Assert.assertEquals; import java.io.Reader; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.IOUtils; import org.junit.Test; import com.github.rwitzel.streamflyer.core.Modifier; import com.github.rwitzel.streamflyer.core.ModifyingReader; import com.github.rwitzel.streamflyer.regex.RegexModifier; import com.github.rwitzel.streamflyer.regex.addons.tokens.Token; import com.github.rwitzel.streamflyer.regex.addons.tokens.TokenProcessor;
/** * Copyright (C) 2011 [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.rwitzel.streamflyer.regex.addons.tokens; /** * Tests {@link MyTokenProcessor} and {@link TokenProcessor}. * * @author rwoo * */ public class MyTokenProcessorTest { /** * Rather an integration test than a unit test. * * @throws Exception */ @Test public void testProcess() throws Exception { // +++ define the tokens we are looking for
List<Token> tokenList = new ArrayList<Token>();
3
debdattabasu/RoboMVVM
library/src/main/java/org/dbasu/robomvvm/viewmodel/ViewModel.java
[ "public enum BindMode {\n\n /**\n * Makes a one-way binding where the target property is set whenever the source property changes.\n */\n SOURCE_TO_TARGET(true, false),\n\n /**\n * Makes a one-way binding where the source property is set whenever the target property changes.\n */\n TARGET_TO_SOURCE(false, true),\n\n /**\n * Makes a two-way binding that keeps the source property and target property in complete sync.\n */\n BIDIRECTIONAL(true, true);\n\n\n /**\n * Returns whether this bind mode can bind the source property to the target property.\n * @return\n * Returns true for {@link #SOURCE_TO_TARGET} and {@link #BIDIRECTIONAL}.\n */\n public boolean canBindSourceToTarget() {\n return sourceToTarget;\n }\n\n /**\n * Returns whether this bind mode can bind the target property to the source property.\n * @return\n * Returns true for {@link #TARGET_TO_SOURCE} and {@link #BIDIRECTIONAL}.\n */\n public boolean canBindTargetToSource() {\n return targetToSource;\n }\n\n private boolean sourceToTarget, targetToSource;\n\n BindMode(boolean sourceToTarget, boolean targetToSource) {\n this.sourceToTarget = sourceToTarget;\n this.targetToSource = targetToSource;\n\n }\n}", "public class Binding {\n\n /**\n * Binds an event in the source component to an action in the target component. When an event of type eventType\n * is raised by the source component, {@link org.dbasu.robomvvm.componentmodel.Component#invokeAction} is called\n * on the target component.\n *\n * @param source\n * The source component.\n * @param target\n * The target component.\n * @param eventType\n * The event type in the source component that triggers the action.\n * @param action\n * The action method name in the target component. The action method may take an argument of the supplied\n * eventType, or may take no arguments.\n * @return\n * The binding created by this call.\n */\n public static Binding bindAction(Component source, Component target, Class<? extends EventArg> eventType, String action) {\n\n Preconditions.checkNotNull(source);\n Preconditions.checkNotNull(target);\n Preconditions.checkNotNull(eventType);\n Preconditions.checkNotNull(action);\n\n Binding ret = new ActionBinding(source, target, eventType, action);\n ret.bind();\n return ret;\n\n }\n\n\n /**\n * Binds a property in the source component to a property in the target component. The directionality of the binding is specified\n * using {@link org.dbasu.robomvvm.binding.BindMode}, and conversions between the source value and the target value are carried\n * out using a {@link org.dbasu.robomvvm.binding.ValueConverter}.\n *\n * @param source\n * The source component.\n * @param sourceProperty\n * The source property name.\n * @param target\n * The target component.\n * @param targetProperty\n * The target property name.\n * @param valueConverter\n * The value converter to convert between source and target properties.\n * @param bindMode\n * The bind mode to be used for this binding.\n * @return\n * The binding created by this call.\n */\n\n public static Binding bindProperty(Component source, String sourceProperty, Component target, String targetProperty, ValueConverter valueConverter, BindMode bindMode) {\n\n Preconditions.checkNotNull(source);\n Preconditions.checkNotNull(sourceProperty);\n Preconditions.checkNotNull(target);\n Preconditions.checkNotNull(targetProperty);\n Preconditions.checkNotNull(valueConverter);\n Preconditions.checkNotNull(bindMode);\n\n Binding ret = new PropertyBinding(source, sourceProperty, target, targetProperty, valueConverter, bindMode);\n ret.bind();\n return ret;\n }\n\n /**\n * Binds a property in the source component to a property in the target component. Changes to the source property\n * are reflected in the target property, but not the other way round. This corresponds to\n * {@link org.dbasu.robomvvm.binding.BindMode#SOURCE_TO_TARGET}. A {@link org.dbasu.robomvvm.binding.DefaultValueConverter} is used.\n *\n * @param source\n * The source component.\n * @param sourceProperty\n * The source property name.\n * @param target\n * The target component.\n * @param targetProperty\n * The target property name.\n * @return\n * The binding created by this call.\n */\n\n public static Binding bindProperty(Component source, String sourceProperty, Component target, String targetProperty) {\n\n return bindProperty(source, sourceProperty, target, targetProperty, new DefaultValueConverter(), BindMode.SOURCE_TO_TARGET);\n\n }\n\n /**\n * Binds a property in the source component to a property in the target component. The directionality of the binding is specified\n * using {@link org.dbasu.robomvvm.binding.BindMode}. No conversions between the source and the target values is\n * performed.\n *\n * @param source\n * The source component.\n * @param sourceProperty\n * The source property name.\n * @param target\n * The target component.\n * @param targetProperty\n * The target property name.\n * @param bindMode\n * The bind mode to be used for this binding.\n * @return\n * The binding created by this call.\n */\n\n public static Binding bindProperty(Component source, String sourceProperty, Component target, String targetProperty, BindMode bindMode) {\n\n return bindProperty(source, sourceProperty, target, targetProperty, new DefaultValueConverter(), bindMode);\n\n }\n\n /**\n * Unbind this binding. This method is automatically\n * called when the source or the target component is garbage collected.\n */\n public void unbind() {\n Component source = getSource();\n Component target = getTarget();\n\n if(source != null) {\n source.removeEventListener(garbageCollectionListener);\n }\n\n if(target != null) {\n target.removeEventListener(garbageCollectionListener);\n }\n\n bound = false;\n }\n\n /**\n * Returns whether the binding is currently bound.\n * @return\n * True is the binding is currently bound. False otherwise.\n */\n public boolean isBound() {\n return bound;\n }\n\n /**\n * Gets the source component\n * @return\n * The source component.\n */\n public Component getSource() {\n return weakSourceReference.get();\n }\n\n /**\n * Gets the target component\n * @return\n * The target Component.\n */\n public Component getTarget() {\n return weakTargetReference.get();\n }\n\n private final WeakReference<Component> weakSourceReference;\n private final WeakReference<Component> weakTargetReference;\n\n private final EventListener garbageCollectionListener = new EventListener(GarbageCollectionEventArg.class) {\n @Override\n public void invoke(EventArg args) {\n unbind();\n }\n };\n\n private boolean bound = false;\n\n protected Binding(Component source, Component target) {\n this.weakSourceReference = new WeakReference<Component>(source);\n this.weakTargetReference = new WeakReference<Component>(target);\n\n }\n\n protected void bind() {\n\n Component source = getSource();\n Component target = getTarget();\n\n if(source != null) {\n source.addEventListener(garbageCollectionListener);\n }\n\n if(target != null) {\n target.addEventListener(garbageCollectionListener);\n }\n bound = true;\n }\n}", "public interface ValueConverter {\n\n /**\n * Converts a source value into a target value. This is called whenever a source\n * property's value is being applied to the target property in a binding.\n *\n * @param value\n * The value of the source property.\n * @return\n * The value to apply to the target.\n */\n public Object convertToTarget(Object value);\n\n\n /**\n * Converts a target value into a source value. This is called whenever a target\n * property's value is being applied to the source property in a binding.\n *\n * @param value\n * The value of the source property.\n * @return\n * The value to apply to the target.\n */\n public Object convertToSource(Object value);\n}", "public class ComponentAdapter extends Component {\n\n private static final String COMPONENT_ADAPTER = \"robomvvm_component_adapter\";\n\n /**\n * Can make associations between arbitrary classes and the {@link ComponentAdapter} subclasses that are used to make\n * components out of them.\n */\n public static class Associations {\n\n static {\n adapterTypes = new HashMap<Class<?>, Class<? extends ComponentAdapter>>();\n set(MenuItem.class, MenuItemAdapter.class);\n set(View.class, ViewAdapter.class);\n set(ImageView.class, ImageViewAdapter.class);\n set(TextView.class, TextViewAdapter.class);\n set(EditText.class, EditTextViewAdapter.class);\n set(CompoundButton.class, CompoundButtonViewAdapter.class);\n set(ProgressBar.class, ProgressBarViewAdapter.class);\n set(SeekBar.class, SeekBarViewAdapter.class);\n set(RatingBar.class, RatingBarViewAdapter.class);\n set(AdapterView.class, AdapterViewAdapter.class);\n set(ListView.class, ListViewAdapter.class);\n }\n\n private static final Map<Class<?>, Class<? extends ComponentAdapter>> adapterTypes;\n\n /**\n * Get the associated component adapter class associated with a class. If no\n * component adapter class is associated with the supplied class, then its super classes and interfaces\n * are searched until a component adapter association is found.\n * @param objectType\n * The class of the object to find associations for.\n * @return\n * The associated component adapter class, or null if none is found.\n */\n public synchronized static Class<? extends ComponentAdapter> get(Class<?> objectType) {\n Preconditions.checkNotNull(objectType);\n\n Class<? extends ComponentAdapter> adapterType = null;\n\n Class<?> myObjectType = objectType;\n\n List<Class<?>> reachableObjectTypes = new ArrayList<Class<?>>();\n\n while (myObjectType!= null) {\n\n reachableObjectTypes.add(myObjectType);\n reachableObjectTypes.addAll(Arrays.asList(myObjectType.getInterfaces()));\n\n myObjectType = myObjectType.getSuperclass();\n }\n\n for(Class<?> klazz : reachableObjectTypes) {\n adapterType = adapterTypes.get(klazz);\n if(adapterType != null) return adapterType;\n\n }\n\n return null;\n }\n\n\n /**\n * Associates a component adapter class with an arbitrary class.\n * @param objectType\n * The class to make the association for. If an association already exists for this class, then it is overwritten.\n * @param adapterType\n * The component adapter class to associate with the supplied class.\n * If this is null, then any existing association of the supplied class is removed.\n */\n public synchronized static void set(Class<?> objectType, Class<? extends ComponentAdapter> adapterType) {\n Preconditions.checkNotNull(objectType);\n\n if(adapterType != null) {\n adapterTypes.put(objectType, adapterType);\n }\n else {\n adapterTypes.remove(objectType);\n }\n }\n }\n\n\n /**\n * Create or retrieve the component adapter for the supplied object. Once created, the component adapter is stored as a tag\n * on the supplied object using {@link org.dbasu.robomvvm.util.ObjectTagger}, which stores weak references to the supplied object to\n * allow for Garbage Collection. Any component adapter associated with an object that has been garbage collected is not stored\n * internally by the library.\n *\n * @param targetObject\n * The object to get the component adapter for.\n * @return\n * The component adapter for the supplied object.\n *\n * @throws java.lang.RuntimeException\n * When no component adapter class is associated with\n * the class of the supplied object.\n */\n public synchronized static ComponentAdapter get(Object targetObject) {\n Preconditions.checkNotNull(targetObject);\n\n ComponentAdapter componentAdapter = (ComponentAdapter) ObjectTagger.getTag(targetObject, COMPONENT_ADAPTER);\n if (componentAdapter != null) return componentAdapter;\n\n Class<? extends ComponentAdapter> adapterType = Associations.get(targetObject.getClass());\n\n if(adapterType == null) {\n\n throw new RuntimeException(\"No ComponentAdapter Subclass Associated With \" + targetObject.getClass().getName() +\n \". Call ComponentAdapter.Associations.set(Class<?> objectType, Class<? extends ComponentAdapter> adapterType) \" +\n \"To Make The Association.\");\n }\n\n try {\n componentAdapter = adapterType.newInstance();\n\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n\n componentAdapter.init(targetObject);\n\n ObjectTagger.setTag(targetObject, COMPONENT_ADAPTER, componentAdapter);\n\n return componentAdapter;\n }\n\n protected Object targetObject;\n\n protected ComponentAdapter() {\n\n }\n\n /**\n * Gets the target object of this component adapter.\n * @return\n * Returns the target object.\n */\n public Object getTargetObject() {\n return targetObject;\n }\n\n private void init(Object targetObject) {\n this.targetObject = targetObject;\n adapt();\n\n }\n\n /**\n * Call this function in subclasses to set up the component adapter.\n */\n protected void adapt() {\n\n }\n}", "public class EventArg {\n\n private final Component source;\n\n /**\n * Construct an Event Arg for a source component.\n * @param source\n * The source component that raises this event.\n */\n public EventArg(Component source) {\n this.source = Preconditions.checkNotNull(source);;\n }\n\n /**\n * Get the source component that raised this event.\n * @return\n * The source component.\n */\n Component getSource() {\n return source;\n }\n\n}", "public class ObjectTagger {\n\n private static class Tag {\n\n private HashMap<String, Object> tags = new HashMap<String, Object>();\n\n void addTag(String key, Object value) {\n tags.put(key, value);\n }\n\n Object removeTag(String key) {\n return tags.remove(key);\n }\n\n Object get(String key) {\n return tags.get(key);\n }\n\n boolean isEmpty() {\n return tags.isEmpty();\n }\n }\n\n private static WeakHashMap<Object, Tag> tagMap = new WeakHashMap<Object, Tag>();\n\n /**\n * Set a tag associated with an object.\n * @param object\n * The object to set the tag for.\n * @param key\n * The {@link java.lang.String} index for the tag.\n * @param value\n * The actual tag.\n */\n public static synchronized void setTag(Object object, String key, Object value) {\n\n Tag tag = tagMap.get(object);\n\n if(tag == null) {\n tag = new Tag();\n tagMap.put(object, tag);\n }\n\n tag.addTag(key, value);\n }\n\n /**\n * Removes a tag associated with an object.\n * @param object\n * The object to remove the tag from.\n * @param key\n * The {@link java.lang.String} index of the tag to remove.\n * @return\n * The tag that has been removed. Null if no such tag exists.\n */\n public static synchronized Object removeTag(Object object, String key) {\n Tag tag = tagMap.get(object);\n\n if(tag == null) {\n return null;\n }\n\n Object ret = tag.removeTag(key);\n\n if(tag.isEmpty()) {\n tagMap.remove(object);\n }\n\n return ret;\n }\n\n /**\n * Gets a tag associated with an object.\n * @param object\n * The object to get the tag of.\n * @param key\n * The {@link java.lang.String} index of the tag to get.\n * @return\n * The associated tag. Null if no such tag exists.\n */\n public static synchronized Object getTag(Object object, String key) {\n Tag tag = tagMap.get(object);\n\n if(tag == null) {\n return null;\n }\n\n return tag.get(key);\n }\n}", "public class ThreadUtil {\n\n /**\n * Checks whether the current thread is the UI thread.\n * @return\n * True if the current thread is the UI thread. False otherwise.\n */\n public static boolean isUiThread() {\n return Looper.getMainLooper().getThread().equals(Thread.currentThread());\n }\n}" ]
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.google.common.base.Preconditions; import org.dbasu.robomvvm.binding.BindMode; import org.dbasu.robomvvm.binding.Binding; import org.dbasu.robomvvm.binding.ValueConverter; import org.dbasu.robomvvm.componentmodel.ComponentAdapter; import org.dbasu.robomvvm.componentmodel.EventArg; import org.dbasu.robomvvm.util.ObjectTagger; import org.dbasu.robomvvm.util.ThreadUtil; import java.util.ArrayList; import java.util.List;
/** * @project RoboMVVM * @project RoboMVVM(https://github.com/debdattabasu/RoboMVVM) * @author Debdatta Basu * * @license 3-clause BSD license(http://opensource.org/licenses/BSD-3-Clause). * Copyright (c) 2014, Debdatta Basu. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that * the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package org.dbasu.robomvvm.viewmodel; /** * View model used for creating and binding views. */ public class ViewModel extends BaseViewModel { private static final String VIEW_MODEL = "robomvvm_view_model"; private static final String VIEW_BINDINGS = "robomvvm_view_bindings"; private View view = null; private final List<Binding> bindings = new ArrayList<Binding>(); /** * Construct a ViewModel with a supplied context. * @param context * The supplied context. */ public ViewModel(Context context) { super(context); } /** * Attempt to unbind a pre-existing view from its view model and bind it to this * view model. * @param viewToConvert * The view to convert. * @return * Null if viewToConvert is null. Null if viewToConvert corresponds to a different view model class. * The bound view otherwise. */ public View convertView(View viewToConvert) { Preconditions.checkArgument(ThreadUtil.isUiThread(), "ViewModel.convertView can only be called from the UI thread"); if(viewToConvert == null) return null; ViewModel otherViewModel = (ViewModel) ObjectTagger.getTag(viewToConvert, VIEW_MODEL); if(otherViewModel == null || !otherViewModel.getClass().equals(this.getClass())) return null; List<Binding> otherViewBindings = (List<Binding>) ObjectTagger.getTag(viewToConvert, VIEW_BINDINGS); if(otherViewBindings != null) { for (Binding binding : otherViewBindings) { binding.unbind(); } } this.view = viewToConvert; bind(); ObjectTagger.setTag(viewToConvert, VIEW_MODEL, this); ObjectTagger.setTag(viewToConvert, VIEW_BINDINGS, new ArrayList<Binding>(bindings)); this.view = null; bindings.clear(); return viewToConvert; } /** * Create a view corresponding to this view model. Created with a null parent. The View Model is stored as a tag on the root View using * {@link org.dbasu.robomvvm.util.ObjectTagger}. This makes sure that the View Model is kept alive as long as the View is alive. * @return * The created view. */ public View createView() { return createView(null); } /** * Create a view corresponding to this view model. The View Model is stored as a tag on the root View using * {@link org.dbasu.robomvvm.util.ObjectTagger}. This makes sure that the View Model is kept alive as long as the View is alive. * @param parent * Parent to attach the created view to. * @return * The created view. */ public View createView(ViewGroup parent) { Preconditions.checkArgument(ThreadUtil.isUiThread(), "ViewModel.createView can only be called from the UI thread"); int layoutId = getLayoutId(); LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View viewToConvert = inflater.inflate(layoutId, parent, false); ObjectTagger.setTag(viewToConvert, VIEW_MODEL, this); return convertView(viewToConvert); } /** * Bind a property of this view model to a property of a view in its layout. * @param property * The property of the view model * @param viewId * The id of the target view. * @param viewProperty * The property of the target view. * @param valueConverter * The value converter to use for conversion. * @param bindMode * The bind mode to use. * @return * The created binding. */ @Override
protected final Binding bindProperty(String property, int viewId, String viewProperty, ValueConverter valueConverter, BindMode bindMode) {
0
http-builder-ng/http-builder-ng
http-builder-ng-core/src/main/java/groovyx/net/http/optional/Csv.java
[ "public interface ChainedHttpConfig extends HttpConfig {\n\n interface ChainedRequest extends Request {\n ChainedRequest getParent();\n\n List<HttpCookie> getCookies();\n\n Object getBody();\n\n String getContentType();\n\n Map<String, BiConsumer<ChainedHttpConfig, ToServer>> getEncoderMap();\n\n Charset getCharset();\n\n default Charset actualCharset() {\n return traverse(this, ChainedRequest::getParent, ChainedRequest::getCharset, Traverser::notNull);\n }\n\n default String actualContentType() {\n return traverse(this, ChainedRequest::getParent, ChainedRequest::getContentType, Traverser::notNull);\n }\n\n default Object actualBody() {\n return traverse(this, ChainedRequest::getParent, ChainedRequest::getBody, Traverser::notNull);\n }\n\n default Map<String, CharSequence> actualHeaders(final Map<String, CharSequence> map) {\n Predicate<Map<String, CharSequence>> addValues = (headers) -> {\n map.putAll(headers);\n return false;\n };\n traverse(this, ChainedRequest::getParent, Request::getHeaders, addValues);\n return map;\n }\n\n default BiConsumer<ChainedHttpConfig, ToServer> actualEncoder(final String contentType) {\n final Function<ChainedRequest, BiConsumer<ChainedHttpConfig, ToServer>> theValue = (cr) -> {\n BiConsumer<ChainedHttpConfig, ToServer> ret = cr.encoder(contentType);\n if (ret != null) {\n return ret;\n } else {\n return cr.encoder(ContentTypes.ANY.getAt(0));\n }\n };\n\n return traverse(this, ChainedRequest::getParent, theValue, Traverser::notNull);\n }\n\n default Auth actualAuth() {\n final Predicate<Auth> choose = (a) -> a != null && a.getAuthType() != null;\n return traverse(this, ChainedRequest::getParent, Request::getAuth, choose);\n }\n\n default List<HttpCookie> actualCookies(final List<HttpCookie> list) {\n Predicate<List<HttpCookie>> addAll = (cookies) -> {\n list.addAll(cookies);\n return false;\n };\n traverse(this, ChainedRequest::getParent, ChainedRequest::getCookies, addAll);\n return list;\n }\n\n HttpVerb getVerb();\n\n void setVerb(HttpVerb verb);\n }\n\n interface ChainedResponse extends Response {\n ChainedResponse getParent();\n\n Class<?> getType();\n\n Function<Throwable,?> getException();\n\n default BiFunction<FromServer, Object, ?> actualAction(final Integer code) {\n return traverse(this, ChainedResponse::getParent, (cr) -> cr.when(code), Traverser::notNull);\n }\n\n default Function<Throwable,?> actualException() {\n return traverse(this, ChainedResponse::getParent, ChainedResponse::getException, Traverser::notNull);\n }\n\n default BiFunction<ChainedHttpConfig, FromServer, Object> actualParser(final String contentType) {\n final Function<ChainedResponse, BiFunction<ChainedHttpConfig, FromServer, Object>> theValue = (cr) -> {\n BiFunction<ChainedHttpConfig, FromServer, Object> ret = cr.parser(contentType);\n if (ret != null) {\n return ret;\n } else {\n return cr.parser(ContentTypes.ANY.getAt(0));\n }\n };\n\n return traverse(this, ChainedResponse::getParent, theValue, Traverser::notNull);\n }\n }\n\n Map<Map.Entry<String, Object>, Object> getContextMap();\n\n default Object actualContext(final String contentType, final Object id) {\n final Map.Entry<String, Object> key = new AbstractMap.SimpleImmutableEntry<>(contentType, id);\n final Map.Entry<String, Object> anyKey = new AbstractMap.SimpleImmutableEntry<>(ContentTypes.ANY.getAt(0), id);\n\n final Function<ChainedHttpConfig, Object> theValue = (config) -> {\n Object ctx = config.getContextMap().get(key);\n if (ctx != null) {\n return ctx;\n } else {\n return config.getContextMap().get(anyKey);\n }\n };\n\n return traverse(this, ChainedHttpConfig::getParent, theValue, Traverser::notNull);\n }\n\n ChainedResponse getChainedResponse();\n\n ChainedRequest getChainedRequest();\n\n ChainedHttpConfig getParent();\n\n default BiFunction<ChainedHttpConfig, FromServer, Object> findParser(final String contentType) {\n final BiFunction<ChainedHttpConfig, FromServer, Object> found = getChainedResponse().actualParser(contentType);\n return found == null ? NativeHandlers.Parsers::streamToBytes : found;\n }\n\n /**\n * Used to find the encoder configured to encode the current resolved content-type.\n *\n * @return the configured encoder\n * @throws IllegalStateException if no coder was found\n */\n default BiConsumer<ChainedHttpConfig, ToServer> findEncoder() {\n return findEncoder(findContentType());\n }\n\n /**\n * Used to find the encoder configured to encode the specified content-type.\n *\n * @param contentType the content-type to be encoded\n * @return the configured encoder\n * @throws IllegalStateException if no coder was found\n */\n default BiConsumer<ChainedHttpConfig, ToServer> findEncoder(final String contentType) {\n final BiConsumer<ChainedHttpConfig, ToServer> encoder = getChainedRequest().actualEncoder(contentType);\n if (encoder == null) {\n throw new IllegalStateException(\"Could not find encoder for content-type (\" + contentType + \")\");\n }\n\n return encoder;\n }\n\n default String findContentType() {\n final String contentType = getChainedRequest().actualContentType();\n if (contentType == null) {\n throw new IllegalStateException(\"Found request body, but content type is undefined\");\n }\n\n return contentType;\n }\n\n default Charset findCharset(){\n return getChainedRequest().actualCharset();\n }\n}", "public interface FromServer {\n\n public static final String DEFAULT_CONTENT_TYPE = \"application/octet-stream\";\n\n /**\n * Defines the interface to the HTTP headers contained in the response. (see also\n * https://en.wikipedia.org/wiki/List_of_HTTP_header_fields[List of HTTP Header Fields])\n */\n public static abstract class Header<T> implements Map.Entry<String, String> {\n\n final String key;\n final String value;\n private T parsed;\n\n protected static String key(final String raw) {\n return raw.substring(0, raw.indexOf(':')).trim();\n }\n\n protected static String cleanQuotes(final String str) {\n return str.startsWith(\"\\\"\") ? str.substring(1, str.length() - 1) : str;\n }\n\n protected static String value(final String raw) {\n return cleanQuotes(raw.substring(raw.indexOf(':') + 1).trim());\n }\n\n protected Header(final String key, final String value) {\n this.key = key;\n this.value = value;\n }\n\n /**\n * Retrieves the header `key`.\n *\n * @return the header key\n */\n public String getKey() {\n return key;\n }\n\n /**\n * Retrieves the header `value`.\n *\n * @return the header value\n */\n public String getValue() {\n return value;\n }\n\n /**\n * Unsupported, headers are read-only.\n *\n * @throws UnsupportedOperationException always\n */\n public String setValue(final String val) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public boolean equals(final Object o) {\n if (!(o instanceof Header)) {\n return false;\n }\n\n Header other = (Header) o;\n return (Objects.equals(getKey(), other.getKey()) &&\n Objects.equals(getValue(), other.getValue()));\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(getKey(), getValue());\n }\n\n @Override\n public String toString() {\n return key + \": \" + value;\n }\n\n /**\n * Retrieves the parsed representation of the 'value`. The type of\n * the returned `Object` depends on the header and will be given\n * by the `getParsedType()` property. \n *\n * @return the parsed header value\n */\n public T getParsed() {\n if (parsed == null) {\n this.parsed = parse();\n }\n\n return parsed;\n }\n\n /**\n * Retrieves the type of the parsed representation of the 'value`.\n *\n * @return the parsed header value type\n */\n public abstract Class<?> getParsedType();\n\n /**\n * Performs the parse of the `value`\n *\n * @return the parsed header value\n */\n protected abstract T parse();\n\n /**\n * Creates a `Header` from a full header string. The string format is colon-delimited as `KEY:VALUE`.\n *\n * [source,groovy]\n * ----\n * Header header = Header.full('Content-Type:text/plain')\n * assert header.key == 'Content-Type'\n * assert header.value == 'text/plain'\n * ----\n *\n * @param raw the full header string\n * @return the `Header` representing the given header string\n */\n public static Header<?> full(final String raw) {\n return keyValue(key(raw), value(raw));\n }\n\n /**\n * Creates a `Header` from a given `key` and `value`.\n *\n * @param key the header key\n * @param value the header value\n * @return the populated `Header`\n */\n public static Header<?> keyValue(String key, String value) {\n final BiFunction<String, String, ? extends Header> func = constructors.get(key);\n return func == null ? new ValueOnly(key, value) : func.apply(key, value);\n }\n\n /**\n * Used to find a specific `Header` by key from a {@link Collection} of `Header`s.\n *\n * @param headers the {@link Collection} of `Header`s to be searched\n * @param key the key of the desired `Header`\n * @return the `Header` with the matching key (or `null`)\n */\n public static Header<?> find(final Collection<Header<?>> headers, final String key) {\n return headers.stream().filter((h) -> h.getKey().equalsIgnoreCase(key)).findFirst().orElse(null);\n }\n\n /**\n * Type representing headers that are simple key/values, with no parseable structure in the value. For example: `Accept-Ranges: bytes`.\n */\n public static class ValueOnly extends Header<String> {\n public ValueOnly(final String key, final String value) {\n super(key, value);\n }\n\n public String parse() {\n return getValue();\n }\n\n /**\n * Always returns {@link String}\n *\n * @return the parsed header type\n */\n public Class<?> getParsedType() {\n return String.class;\n }\n }\n\n /**\n * Type representing headers that have values which are parseable as key/value pairs,\n * provided the header hey is included in the key/value map.\n * For example: `Content-Type: text/html; charset=utf-8`\n */\n public static class CombinedMap extends Header<Map<String, String>> {\n public CombinedMap(final String key, final String value) {\n super(key, value);\n }\n\n public Map<String, String> parse() {\n Map<String, String> ret = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);\n final String[] ary = getValue().split(\";\");\n ret.put(key, cleanQuotes(ary[0].trim()));\n if (ary.length > 1) {\n final String[] secondary = ary[1].split(\"=\");\n ret.put(secondary[0].trim(), cleanQuotes(secondary[1].trim()));\n }\n\n return unmodifiableMap(ret);\n }\n\n /**\n * Always returns {@link List}\n *\n * @return the parsed header type\n */\n public Class<?> getParsedType() {\n return Map.class;\n }\n }\n\n /**\n * Type representing headers that have values which are comma separated lists.\n * For example: `Allow: GET, HEAD`\n */\n public static class CsvList extends Header<List<String>> {\n public CsvList(final String key, final String value) {\n super(key, value);\n }\n\n public List<String> parse() {\n return unmodifiableList(stream(getValue().split(\",\")).map(String::trim).collect(toList()));\n }\n\n public Class<?> getParsedType() {\n return List.class;\n }\n }\n\n /**\n * Type representing headers that have values which are zoned date time values.\n * Values representing seconds from now are also converted to zoned date time values\n * with UTC/GMT zone offsets.\n *\n * * Example 1: `Retry-After: Fri, 07 Nov 2014 23:59:59 GMT`\n * * Example 2: `Retry-After: 120`\n */\n public static class HttpDate extends Header<ZonedDateTime> {\n public HttpDate(final String key, final String value) {\n super(key, value);\n }\n\n private boolean isSimpleNumber() {\n for (int i = 0; i < getValue().length(); ++i) {\n if (!Character.isDigit(getValue().charAt(i))) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Always returns {@link ZonedDateTime}\n *\n * @return the parsed header type\n */\n public ZonedDateTime parse() {\n if (isSimpleNumber()) {\n return ZonedDateTime.now(ZoneOffset.UTC).plusSeconds(Long.parseLong(getValue()));\n } else {\n return parse(RFC_1123_DATE_TIME);\n }\n }\n\n /**\n * Retrieves the {@link ZonedDateTime} value of the header using the provided {@link DateTimeFormatter}.\n *\n * @param formatter the formatter to be used\n * @return\n */\n public ZonedDateTime parse(final DateTimeFormatter formatter) {\n return ZonedDateTime.parse(getValue(), formatter);\n }\n\n public Class<?> getParsedType() {\n return ZonedDateTime.class;\n }\n }\n\n /**\n * Type representing headers that have values which are parseable as key/value pairs.\n * For example: `Alt-Svc: h2=\"http2.example.com:443\"; ma=7200`\n */\n public static class MapPairs extends Header<Map<String, String>> {\n public MapPairs(final String key, final String value) {\n super(key, value);\n }\n\n public Map<String, String> parse() {\n return stream(getValue().split(\";\"))\n .map(String::trim)\n .map((str) -> str.split(\"=\"))\n .collect(toMap((ary) -> ary[0].trim(),\n (ary) -> {\n if (ary.length == 1) {\n return ary[0];\n } else {\n return cleanQuotes(ary[1].trim());\n }\n },\n (oldVal, newVal) -> newVal,\n () -> new TreeMap<>(String.CASE_INSENSITIVE_ORDER)));\n }\n\n /**\n * Always returns {@link Map}\n *\n * @return the parsed header type\n */\n public Class<?> getParsedType() {\n return Map.class;\n }\n }\n\n /**\n * Type representing headers that have values which are parseable as longs.\n * For example: `Content-Length: 348`\n */\n public static class SingleLong extends Header<Long> {\n public SingleLong(final String key, final String value) {\n super(key, value);\n }\n\n public Long parse() {\n return Long.valueOf(getValue());\n }\n\n /**\n * Always returns {@link Long}\n *\n * @return the parsed header type\n */\n public Class<?> getParsedType() {\n return Long.class;\n }\n }\n\n public static class HttpCookies extends Header<List<HttpCookie>> {\n public HttpCookies(final String key, final String value) {\n super(key, value);\n }\n\n public List<HttpCookie> parse() {\n return HttpCookie.parse(key + \": \" + value);\n }\n\n public Class<?> getParsedType() {\n return List.class;\n }\n }\n\n private static final Map<String, BiFunction<String, String, ? extends Header>> constructors;\n\n static {\n final Map<String, BiFunction<String, String, ? extends Header>> tmp = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);\n tmp.put(\"Access-Control-Allow-Origin\", ValueOnly::new);\n tmp.put(\"Accept-Patch\", CombinedMap::new);\n tmp.put(\"Accept-Ranges\", ValueOnly::new);\n tmp.put(\"Age\", SingleLong::new);\n tmp.put(\"Allow\", CsvList::new);\n tmp.put(\"Alt-Svc\", MapPairs::new);\n tmp.put(\"Cache-Control\", MapPairs::new);\n tmp.put(\"Connection\", ValueOnly::new);\n tmp.put(\"Content-Disposition\", CombinedMap::new);\n tmp.put(\"Content-Encoding\", ValueOnly::new);\n tmp.put(\"Content-Language\", ValueOnly::new);\n tmp.put(\"Content-Length\", SingleLong::new);\n tmp.put(\"Content-Location\", ValueOnly::new);\n tmp.put(\"Content-MD5\", ValueOnly::new);\n tmp.put(\"Content-Range\", ValueOnly::new);\n tmp.put(\"Content-Type\", CombinedMap::new);\n tmp.put(\"Date\", HttpDate::new);\n tmp.put(\"ETag\", ValueOnly::new);\n tmp.put(\"Expires\", HttpDate::new);\n tmp.put(\"Last-Modified\", HttpDate::new);\n tmp.put(\"Link\", CombinedMap::new);\n tmp.put(\"Location\", ValueOnly::new);\n tmp.put(\"P3P\", MapPairs::new);\n tmp.put(\"Pragma\", ValueOnly::new);\n tmp.put(\"Proxy-Authenticate\", ValueOnly::new);\n tmp.put(\"Public-Key-Pins\", MapPairs::new);\n tmp.put(\"Refresh\", CombinedMap::new);\n tmp.put(\"Retry-After\", HttpDate::new);\n tmp.put(\"Server\", ValueOnly::new);\n tmp.put(\"Set-Cookie\", HttpCookies::new);\n tmp.put(\"Set-Cookie2\", HttpCookies::new);\n tmp.put(\"Status\", ValueOnly::new);\n tmp.put(\"Strict-Transport-Security\", MapPairs::new);\n tmp.put(\"Trailer\", ValueOnly::new);\n tmp.put(\"Transfer-Encoding\", ValueOnly::new);\n tmp.put(\"TSV\", ValueOnly::new);\n tmp.put(\"Upgrade\", CsvList::new);\n tmp.put(\"Vary\", ValueOnly::new);\n tmp.put(\"Via\", CsvList::new);\n tmp.put(\"Warning\", ValueOnly::new);\n tmp.put(\"WWW-Authenticate\", ValueOnly::new);\n tmp.put(\"X-Frame-Options\", ValueOnly::new);\n constructors = unmodifiableMap(tmp);\n }\n }\n\n /**\n * Retrieves the value of the \"Content-Type\" header from the response.\n *\n * @return the value of the \"Content-Type\" response header\n */\n default String getContentType() {\n final Header.CombinedMap header = (Header.CombinedMap) Header.find(getHeaders(), \"Content-Type\");\n if (header == null) {\n return DEFAULT_CONTENT_TYPE;\n } else {\n return header.getParsed().get(\"Content-Type\");\n }\n }\n\n /**\n * Retrieves the value of the charset from the \"Content-Type\" response header.\n *\n * @return the value of the charset from the \"Content-Type\" response header\n */\n default Charset getCharset() {\n final Header.CombinedMap header = (Header.CombinedMap) Header.find(getHeaders(), \"Content-Type\");\n if (header == null) {\n return StandardCharsets.UTF_8;\n }\n\n if (header.getParsed().containsKey(\"charset\")) {\n Charset.forName(header.getParsed().get(\"charset\"));\n }\n\n return StandardCharsets.UTF_8;\n }\n\n default List<HttpCookie> getCookies() {\n return HttpBuilder.cookies(getHeaders());\n }\n\n /**\n * Retrieves the {@link InputStream} containing the response content (may have already been processed).\n *\n * @return the response content\n */\n InputStream getInputStream();\n\n /**\n * Retrieves the response status code (https://en.wikipedia.org/wiki/List_of_HTTP_status_codes[List of HTTP status code]).\n *\n * @return the response status code\n */\n int getStatusCode();\n\n /**\n * Retrieves the response status message.\n *\n * @return the response status message (or null)\n */\n String getMessage();\n\n /**\n * Retrieves a {@link List} of the response headers as ({@link Header} objects).\n *\n * @return a {@link List} of response headers\n */\n List<Header<?>> getHeaders();\n\n /**\n * Determines whether or not there is body content in the response.\n *\n * @return true if there is body content in the response\n */\n boolean getHasBody();\n\n /**\n * Retrieves the {@link URI} of the original request.\n *\n * @return the {@link URI} of the original request\n */\n URI getUri();\n\n /**\n * Performs any client-specific response finishing operations.\n */\n void finish();\n\n /**\n * Retrieves a {@link Reader} for the response body content (if there is any). The content may have already been processed.\n *\n * @return a {@link Reader} for the response body content (may be empty)\n */\n default Reader getReader() {\n return new BufferedReader(new InputStreamReader(getInputStream()));\n }\n}", "public interface HttpConfig {\n\n /**\n * Defines the an enumeration of the overall HTTP response status categories.\n */\n enum Status {\n SUCCESS, FAILURE\n }\n\n /**\n * Defines the allowed values of the HTTP authentication type.\n */\n enum AuthType {\n BASIC, DIGEST\n }\n\n /**\n * Defines the configurable HTTP request authentication properties.\n */\n interface Auth {\n\n /**\n * Retrieve the authentication type for the request.\n *\n * @return the {@link AuthType} for the Request\n */\n AuthType getAuthType();\n\n /**\n * Retrieves the configured user for the request.\n *\n * @return the configured user\n */\n String getUser();\n\n /**\n * Retrieves the configured password for the request.\n *\n * @return the configured password for the request\n */\n String getPassword();\n\n /**\n * Configures the request to use BASIC authentication with the given `username` and `password`. The authentication will not be preemptive. This\n * method is an alias for calling: `basic(String, String, false)`.\n *\n * [source,groovy]\n * ----\n * def http = HttpBuilder.configure {\n * request.uri = 'http://localhost:10101'\n * request.auth.basic 'admin', '$3cr3t'\n * }\n * ----\n *\n * @param user the username\n * @param password the user's password\n */\n default void basic(String user, String password) {\n basic(user, password, false);\n }\n\n /**\n * Configures the request to use BASIC authentication with the given `username` and `password`.\n *\n * [source,groovy]\n * ----\n * def http = HttpBuilder.configure {\n * request.uri = 'http://localhost:10101'\n * request.auth.basic 'admin', '$3cr3t', true\n * }\n * ----\n *\n * @param user the username\n * @param password the user's password\n * @param preemptive whether or not this call will override similar configuration in the chain\n */\n void basic(String user, String password, boolean preemptive);\n\n /**\n * Configures the request to use DIGEST authentication with the given username and password. The authentication will not be preemptive. This\n * method is an alias for calling: `digest(String, String, false)`.\n *\n * [source,groovy]\n * ----\n * def http = HttpBuilder.configure {\n * request.uri = 'http://localhost:10101'\n * request.auth.digest 'admin', '$3cr3t'\n * }\n * ----\n *\n * @param user the username\n * @param password the user's password\n */\n default void digest(String user, String password) {\n digest(user, password, false);\n }\n\n /**\n * Configures the request to use DIGEST authentication with the given information.\n *\n * [source,groovy]\n * ----\n * def http = HttpBuilder.configure {\n * request.uri = 'http://localhost:10101'\n * request.auth.digest 'admin', '$3cr3t', true\n * }\n * ----\n *\n * @param user the username\n * @param password the user's password\n * @param preemptive whether or not this call will override similar configuration in the chain\n */\n void digest(String user, String password, boolean preemptive);\n }\n\n /**\n * Defines the configurable HTTP request properties.\n *\n * The `uri` property is the only one that must be defined either in the {@link HttpBuilder} or in the verb configuration.\n */\n interface Request {\n\n /**\n * Retrieves the authentication information for the request.\n *\n * @return the authentication information for the request.\n */\n Auth getAuth();\n\n /**\n * The `contentType` property is used to specify the `Content-Type` header value for the request.\n *\n * [source,groovy]\n * ----\n * def http = HttpBuilder.configure {\n * request.uri = 'http://localhost:10101'\n * request.contentType = 'text/json'\n * }\n *\n * http.post {\n * request.uri.path = '/bar'\n * request.contentType = 'text/csv'\n * }\n * ----\n *\n * By default, the value will be `text/plain`. The {@link ContentTypes} class provides a helper for some of the more common content type values.\n *\n * @param val the content type value to be used\n */\n void setContentType(String val);\n\n /**\n * The `charset` property is used to specify the character set (as a String) used by the request.\n *\n * [source,groovy]\n * ----\n * def http = HttpBuilder.configure {\n * request.uri = 'http://localhost:10101'\n * request.charset = 'utf-16'\n * }\n *\n * http.post {\n * request.uri.path = '/bar'\n * request.charset = 'utf-8'\n * }\n * ----\n *\n * @param val the content type character set value to be used\n */\n void setCharset(String val);\n\n /**\n * The `charset` property is used to specify the character set (as a {@link Charset}) used by the request. This value will be reflected in\n * the `Content-Type` header value (e.g. `Content-Type: text/plain; charset=utf-8`). A content-type value must be specified in order for this\n * value to be applied.\n *\n * [source,groovy]\n * ----\n * def http = HttpBuilder.configure {\n * request.uri = 'http://localhost:10101'\n * request.charset = 'utf-16'\n * }\n *\n * http.post {\n * request.uri.path = '/bar'\n * request.charset = 'utf-8'\n * }\n * ----\n *\n * @param val the content type character set value to be used\n */\n void setCharset(Charset val);\n\n /**\n * Retrieves the {@link UriBuilder} for the request, which provides methods for more fine-grained URI specification.\n *\n * [source,groovy]\n * ----\n * def http = HttpBuilder.configure {\n * request.uri = 'http://localhost:10101'\n * }\n *\n * http.get {\n * request.uri.path = '/foo'\n * }\n * ----\n *\n * @return the {@link UriBuilder} for the request\n */\n UriBuilder getUri();\n\n /**\n * The `request.uri` is the URI of the HTTP endpoint for the request, specified as a `String` in this case.\n *\n * [source,groovy]\n * ----\n * def http = HttpBuilder.configure {\n * request.uri = 'http://localhost:10101'\n * }\n *\n * http.get {\n * request.uri.path = '/foo'\n * }\n *\n * http.post {\n * request.uri.path = '/bar'\n * }\n * ----\n *\n * Which allows multiple verb requests to be configured against the same {@link HttpBuilder}. See the {@link UriBuilder} documentation for\n * more details.\n *\n * The `uri` is the only required configuration property.\n *\n * @param val the URI to be used for the request, as a String\n * @throws IllegalArgumentException if there is a problem with the URI syntax\n */\n void setUri(String val);\n\n /**\n * The `request.raw` is the means of specifying a \"raw\" URI as the HTTP endpoint for the request, specified as a `String`. No encoding or decoding is performed on a \"raw\" URI. Any such\n * encoding or decoding of URI content must be done in the provided string itself, as it will be used \"as is\" in the resulting URI. This functionality is useful in the case where\n * there are encoded entities in the URI path, since the standard `uri` method will decode these on building the `URI`.\n *\n * @param val the raw URI string\n */\n void setRaw(String val);\n\n /**\n * The `request.uri` is the URI of the HTTP endpoint for the request, specified as a `URI` in this case.\n *\n * [source,groovy]\n * ----\n * def http = HttpBuilder.configure {\n * request.uri = new URI('http://localhost:10101')\n * }\n *\n * http.get {\n * request.uri.path = '/foo'\n * }\n *\n * http.post {\n * request.uri.path = '/bar'\n * }\n * ----\n *\n * Which allows multiple verb requests to be configured against the same {@link HttpBuilder}. See the {@link UriBuilder} documentation for\n * more details.\n *\n * The `uri` is the only required configuration property.\n *\n * @param val the URI to be used for the request, as a URI\n */\n void setUri(URI val);\n\n /**\n * The `request.uri` is the URI of the HTTP endpoint for the request, specified as a `URL` in this case.\n *\n * [source,groovy]\n * ----\n * def http = HttpBuilder.configure {\n * request.uri = new URL('http://localhost:10101')\n * }\n *\n * http.get {\n * request.uri.path = '/foo'\n * }\n *\n * http.post {\n * request.uri.path = '/bar'\n * }\n * ----\n *\n * Which allows multiple verb requests to be configured against the same {@link HttpBuilder}. See the {@link UriBuilder} documentation for\n * more details.\n *\n * The `uri` is the only required configuration property.\n *\n * @param val the URI to be used for the request, as a URL\n */\n void setUri(URL val) throws URISyntaxException;\n\n /**\n * Used to retrieve the request headers.\n *\n * @return the `Map` of request headers\n */\n Map<String, CharSequence> getHeaders();\n\n /**\n * The `headers` property allows the direct specification of the request headers as a `Map<String,String>`. Be aware that `Content-Type` and\n * `Accept` are actually header values and it is up to the implementation to determine which configuration will win out if both are configured.\n *\n * [source,groovy]\n * ----\n * def http = HttpBuilder.configure {\n * request.uri = 'http://localhost:10101'\n * request.headers = [\n * ClientId: '987sdfsdf9uh'\n * ]\n * }\n *\n * http.post {\n * request.uri.path = '/bar'\n * request.headers = [\n * AccessCode: '99887766'\n * ]\n * }\n * ----\n *\n * WARNING: The headers are additive; however, a header specified in the verb configuration may overwrite one defined in the global configuration.\n *\n * @param toAdd the headers to be added to the request headers\n */\n void setHeaders(Map<String, CharSequence> toAdd);\n\n /**\n * The `accept` property allows configuration of the request `Accept` header, which may be used to specify certain media types which are\n * acceptable for the response.\n *\n * [source,groovy]\n * ----\n * def http = HttpBuilder.configure {\n * request.uri = 'http://localhost:10101'\n * request.accept = ['image/jpeg']\n * }\n *\n * http.post {\n * request.uri.path = '/bar'\n * request.accept = ['image/tiff', 'image/png']\n * }\n * ----\n *\n * @param values the accept header values as a String array\n */\n void setAccept(String[] values);\n\n /**\n * The `accept` property allows configuration of the request `Accept` header, which may be used to specify certain media types which are\n * acceptable for the response.\n *\n * [source,groovy]\n * ----\n * def http = HttpBuilder.configure {\n * request.uri = 'http://localhost:10101'\n * request.accept = ['image/jpeg']\n * }\n *\n * http.post {\n * request.uri.path = '/bar'\n * request.accept = ['image/tiff', 'image/png']\n * }\n * ----\n *\n * @param values the accept header values as a List\n */\n void setAccept(Iterable<String> values);\n\n /**\n * The `body` property is used to configure the body content for the request. The request body content may be altered by configured encoders\n * internally or may be passed on unmodified. See {@link HttpConfig} and {@link HttpObjectConfig} for content-altering methods (encoders,\n * decoders and interceptors).\n *\n * @param val the request body content\n */\n void setBody(Object val);\n\n /**\n * The `cookie` configuration options provide a means of adding HTTP Cookies to the request. Cookies are defined with a `name` and `value`.\n *\n * [source,groovy]\n * ----\n * def http = HttpBuilder.configure {\n * request.uri = 'http://localhost:10101'\n * request.cookie 'seen-before', 'true'\n * }\n * ----\n *\n * WARNING: Cookies are additive, once a Cookie is defined (e.g. in the global configuration), you cannot overwrite it in per-verb configurations.\n *\n * As noted in the {@link groovyx.net.http.HttpObjectConfig.Client} configuration, the default Cookie version supported is `0`, but this may\n * be modified.\n *\n * @param name the cookie name\n * @param value the cookie value\n */\n default void cookie(String name, String value) {\n cookie(name, value, (Date) null);\n }\n\n /**\n * The `cookie` configuration options provide a means of adding HTTP Cookies to the request. Cookies are defined with a `name`, `value`, and\n * `expires` Date.\n *\n * [source,groovy]\n * ----\n * def http = HttpBuilder.configure {\n * request.uri = 'http://localhost:10101'\n * request.cookie 'seen-before', 'true'\n * }\n *\n * http.post {\n * request.uri.path = '/bar'\n * request.cookie 'last-page', 'item-list', Date.parse('MM/dd/yyyy', '12/31/2016')\n * }\n * ----\n *\n * WARNING: Cookies are additive, once a Cookie is defined (e.g. in the global configuration), you cannot overwrite it in per-verb configurations.\n *\n * As noted in the {@link groovyx.net.http.HttpObjectConfig.Client} configuration, the default Cookie version supported is `0`, but this may\n * be modified.\n *\n * @param name the cookie name\n * @param value the cookie value\n * @param expires the cookie expiration date\n */\n void cookie(String name, String value, Date expires);\n\n /**\n * The `cookie` configuration options provide a means of adding HTTP Cookies to the request. Cookies are defined with a `name`, `value`, and\n * an expiration date as {@link LocalDateTime}.\n *\n * [source,groovy]\n * ----\n * HttpBuilder.configure {\n * request.uri = 'http://localhost:10101'\n * }.post {\n * request.uri.path = '/bar'\n * request.cookie 'last-page', 'item-list', LocalDateTime.now().plus(1, ChronoUnit.MONTHS)\n * }\n * ----\n *\n * WARNING: Cookies are additive, once a Cookie is defined (e.g. in the global configuration), you cannot overwrite it in per-verb configurations.\n *\n * As noted in the {@link groovyx.net.http.HttpObjectConfig.Client} configuration, the default Cookie version supported is `0`, but this may\n * be modified.\n *\n * @param name the cookie name\n * @param value the cookie value\n * @param expires the cookie expiration date\n */\n void cookie(String name, String value, LocalDateTime expires);\n\n /**\n * Specifies the request encoder ({@link ToServer} instance) to be used when encoding the given content type.\n *\n * @param contentType the content type\n * @param val the request encoder (wrapped in a {@link BiConsumer} function)\n */\n void encoder(String contentType, BiConsumer<ChainedHttpConfig, ToServer> val);\n\n /**\n * Specifies the request encoder ({@link ToServer} instance) to be used when encoding the given list of content types.\n *\n * @param contentTypes the content types\n * @param val the request encoder (wrapped in a {@link BiConsumer} function)\n */\n void encoder(Iterable<String> contentTypes, BiConsumer<ChainedHttpConfig, ToServer> val);\n\n /**\n * Retrieves the request encoder ({@link ToServer} instance) for the specified content type wrapped in a {@link BiConsumer} function.\n *\n * @param contentType the content type of the encoder to be retrieved\n * @return the encoder for the specified content type (wrapped in a {@link BiConsumer} function)\n */\n BiConsumer<ChainedHttpConfig, ToServer> encoder(String contentType);\n }\n\n /**\n * Defines the configurable HTTP response properties.\n */\n interface Response {\n\n /**\n * Configures the execution of the provided closure \"when\" the given status occurs in the response. The `closure` will be called with an instance\n * of the response as a `FromServer` instance and the response body as an `Object` (if there is one). The value returned from the closure will be\n * used as the result value of the request; this allows the closure to modify the captured response.\n *\n * [source,groovy]\n * ----\n * def http = HttpBuilder.configure {\n * request.uri = 'http://localhost:10101'\n * }\n *\n * http.get {\n * request.uri.path = '/foo'\n * response.when(Status.SUCCESS){\n * // executed when a successful response is received\n * }\n * }\n * ----\n *\n * This method is the same as calling either the `success(Closure)` or `failure(Closure)` methods. Only one closure may be mapped to each\n * status.\n *\n * @param status the response {@link Status} enum\n * @param closure the closure to be executed\n */\n default void when(Status status, Closure<?> closure) {\n when(status, new ClosureBiFunction<>(closure));\n }\n\n /**\n * Configures the execution of the provided function \"when\" the given status occurs in the response. The `function` will be called with an instance\n * of the response as a `FromServer` instance and the response body as an `Object` (if there is one). The value returned from the closure will be\n * used as the result value of the request; this allows the closure to modify the captured response.\n *\n * This method is generally used for Java-based configuration.\n *\n * [source,java]\n * ----\n * HttpBuilder http = HttpBuilder.configure(config -> {\n * config.getRequest().setUri(\"http://localhost:10101\");\n * });\n * http.get( config -> {\n * config.getRequest().getUri().setPath(\"/foo\");\n * config.getResponse().when(Status.SUCCESS, new BiFunction<FromServer, Object, Object>() {\n * // executed when a successful response is received\n * });\n * });\n * ----\n *\n * This method is the same as calling either the `success(BiFunction)` or `failure(BiFunction)` methods. Only one function may be mapped to each\n * status.\n *\n * @param status the response {@link Status} enum\n * @param function the function to be executed\n */\n void when(Status status, BiFunction<FromServer, Object, ?> function);\n\n /**\n * Configures the execution of the provided closure \"when\" the given status code occurs in the response. The `closure` will be called with an instance\n * of the response as a `FromServer` instance. The value returned from the closure will be used as the result value of the request; this allows\n * the closure to modify the captured response.\n *\n * [source,groovy]\n * ----\n * def http = HttpBuilder.configure {\n * request.uri = 'http://localhost:10101'\n * }\n *\n * http.get {\n * request.uri.path = '/foo'\n * response.when(404){\n * // executed when a 'not found' response is received\n * }\n * }\n * ----\n *\n * @param code the response code to be caught\n * @param closure the closure to be executed\n */\n default void when(Integer code, Closure<?> closure) {\n when(code, new ClosureBiFunction<>(closure));\n }\n\n /**\n * Configures the execution of the provided function \"when\" the given status code occurs in the response. The `function` will be called with an instance\n * of the response as a `FromServer` instance and the response body as an `Object` (if there is one). The value returned from the closure will be\n * used as the result value of the request; this allows the closure to modify the captured response.\n *\n * This method is generally used for Java-based configuration.\n *\n * [source,java]\n * ----\n * HttpBuilder http = HttpBuilder.configure(config -> {\n * config.getRequest().setUri(\"http://localhost:10101\");\n * });\n * http.get( config -> {\n * config.getRequest().getUri().setPath(\"/foo\");\n * config.getResponse().when(404, new BiFunction<FromServer, Object, Object>() {\n * // executed when a successful response is received\n * });\n * });\n * ----\n *\n * This method is the same as calling either the `success(BiFunction)` or `failure(BiFunction)` methods. Only one function may be mapped to each\n * status.\n *\n * @param code the response code\n * @param function the function to be executed\n */\n void when(Integer code, BiFunction<FromServer, Object, ?> function);\n\n /**\n * Configures the execution of the provided closure \"when\" the given status code (as a String) occurs in the response. The `closure` will be\n * called with an instance of the response as a `FromServer` instance. The value returned from the closure will be used as the result value\n * of the request; this allows the closure to modify the captured response.\n *\n * [source,groovy]\n * ----\n * def http = HttpBuilder.configure {\n * request.uri = 'http://localhost:10101'\n * }\n *\n * http.get {\n * request.uri.path = '/foo'\n * response.when('404'){\n * // executed when a 'not found' response is received\n * }\n * }\n * ----\n *\n * @param code the response code to be caught\n * @param closure the closure to be executed\n */\n default void when(String code, Closure<?> closure) {\n when(code, new ClosureBiFunction<>(closure));\n }\n\n /**\n * Configures the execution of the provided function \"when\" the given status code (as a `String`) occurs in the response. The `function` will be\n * called with an instance of the response as a `FromServer` instance and the response body as an `Object` (if there is one). The value returned\n * from the function will be used as the result value of the request; this allows the function to modify the captured response.\n *\n * This method is generally used for Java-based configuration.\n *\n * [source,java]\n * ----\n * HttpBuilder http = HttpBuilder.configure(config -> {\n * config.getRequest().setUri(\"http://localhost:10101\");\n * });\n * http.get( config -> {\n * config.getRequest().getUri().setPath(\"/foo\");\n * config.getResponse().when(\"404\", new BiFunction<FromServer, Object, Object>() {\n * // executed when a successful response is received\n * });\n * });\n * ----\n *\n * @param code the response code as a `String`\n * @param function the function to be executed\n */\n void when(String code, BiFunction<FromServer, Object, ?> function);\n\n /**\n * Used to retrieve the \"when\" function associated with the given status code.\n *\n * @param code the status code\n * @return the mapped closure\n */\n BiFunction<FromServer, Object, ?> when(Integer code);\n\n /**\n * Configures the execution of the provided closure \"when\" a successful response is received (code < 400). The `closure` will be called with\n * an instance of the response as a `FromServer` instance. The value returned from the closure will be used as the result value of the request;\n * this allows the closure to modify the captured response.\n *\n * [source,groovy]\n * ----\n * def http = HttpBuilder.configure {\n * request.uri = 'http://localhost:10101'\n * }\n *\n * http.get {\n * request.uri.path = '/foo'\n * response.success(){\n * // executed when a successful response is received\n * }\n * }\n * ----\n *\n * This method is the same as calling either the `when(Status.SUCCESS, Closure)` method.\n *\n * @param closure the closure to be executed\n */\n default void success(Closure<?> closure) {\n success(new ClosureBiFunction<>(closure));\n }\n\n /**\n * Configures the execution of the provided function when a success response is received (code < 400). The `function` will be called with\n * an instance of the response as a `FromServer` instance and the body content as an `Object` (if present). The value returned from the function\n * will be used as the result value of the request; this allows the function to modify the captured response.\n *\n * This method is generally used for Java-specific configuration.\n *\n * [source,java]\n * ----\n * HttpBuilder http = HttpBuilder.configure(config -> {\n * config.getRequest().setUri(\"http://localhost:10101\");\n * });\n * http.get( config -> {\n * config.getRequest().getUri().setPath(\"/foo\");\n * config.getResponse().success(new BiFunction<FromServer, Object, Object>() {\n * // executed when a success response is received\n * });\n * });\n * ----\n *\n * This method is the same as calling either the `when(Status.SUCCESS, BiFunction)` method.\n *\n * @param function the closure to be executed\n */\n void success(BiFunction<FromServer, Object, ?> function);\n\n /**\n * Configures the execution of the provided closure \"when\" a failure response is received (code >= 400). The `closure` will be called with\n * an instance of the response as a `FromServer` instance. The value returned from the closure will be used as the result value of the request;\n * this allows the closure to modify the captured response.\n *\n * [source,groovy]\n * ----\n * def http = HttpBuilder.configure {\n * request.uri = 'http://localhost:10101'\n * }\n *\n * http.get {\n * request.uri.path = '/foo'\n * response.failure {\n * // executed when a failure response is received\n * }\n * }\n * ----\n *\n * This method is the same as calling either the `when(Status.FAILURE, Closure)` method.\n *\n * @param closure the closure to be executed\n */\n default void failure(Closure<?> closure) {\n failure(new ClosureBiFunction<>(closure));\n }\n\n /**\n * Configures the execution of the provided function \"when\" a failure response is received (code >= 400). The `function` will be called with\n * an instance of the response as a `FromServer` instance and the body content as an `Object` (if present). The value returned from the function\n * will be used as the result value of the request; this allows the function to modify the captured response.\n *\n * This method is generally used for Java-specific configuration.\n *\n * [source,java]\n * ----\n * HttpBuilder http = HttpBuilder.configure(config -> {\n * config.getRequest().setUri(\"http://localhost:10101\");\n * });\n * http.get( config -> {\n * config.getRequest().getUri().setPath(\"/foo\");\n * config.getResponse().failure(new BiFunction<FromServer, Object, Object>() {\n * // executed when a failure response is received\n * });\n * });\n * ----\n *\n * This method is the same as calling either the `when(Status.FAILURE, BiFunction)` method.\n *\n * @param function the closure to be executed\n */\n void failure(BiFunction<FromServer, Object, ?> function);\n\n /**\n * Configures the execution of the provided closure to handle exceptions during request/response processing. This is\n * different from a failure condition because there is no response, no status code, no headers, etc. The `closure` will be called with\n * the best guess as to what was the original exception. Some attempts will be made to unwrap exceptions that are of type\n * {@link groovyx.net.http.TransportingException} or {@link java.lang.reflect.UndeclaredThrowableException}. The `closure`\n * should have a single {@link java.lang.Throwable} argument.\n *\n * The value returned from the closure will be used as the result value of the request. Since there is no response\n * body for the closure to process, this usually means that the closure should do one of three things: re-throw the exception or \n * throw a wrapped version of the exception, return null, or return a predefined empty value.\n *\n * [source,groovy]\n * ----\n * def http = HttpBuilder.configure {\n * request.uri = 'http://localhost:10101'\n * }\n *\n * http.get {\n * request.uri.path = '/foo'\n * response.exception { Throwable t ->\n * t.printStackTrace();\n * throw new RuntimeException(t);\n * }\n * }\n * ----\n *\n * The default exception method wraps the exception in a {@link java.lang.RuntimeException} (if it is\n * not already of that type) and rethrows.\n *\n * @param closure the closure to be executed\n */\n default void exception(Closure<?> closure) {\n exception(new ClosureFunction<>(closure));\n }\n\n /**\n * Configures the execution of the provided `function` to handle exceptions during request/response processing. This is\n * different from a failure condition because there is no response, no status code, no headers, etc. The `function` will be called with\n * the best guess as to what was the original exception. Some attempts will be made to unwrap exceptions that are of type\n * {@link groovyx.net.http.TransportingException} or {@link java.lang.reflect.UndeclaredThrowableException}.\n *\n * The value returned from the function will be used as the result value of the request. Since there is no response\n * body for the function to process, this usually means that the function should do one of three things: re-throw the exception or \n * throw a wrapped version of the exception, return null, or return a predefined empty value.\n\n * This method is generally used for Java-specific configuration.\n *\n * [source,java]\n * ----\n * HttpBuilder http = HttpBuilder.configure(config -> {\n * config.getRequest().setUri(\"http://localhost:10101\");\n * });\n * http.get( config -> {\n * config.getRequest().getUri().setPath(\"/foo\");\n * config.getResponse().exception((t) -> {\n * t.printStackTrace();\n * throw new RuntimeException(t);\n * });\n * });\n * ----\n *\n * The built in exception method wraps the exception in a {@link java.lang.RuntimeException} (if it is\n * not already of that type) and rethrows.\n *\n * @param function the function to be executed\n */\n void exception(Function<Throwable,?> function);\n \n /**\n * Used to specify a response parser ({@link FromServer} instance) for the specified content type, wrapped in a {@link BiFunction}.\n *\n * @param contentType the content type where the parser will be applied\n * @param val the parser wrapped in a function object\n */\n void parser(String contentType, BiFunction<ChainedHttpConfig, FromServer, Object> val);\n\n /**\n * Used to specify a response parser ({@link FromServer} instance) for the specified content types, wrapped in a {@link BiFunction}.\n *\n * @param contentTypes the contents type where the parser will be applied\n * @param val the parser wrapped in a function object\n */\n void parser(Iterable<String> contentTypes, BiFunction<ChainedHttpConfig, FromServer, Object> val);\n\n /**\n * Used to retrieve the parser configured for the specified content type.\n *\n * @param contentType the content type\n * @return the mapped parser as a {@link FromServer} instance wrapped in a function object\n */\n BiFunction<ChainedHttpConfig, FromServer, Object> parser(String contentType);\n }\n\n /**\n * Registers a context-level content-type specific object.\n *\n * @param contentType the content type scope of the mapping\n * @param id the mapping key\n * @param obj the mapping value\n */\n void context(String contentType, Object id, Object obj);\n\n /**\n * Used to register a content-type-scoped object on the context in the specified content-type scopes.\n *\n * @param contentTypes the content-types where the mapping is scoped\n * @param id the mapping key\n * @param obj the mapping value\n */\n default void context(final Iterable<String> contentTypes, final Object id, final Object obj) {\n for (String contentType : contentTypes) {\n context(contentType, id, obj);\n }\n }\n\n /**\n * Used to retrieve configuration information about the HTTP request.\n *\n * @return the HTTP request\n */\n Request getRequest();\n\n /**\n * Used to retrieve configuration information about the HTTP response.\n *\n * @return the HTTP response\n */\n Response getResponse();\n}", "public interface ToServer {\n\n /**\n * Translates the request content appropriately for the underlying client implementation. The contentType will be determined by the request.\n *\n * @param inputStream the request input stream to be translated.\n */\n void toServer(InputStream inputStream);\n}", "public class TransportingException extends RuntimeException {\n\n public TransportingException(final String message, final Throwable cause) {\n super(message, cause);\n }\n\n public TransportingException(final Throwable cause) {\n super(cause);\n }\n}", "public static class Encoders {\n\n // TODO: better testing around encoders\n\n public static Object checkNull(final Object body) {\n if (body == null) {\n throw new NullPointerException(\"Effective body cannot be null\");\n }\n\n return body;\n }\n\n public static void checkTypes(final Object body, final Class<?>[] allowedTypes) {\n final Class<?> type = body.getClass();\n for (Class<?> allowed : allowedTypes) {\n if (allowed.isAssignableFrom(type)) {\n return;\n }\n }\n\n final String msg = String.format(\"Cannot encode bodies of type %s, only bodies of: %s\",\n type.getName(),\n Arrays.stream(allowedTypes).map(Class::getName).collect(Collectors.joining(\", \")));\n\n throw new IllegalArgumentException(msg);\n }\n\n public static InputStream readerToStream(final Reader r, final Charset cs) throws IOException {\n return new ReaderInputStream(r, cs);\n }\n\n public static InputStream stringToStream(final String s, final Charset cs) {\n return new CharSequenceInputStream(s, cs);\n }\n\n public static boolean handleRawUpload(final ChainedHttpConfig config, final ToServer ts) {\n final ChainedHttpConfig.ChainedRequest request = config.getChainedRequest();\n final Object body = request.actualBody();\n final Charset charset = request.actualCharset();\n\n try {\n if (body instanceof File) {\n ts.toServer(new FileInputStream((File) body));\n return true;\n } else if (body instanceof Path) {\n ts.toServer(Files.newInputStream((Path) body));\n return true;\n } else if (body instanceof byte[]) {\n ts.toServer(new ByteArrayInputStream((byte[]) body));\n return true;\n } else if (body instanceof InputStream) {\n ts.toServer((InputStream) body);\n return true;\n } else if (body instanceof Reader) {\n ts.toServer(new ReaderInputStream((Reader) body, charset));\n return true;\n } else {\n return false;\n }\n } catch (IOException e) {\n throw new TransportingException(e);\n }\n }\n\n private static final Class[] BINARY_TYPES = new Class[]{ByteArrayInputStream.class, InputStream.class, byte[].class, Closure.class};\n\n /**\n * Standard encoder for binary types. Accepts ByteArrayInputStream, InputStream, and byte[] types.\n *\n * @param config Fully configured chained request\n * @param ts Formatted http body is passed to the ToServer argument\n */\n public static void binary(final ChainedHttpConfig config, final ToServer ts) {\n final ChainedHttpConfig.ChainedRequest request = config.getChainedRequest();\n final Object body = checkNull(request.actualBody());\n if (handleRawUpload(config, ts)) {\n return;\n }\n\n checkTypes(body, BINARY_TYPES);\n\n if (body instanceof byte[]) {\n ts.toServer(new ByteArrayInputStream((byte[]) body));\n } else {\n throw new UnsupportedOperationException();\n }\n }\n\n private static final Class[] TEXT_TYPES = new Class[]{Closure.class, Writable.class, Reader.class, String.class};\n\n /**\n * Standard encoder for text types. Accepts String and Reader types\n *\n * @param config Fully configured chained request\n * @param ts Formatted http body is passed to the ToServer argument\n */\n public static void text(final ChainedHttpConfig config, final ToServer ts) throws IOException {\n final ChainedHttpConfig.ChainedRequest request = config.getChainedRequest();\n if (handleRawUpload(config, ts)) {\n return;\n }\n\n final Object body = checkNull(request.actualBody());\n checkTypes(body, TEXT_TYPES);\n\n ts.toServer(stringToStream(body.toString(), request.actualCharset()));\n }\n\n private static final Class[] FORM_TYPES = {Map.class, String.class};\n\n /**\n * Standard encoder for requests with content type 'application/x-www-form-urlencoded'.\n * Accepts String and Map types. If the body is a String type the method assumes it is properly\n * url encoded and is passed to the ToServer parameter as is. If the body is a Map type then\n * the output is generated by the {@link Form} class.\n *\n * @param config Fully configured chained request\n * @param ts Formatted http body is passed to the ToServer argument\n */\n public static void form(final ChainedHttpConfig config, final ToServer ts) {\n final ChainedHttpConfig.ChainedRequest request = config.getChainedRequest();\n if (handleRawUpload(config, ts)) {\n return;\n }\n\n final Object body = checkNull(request.actualBody());\n checkTypes(body, FORM_TYPES);\n\n if (body instanceof String) {\n ts.toServer(stringToStream((String) body, request.actualCharset()));\n } else if (body instanceof Map) {\n final Map<?, ?> params = (Map) body;\n final String encoded = Form.encode(params, request.actualCharset());\n ts.toServer(stringToStream(encoded, request.actualCharset()));\n } else {\n throw new UnsupportedOperationException();\n }\n }\n\n private static final Class[] XML_TYPES = new Class[]{String.class, StreamingMarkupBuilder.class};\n\n /**\n * Standard encoder for requests with an xml body.\n * <p>\n * Accepts String and {@link Closure} types. If the body is a String type the method passes the body\n * to the ToServer parameter as is. If the body is a {@link Closure} then the closure is converted\n * to xml using Groovy's {@link StreamingMarkupBuilder}.\n *\n * @param config Fully configured chained request\n * @param ts Formatted http body is passed to the ToServer argument\n */\n public static void xml(final ChainedHttpConfig config, final ToServer ts) {\n final ChainedHttpConfig.ChainedRequest request = config.getChainedRequest();\n if (handleRawUpload(config, ts)) {\n return;\n }\n\n final Object body = checkNull(request.actualBody());\n checkTypes(body, XML_TYPES);\n\n if (body instanceof String) {\n ts.toServer(stringToStream((String) body, request.actualCharset()));\n } else if (body instanceof Closure) {\n final StreamingMarkupBuilder smb = new StreamingMarkupBuilder();\n ts.toServer(stringToStream(smb.bind(body).toString(), request.actualCharset()));\n } else {\n throw new UnsupportedOperationException();\n }\n }\n\n /**\n * Standard encoder for requests with a json body.\n * <p>\n * Accepts String, {@link GString} and {@link Closure} types. If the body is a String type the method passes the body\n * to the ToServer parameter as is. If the body is a {@link Closure} then the closure is converted\n * to json using Groovy's {@link JsonBuilder}.\n *\n * @param config Fully configured chained request\n * @param ts Formatted http body is passed to the ToServer argument\n */\n public static void json(final ChainedHttpConfig config, final ToServer ts) {\n final ChainedHttpConfig.ChainedRequest request = config.getChainedRequest();\n if (handleRawUpload(config, ts)) {\n return;\n }\n\n final Object body = checkNull(request.actualBody());\n final String json = ((body instanceof String || body instanceof GString)\n ? body.toString()\n : new JsonBuilder(body).toString());\n ts.toServer(stringToStream(json, request.actualCharset()));\n }\n}" ]
import static groovyx.net.http.NativeHandlers.Encoders.*; import com.opencsv.CSVReader; import com.opencsv.CSVWriter; import groovyx.net.http.ChainedHttpConfig; import groovyx.net.http.FromServer; import groovyx.net.http.HttpConfig; import groovyx.net.http.ToServer; import groovyx.net.http.TransportingException; import java.io.IOException; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Supplier;
/** * Copyright (C) 2017 HttpBuilder-NG Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package groovyx.net.http.optional; /** * Optional CSV encoder/parser implementation based on the [OpenCSV](http://opencsv.sourceforge.net/) library. It will be available when the OpenCsv * library is on the classpath (an optional dependency). */ public class Csv { public static final Supplier<BiConsumer<ChainedHttpConfig, ToServer>> encoderSupplier = () -> Csv::encode; public static final Supplier<BiFunction<ChainedHttpConfig, FromServer, Object>> parserSupplier = () -> Csv::parse; public static class Context { public static final String ID = "3DOJ0FPjyD4GwLmpMjrCYnNJK60="; public static final Context DEFAULT_CSV = new Context(','); public static final Context DEFAULT_TSV = new Context('\t'); private final Character separator; private final Character quoteChar; public Context(final Character separator) { this(separator, null); } public Context(final Character separator, final Character quoteChar) { this.separator = separator; this.quoteChar = quoteChar; } public char getSeparator() { return separator; } public boolean hasQuoteChar() { return quoteChar != null; } public char getQuoteChar() { return quoteChar; } private CSVReader makeReader(final Reader reader) { if (hasQuoteChar()) { return new CSVReader(reader, separator, quoteChar); } else { return new CSVReader(reader, separator); } } private CSVWriter makeWriter(final Writer writer) { if (hasQuoteChar()) { return new CSVWriter(writer, separator, quoteChar); } else { return new CSVWriter(writer, separator); } } } /** * Used to parse the server response content using the OpenCsv parser. * * @param config the configuration * @param fromServer the server content accessor * @return the parsed object */ public static Object parse(final ChainedHttpConfig config, final FromServer fromServer) { try { final Csv.Context ctx = (Csv.Context) config.actualContext(fromServer.getContentType(), Csv.Context.ID); return ctx.makeReader(fromServer.getReader()).readAll(); } catch (IOException e) {
throw new TransportingException(e);
4
UBOdin/jsqlparser
src/net/sf/jsqlparser/statement/replace/Replace.java
[ "public interface ItemsList {\r\n\tpublic void accept(ItemsListVisitor itemsListVisitor);\r\n}\r", "public interface Statement {\r\n\tpublic void accept(StatementVisitor statementVisitor);\r\n}\r", "public interface StatementVisitor {\r\n\tpublic void visit(Select select);\r\n\tpublic void visit(Delete delete);\r\n\tpublic void visit(Update update);\r\n\tpublic void visit(Insert insert);\r\n\tpublic void visit(Replace replace);\r\n\tpublic void visit(Drop drop);\r\n\tpublic void visit(Truncate truncate);\r\n\tpublic void visit(CreateTable createTable);\r\n\r\n}\r", "public class PlainSelect implements SelectBody {\r\n\tprivate Distinct distinct = null;\r\n\tprivate List<SelectItem> selectItems;\r\n\tprivate Table into;\r\n\tprivate FromItem fromItem;\r\n\tprivate List<Join> joins;\r\n\tprivate Expression where;\r\n\tprivate List<Column> groupByColumnReferences;\r\n\tprivate List<OrderByElement> orderByElements;\r\n\tprivate Expression having;\r\n\tprivate Limit limit;\r\n\tprivate Top top;\r\n\t\r\n\r\n\r\n\t/**\r\n\t * The {@link FromItem} in this query\r\n\t * @return the {@link FromItem}\r\n\t */\r\n\tpublic FromItem getFromItem() {\r\n\t\treturn fromItem;\r\n\t}\r\n\r\n\tpublic Table getInto() {\r\n\t\treturn into;\r\n\t}\r\n\r\n\t/**\r\n\t * The {@link SelectItem}s in this query (for example the A,B,C in \"SELECT A,B,C\")\r\n\t * @return a list of {@link SelectItem}s\r\n\t */\r\n\tpublic List<SelectItem> getSelectItems() {\r\n\t\treturn selectItems;\r\n\t}\r\n\r\n\tpublic Expression getWhere() {\r\n\t\treturn where;\r\n\t}\r\n\r\n\tpublic void setFromItem(FromItem item) {\r\n\t\tfromItem = item;\r\n\t}\r\n\r\n\tpublic void setInto(Table table) {\r\n\t\tinto = table;\r\n\t}\r\n\r\n\r\n\tpublic void setSelectItems(List<SelectItem> list) {\r\n\t\tselectItems = list;\r\n\t}\r\n\r\n\tpublic void setWhere(Expression where) {\r\n\t\tthis.where = where;\r\n\t}\r\n\r\n\t\r\n\t/**\r\n\t * The list of {@link Join}s\r\n\t * @return the list of {@link Join}s\r\n\t */\r\n\tpublic List<Join> getJoins() {\r\n\t\treturn joins;\r\n\t}\r\n\r\n\tpublic void setJoins(List<Join> list) {\r\n\t\tjoins = list;\r\n\t}\r\n\r\n\tpublic void accept(SelectVisitor selectVisitor){\r\n\t\tselectVisitor.visit(this);\r\n\t}\r\n\r\n\tpublic List<OrderByElement> getOrderByElements() {\r\n\t\treturn orderByElements;\r\n\t}\r\n\r\n\tpublic void setOrderByElements(List<OrderByElement> orderByElements) {\r\n\t\tthis.orderByElements = orderByElements;\r\n\t}\r\n\r\n\tpublic Limit getLimit() {\r\n\t\treturn limit;\r\n\t}\r\n\r\n\tpublic void setLimit(Limit limit) {\r\n\t\tthis.limit = limit;\r\n\t}\r\n\r\n\tpublic Top getTop() {\r\n\t\treturn top;\r\n\t}\r\n\r\n\tpublic void setTop(Top top) {\r\n\t\tthis.top = top;\r\n\t}\r\n\r\n\tpublic Distinct getDistinct() {\r\n\t\treturn distinct;\r\n\t}\r\n\r\n\tpublic void setDistinct(Distinct distinct) {\r\n\t\tthis.distinct = distinct;\r\n\t}\r\n\r\n\tpublic Expression getHaving() {\r\n\t\treturn having;\r\n\t}\r\n\r\n\tpublic void setHaving(Expression expression) {\r\n\t\thaving = expression;\r\n\t}\r\n\r\n\t/**\r\n\t * A list of {@link Expression}s of the GROUP BY clause.\r\n\t * It is null in case there is no GROUP BY clause\r\n\t * @return a list of {@link Expression}s \r\n\t */\r\n\tpublic List<Column> getGroupByColumnReferences() {\r\n\t\treturn groupByColumnReferences;\r\n\t}\r\n\r\n\tpublic void setGroupByColumnReferences(List<Column> list) {\r\n\t\tgroupByColumnReferences = list;\r\n\t}\r\n\r\n\tpublic String toString() {\r\n\t\tString sql = \"\";\r\n\r\n\t\tsql = \"SELECT \";\r\n\t\tsql += ((distinct != null)?\"\"+distinct+\" \":\"\");\r\n\t\tsql += ((top != null)?\"\"+top+\" \":\"\");\r\n\t\tsql += getStringList(selectItems);\r\n\t\tsql += \" FROM \" + fromItem;\r\n\t\tif (joins != null) {\r\n\t\t\tIterator it = joins.iterator();\r\n\t\t\twhile(it.hasNext()) {\r\n\t\t\t\tJoin join = (Join)it.next();\r\n\t\t\t\tif (join.isSimple()) {\r\n\t\t\t\t\tsql += \", \" + join;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tsql += \" \" + join;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t//sql += getFormatedList(joins, \"\", false, false);\r\n\t\tsql += ((where != null) ? \" WHERE \" + where : \"\");\r\n\t\tsql += getFormatedList(groupByColumnReferences, \"GROUP BY\");\r\n\t\tsql += ((having != null) ? \" HAVING \" + having : \"\");\r\n\t\tsql += orderByToString(orderByElements);\r\n\t\tsql += ((limit != null) ? limit+\"\" : \"\");\r\n\r\n\t\treturn sql;\r\n\t}\r\n\r\n\r\n\tpublic static String orderByToString(List<OrderByElement> orderByElements) {\r\n\t\treturn getFormatedList(orderByElements, \"ORDER BY\");\r\n\t}\r\n\r\n\t\r\n\tpublic static String getFormatedList(List list, String expression) {\r\n\t\treturn getFormatedList(list, expression, true, false);\r\n\t}\r\n\r\n\t\r\n\tpublic static String getFormatedList(List list, String expression, boolean useComma, boolean useBrackets) {\r\n\t\tString sql = getStringList(list, useComma, useBrackets);\r\n\r\n\t\tif (sql.length() > 0) {\r\n\t\t if (expression.length() > 0) {\r\n\t\t sql = \" \" + expression + \" \" + sql;\r\n\t\t } else { \r\n\t\t sql = \" \" + sql;\r\n\t\t }\r\n\t\t}\r\n\r\n\t\treturn sql;\r\n\t}\r\n\r\n\t/**\r\n\t * List the toString out put of the objects in the List comma separated. If\r\n\t * the List is null or empty an empty string is returned.\r\n\t * \r\n\t * The same as getStringList(list, true, false)\r\n\t * @see #getStringList(List, boolean, boolean)\r\n\t * @param list\r\n\t * list of objects with toString methods\r\n\t * @return comma separated list of the elements in the list\r\n\t */\r\n\tpublic static String getStringList(List list) {\r\n\t\treturn getStringList(list, true, false);\r\n\t}\r\n\r\n\t/**\r\n\t * List the toString out put of the objects in the List that can be comma separated. If\r\n\t * the List is null or empty an empty string is returned.\r\n\t * \r\n\t * @param list list of objects with toString methods\r\n\t * @param useComma true if the list has to be comma separated\r\n\t * @param useBrackets true if the list has to be enclosed in brackets\r\n\t * @return comma separated list of the elements in the list\r\n\t */\r\n\tpublic static String getStringList(List list, boolean useComma, boolean useBrackets) {\r\n\t\tString ans = \"\";\r\n\t\tString comma = \",\";\r\n\t\tif (!useComma) {\r\n\t\t comma = \"\";\r\n\t\t}\r\n\t\tif (list != null) {\r\n\t\t if (useBrackets) {\r\n\t\t ans += \"(\";\r\n\t\t }\r\n\t\t \r\n\t\t\tfor (int i = 0; i < list.size(); i++) {\r\n\t\t\t\tans += \"\" + list.get(i) + ((i < list.size() - 1) ? comma + \" \" : \"\");\r\n\t\t\t}\r\n\t\t\t\r\n\t\t if (useBrackets) {\r\n\t\t ans += \")\";\r\n\t\t }\r\n\t\t}\r\n\r\n\t\treturn ans;\r\n\t}\r\n}\r", "public class SubSelect implements FromItem, Expression, ItemsList {\r\n\tprivate SelectBody selectBody;\r\n\tprivate String alias;\r\n\r\n\tpublic void accept(FromItemVisitor fromItemVisitor) {\r\n\t\tfromItemVisitor.visit(this);\r\n\t}\r\n\r\n\tpublic SelectBody getSelectBody() {\r\n\t\treturn selectBody;\r\n\t}\r\n\r\n\tpublic void setSelectBody(SelectBody body) {\r\n\t\tselectBody = body;\r\n\t}\r\n\r\n\tpublic void accept(ExpressionVisitor expressionVisitor) {\r\n\t\texpressionVisitor.visit(this);\r\n\t}\r\n\r\n\tpublic String getAlias() {\r\n\t\treturn alias;\r\n\t}\r\n\r\n\tpublic void setAlias(String string) {\r\n\t\talias = string;\r\n\t}\r\n\r\n\tpublic void accept(ItemsListVisitor itemsListVisitor) {\r\n\t\titemsListVisitor.visit(this);\r\n\t}\r\n\r\n\tpublic String toString () {\r\n\t\treturn \"(\"+selectBody+\")\"+((alias!=null)?\" \"+alias:\"\");\r\n\t}\r\n}\r" ]
import net.sf.jsqlparser.statement.select.SubSelect; import java.util.List; import net.sf.jsqlparser.expression.*; import net.sf.jsqlparser.expression.operators.relational.ItemsList; import net.sf.jsqlparser.schema.*; import net.sf.jsqlparser.statement.Statement; import net.sf.jsqlparser.statement.StatementVisitor; import net.sf.jsqlparser.statement.select.PlainSelect;
/* ================================================================ * JSQLParser : java based sql parser * ================================================================ * * Project Info: http://jsqlparser.sourceforge.net * Project Lead: Leonardo Francalanci ([email protected]); * * (C) Copyright 2004, by Leonardo Francalanci * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ package net.sf.jsqlparser.statement.replace; /** * The replace statement. */ public class Replace implements Statement { private Table table; private List<Column> columns; private ItemsList itemsList; private List<Expression> expressions; private boolean useValues = true; public void accept(StatementVisitor statementVisitor) { statementVisitor.visit(this); } public Table getTable() { return table; } public void setTable(Table name) { table = name; } /** * A list of {@link net.sf.jsqlparser.schema.Column}s either from a "REPLACE mytab (col1, col2) [...]" or a "REPLACE mytab SET col1=exp1, col2=exp2". * @return a list of {@link net.sf.jsqlparser.schema.Column}s */ public List<Column> getColumns() { return columns; } /** * An {@link ItemsList} (either from a "REPLACE mytab VALUES (exp1,exp2)" or a "REPLACE mytab SELECT * FROM mytab2") * it is null in case of a "REPLACE mytab SET col1=exp1, col2=exp2" * @return The target relation */ public ItemsList getItemsList() { return itemsList; } public void setColumns(List<Column> list) { columns = list; } public void setItemsList(ItemsList list) { itemsList = list; } /** * A list of {@link net.sf.jsqlparser.expression.Expression}s (from a "REPLACE mytab SET col1=exp1, col2=exp2"). <br> * it is null in case of a "REPLACE mytab (col1, col2) [...]" * @return The replacement expressions */ public List<Expression> getExpressions() { return expressions; } public void setExpressions(List<Expression> list) { expressions = list; } public boolean isUseValues() { return useValues; } public void setUseValues(boolean useValues) { this.useValues = useValues; } public String toString() { String sql = "REPLACE "+table; if(expressions != null && columns != null ) { //the SET col1=exp1, col2=exp2 case sql += " SET "; //each element from expressions match up with a column from columns. for (int i = 0, s = columns.size(); i < s; i++) { sql += ""+columns.get(i)+"="+expressions.get(i); sql += (i<s-1)?", ":""; } } else if( columns != null ) { //the REPLACE mytab (col1, col2) [...] case
sql += " "+PlainSelect.getStringList(columns, true, true);
3
yyon/grapplemod
main/java/com/yyon/grapplinghook/blocks/BlockGrappleModifier.java
[ "@Config(modid=\"grapplemod\", name=\"grappling_hook\", category=\"\")\npublic class GrappleConfig {\n\tpublic static class Config {\n\t\t// rope\n\t\tpublic double default_maxlen = 30;\n\t\tpublic boolean default_phaserope = false;\n\t\tpublic boolean default_sticky = false;\n\t\t// hook thrower\n\t\tpublic double default_hookgravity = 1F;\n\t\tpublic double default_throwspeed = 2F;\n\t\tpublic boolean default_reelin = true;\n\t\tpublic double default_verticalthrowangle = 0F;\n\t\tpublic double default_sneakingverticalthrowangle = 0F;\n\t\tpublic boolean default_detachonkeyrelease = false;\n\t\t// motor\n\t\tpublic boolean default_motor = false;\n\t\tpublic double default_motormaxspeed = 4;\n\t\tpublic double default_motoracceleration = 0.2;\n\t\tpublic boolean default_motorwhencrouching = false;\n\t\tpublic boolean default_motorwhennotcrouching = true;\n\t\tpublic boolean default_smartmotor = false;\n\t\tpublic boolean default_motordampener = false;\n\t\tpublic boolean default_pullbackwards = true;\n\t\t// swing speed\n\t\tpublic double default_playermovementmult = 1;\n\t\t// ender staff\n\t\tpublic boolean default_enderstaff = false;\n\t\t// forcefield\n\t\tpublic boolean default_repel = false;\n\t\tpublic double default_repelforce = 1;\n\t\t// hook magnet\n\t\tpublic boolean default_attract = false;\n\t\tpublic double default_attractradius = 3;\n\t\t// double hook\n\t\tpublic boolean default_doublehook = false;\n\t\tpublic boolean default_smartdoublemotor = true;\n\t\tpublic double default_angle = 20;\n\t\tpublic double default_sneakingangle = 10;\n\t\tpublic boolean default_oneropepull = false;\n\t\t// rocket\n\t\tpublic boolean default_rocketenabled = false;\n\t\tpublic double default_rocket_force = 1;\n\t\tpublic double default_rocket_active_time = 0.5;\n\t\tpublic double default_rocket_refuel_ratio = 15;\n\t\tpublic double default_rocket_vertical_angle = 0;\n\t\t\n\n\t\t// upgraded values for alternativegrapple items\n\t\tpublic double upgraded_throwspeed = 3.5;\n\t\tpublic double upgraded_maxlen = 60;\n\n\t\t// rope\n\t\tpublic double max_maxlen = 60;\n\t\t// hook thrower\n\t\tpublic double max_hookgravity = 100;\n\t\tpublic double max_throwspeed = 5;\n\t\tpublic double max_verticalthrowangle = 45;\n\t\tpublic double max_sneakingverticalthrowangle = 45;\n\t\t// motor\n\t\tpublic double max_motormaxspeed = 4;\n\t\tpublic double max_motoracceleration = 0.2;\n\t\t// swing speed\n\t\tpublic double max_playermovementmult = 2;\n\t\t// forcefield\n\t\tpublic double max_repelforce = 1;\n\t\t// hook magnet\n\t\tpublic double max_attractradius = 3;\n\t\t// double hook\n\t\tpublic double max_angle = 45;\n\t\tpublic double max_sneakingangle = 45;\n\t\t\n\t\t\n\t\t// rope\n\t\tpublic double max_upgrade_maxlen = 200;\n\t\t// hook thrower\n\t\tpublic double max_upgrade_hookgravity = 100;\n\t\tpublic double max_upgrade_throwspeed = 20;\n\t\tpublic double max_upgrade_verticalthrowangle = 90;\n\t\tpublic double max_upgrade_sneakingverticalthrowangle = 90;\n\t\t// motorversion\n\t\tpublic double max_upgrade_motormaxspeed = 10;\n\t\tpublic double max_upgrade_motoracceleration = 1;\n\t\t// swing speed\n\t\tpublic double max_upgrade_playermovementmult = 5;\n\t\t// forcefield\n\t\tpublic double max_upgrade_repelforce = 5;\n\t\t// hook magnet\n\t\tpublic double max_upgrade_attractradius = 10;\n\t\t// double hook\n\t\tpublic double max_upgrade_angle = 90;\n\t\tpublic double max_upgrade_sneakingangle = 90;\n\t\t// rocket\n\t\tpublic double max_rocket_active_time = 0.5;\n\t\tpublic double max_upgrade_rocket_active_time = 20;\n\t\tpublic double max_rocket_force = 1;\n\t\tpublic double max_upgrade_rocket_force = 5;\n\n\t\tpublic double min_rocket_refuel_ratio = 15;\n\t\tpublic double min_upgrade_rocket_refuel_ratio = 1;\n\t\tpublic double max_rocket_refuel_ratio = 30;\n\t\tpublic double max_upgrade_rocket_refuel_ratio = 30;\n\n\t\tpublic double min_hookgravity = 1;\n\t\tpublic double min_upgrade_hookgravity = 0;\n\t\t\n\t\tpublic double max_upgrade_rocket_vertical_angle = 90;\n\t\tpublic double max_rocket_vertical_angle = 90;\n\t\t\n\t\tpublic String grapplingBlocks = \"any\";\n\t\tpublic String grapplingNonBlocks = \"none\";\n\t\t\n\t\t// rope\n\t\tpublic int enable_maxlen = 0;\n\t\tpublic int enable_phaserope = 0;\n\t\tpublic int enable_sticky = 0;\n\t\t// hook thrower\n\t\tpublic int enable_hookgravity = 0;\n\t\tpublic int enable_throwspeed = 0;\n\t\tpublic int enable_reelin = 0;\n\t\tpublic int enable_verticalthrowangle = 0;\n\t\tpublic int enable_sneakingverticalthrowangle = 0;\n\t\tpublic int enable_detachonkeyrelease = 0;\n\t\t// motor\n\t\tpublic int enable_motor = 0;\n\t\tpublic int enable_motormaxspeed = 0;\n\t\tpublic int enable_motoracceleration = 0;\n\t\tpublic int enable_motorwhencrouching = 0;\n\t\tpublic int enable_motorwhennotcrouching = 0;\n\t\tpublic int enable_smartmotor = 0;\n\t\tpublic int enable_motordampener = 1;\n\t\tpublic int enable_pullbackwards = 0;\n\t\t// swing speed\n\t\tpublic int enable_playermovementmult = 0;\n\t\t// ender staff\n\t\tpublic int enable_enderstaff = 0;\n\t\t// forcefield\n\t\tpublic int enable_repel = 0;\n\t\tpublic int enable_repelforce = 0;\n\t\t// hook magnet\n\t\tpublic int enable_attract = 0;\n\t\tpublic int enable_attractradius = 0;\n\t\t// double hook\n\t\tpublic int enable_doublehook = 0;\n\t\tpublic int enable_smartdoublemotor = 0;\n\t\tpublic int enable_angle = 0;\n\t\tpublic int enable_sneakingangle = 0;\n\t\tpublic int enable_oneropepull = 0;\n\t\t// rocket\n\t\tpublic int enable_rocket = 0;\n\t\tpublic int enable_rocket_force = 0;\n\t\tpublic int enable_rocket_active_time = 0;\n\t\tpublic int enable_rocket_refuel_ratio = 0;\n\t\tpublic int enable_rocket_vertical_angle = 0;\n\n\t\t\n\t\tpublic boolean longfallbootsrecipe = true;\n\t\t\n\t\tpublic boolean hookaffectsentities = true;\n\n\t\t// ender staff\n\t\tpublic double ender_staff_strength = 1.5;\n\t\tpublic int ender_staff_recharge = 100;\n\t\t\n\t\tpublic double wall_jump_up = 0.7;\n\t\tpublic double wall_jump_side = 0.4;\n\t\t\n\t\tpublic double max_wallrun_time = 3;\n\t\t\n\t\tpublic double doublejumpforce = 0.8;\n\t\tpublic double slidingjumpforce = 0.6;\n\t\tpublic double wallrun_speed = 0.1;\n\t\tpublic double wallrun_max_speed = 0.7;\n\t\tpublic double wallrun_drag = 0.01;\n\t\tpublic double wallrun_min_speed = 0;\n\t\tpublic double sliding_friction = 1 / 150F;\n\t\tpublic boolean override_allowflight = true;\n\t\t\n\t\tpublic double airstrafe_max_speed = 0.7;\n\t\t\n\t\tpublic double rope_snap_buffer = 5;\n\t\tpublic int default_durability = 500;\n\t\tpublic double rope_jump_power = 1;\n\t\tpublic boolean rope_jump_at_angle = false;\n\t\tpublic double sliding_min_speed = 0.15;\n\t\tpublic double sliding_end_min_speed = 0.01;\n\t\tpublic boolean doublejump_relative_to_falling = false;\n\t\t\n\t\tpublic boolean dont_override_movement_in_air = false;\n\t\t\n\t\tpublic double dont_doublejump_if_falling_faster_than = 999999999.0;\n\t\tpublic double rope_jump_cooldown_s = 0;\n\t\tpublic double climb_speed = 0.3;\n\t\t\n\t\tpublic int enchant_rarity_double_jump = 0;\n\t\tpublic int enchant_rarity_sliding = 0;\n\t\tpublic int enchant_rarity_wallrun = 0;\n\t\tpublic double airstrafe_acceleration = 0.015;\n\t\t\n\t\tpublic String grappleBreakBlocks = \"none\";\n\t\tpublic String grappleIgnoreBlocks = \"minecraft:tallgrass,minecraft:double_plant\";\n\t}\n\t\n\tpublic static Config options = new Config(); // local options\n\t\n\tprivate static Config server_options = null;\n\t\n\tpublic static class ClientConfig {\n\t\tpublic double wallrun_sound_effect_time_s = 0.35;\n\t\tpublic float wallrun_camera_tilt_degrees = 10;\n\t\tpublic float wallrun_camera_animation_s = 0.5f;\n\t\tpublic float wallrun_sound_volume = 1.0F;\n\t\tpublic float doublejump_sound_volume = 1.0F;\n\t\tpublic float slide_sound_volume = 1.0F;\n\t\tpublic float wallrunjump_sound_volume = 1.0F;\n\t\tpublic float enderstaff_sound_volume = 1.0F;\n\t\tpublic float rocket_sound_volume = 1.0F;\n\t}\n\t\n\tpublic static ClientConfig client_options = new ClientConfig(); // client-only options, don't need to sync with server\n\n\tpublic static Config getconf() {\n\t\tif (server_options == null) {\n\t\t\treturn options;\n\t\t} else {\n\t\t\treturn server_options;\n\t\t}\n\t}\n\t\n\tpublic static void setserveroptions(Config newserveroptions) {\n\t\tserver_options = newserveroptions;\n\t}\n}", "public class GrappleCustomization {\n\tpublic static final String[] booleanoptions = new String[] {\"phaserope\", \"motor\", \"motorwhencrouching\", \"motorwhennotcrouching\", \"smartmotor\", \"enderstaff\", \"repel\", \"attract\", \"doublehook\", \"smartdoublemotor\", \"motordampener\", \"reelin\", \"pullbackwards\", \"oneropepull\", \"sticky\", \"detachonkeyrelease\", \"rocket\"};\n\tpublic static final String[] doubleoptions = new String[] {\"maxlen\", \"hookgravity\", \"throwspeed\", \"motormaxspeed\", \"motoracceleration\", \"playermovementmult\", \"repelforce\", \"attractradius\", \"angle\", \"sneakingangle\", \"verticalthrowangle\", \"sneakingverticalthrowangle\", \"rocket_force\", \"rocket_active_time\", \"rocket_refuel_ratio\", \"rocket_vertical_angle\"};\n\t\n\t// rope\n\tpublic double maxlen = GrappleConfig.getconf().default_maxlen;\n\tpublic boolean phaserope = GrappleConfig.getconf().default_phaserope;\n\tpublic boolean sticky = GrappleConfig.getconf().default_sticky;\n\n\t// hook thrower\n\tpublic double hookgravity = GrappleConfig.getconf().default_hookgravity;\n\tpublic double throwspeed = GrappleConfig.getconf().default_throwspeed;\n\tpublic boolean reelin = GrappleConfig.getconf().default_reelin;\n\tpublic double verticalthrowangle = GrappleConfig.getconf().default_verticalthrowangle;\n\tpublic double sneakingverticalthrowangle = GrappleConfig.getconf().default_sneakingverticalthrowangle;\n\tpublic boolean detachonkeyrelease = GrappleConfig.getconf().default_detachonkeyrelease;\n\n\t// motor\n\tpublic boolean motor = GrappleConfig.getconf().default_motor;\n\tpublic double motormaxspeed = GrappleConfig.getconf().default_motormaxspeed;\n\tpublic double motoracceleration = GrappleConfig.getconf().default_motoracceleration;\n\tpublic boolean motorwhencrouching = GrappleConfig.getconf().default_motorwhencrouching;\n\tpublic boolean motorwhennotcrouching = GrappleConfig.getconf().default_motorwhennotcrouching;\n\tpublic boolean smartmotor = GrappleConfig.getconf().default_smartmotor;\n\tpublic boolean motordampener = GrappleConfig.getconf().default_motordampener;\n\tpublic boolean pullbackwards = GrappleConfig.getconf().default_pullbackwards;\n\t\n\t// swing speed\n\tpublic double playermovementmult = GrappleConfig.getconf().default_playermovementmult;\n\n\t// ender staff\n\tpublic boolean enderstaff = GrappleConfig.getconf().default_enderstaff;\n\n\t// forcefield\n\tpublic boolean repel = GrappleConfig.getconf().default_repel;\n\tpublic double repelforce = GrappleConfig.getconf().default_repelforce;\n\t\n\t// hook magnet\n\tpublic boolean attract = GrappleConfig.getconf().default_attract;\n\tpublic double attractradius = GrappleConfig.getconf().default_attractradius;\n\t\n\t// double hook\n\tpublic boolean doublehook = GrappleConfig.getconf().default_doublehook;\n\tpublic boolean smartdoublemotor = GrappleConfig.getconf().default_smartdoublemotor;\n\tpublic double angle = GrappleConfig.getconf().default_angle;\n\tpublic double sneakingangle = GrappleConfig.getconf().default_sneakingangle;\n\tpublic boolean oneropepull = GrappleConfig.getconf().default_oneropepull;\n\t\n\t// rocket\n\tpublic boolean rocket = GrappleConfig.getconf().default_rocketenabled;\n\tpublic double rocket_force = GrappleConfig.getconf().default_rocket_force;\n\tpublic double rocket_active_time = GrappleConfig.getconf().default_rocket_active_time;\n\tpublic double rocket_refuel_ratio = GrappleConfig.getconf().default_rocket_refuel_ratio;\n\tpublic double rocket_vertical_angle = GrappleConfig.getconf().default_rocket_vertical_angle;\n\t\n\tpublic GrappleCustomization() {\n\t\t\n\t}\n\t\n\tpublic NBTTagCompound writeNBT() {\n\t\tNBTTagCompound compound = new NBTTagCompound();\n\t\tfor (String option : booleanoptions) {\n\t\t\tcompound.setBoolean(option, this.getBoolean(option));\n\t\t}\n\t\tfor (String option : doubleoptions) {\n\t\t\tcompound.setDouble(option, this.getDouble(option));\n\t\t}\n\t\treturn compound;\n\t}\n\t\n\tpublic void loadNBT(NBTTagCompound compound) {\n\t\tfor (String option : booleanoptions) {\n\t\t\tif (compound.hasKey(option)) {\n\t\t\t\tthis.setBoolean(option, compound.getBoolean(option));\n\t\t\t}\n\t\t}\n\t\tfor (String option : doubleoptions) {\n\t\t\tif (compound.hasKey(option)) {\n\t\t\t\tthis.setDouble(option, compound.getDouble(option));\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void setBoolean(String option, boolean bool) {\n\t\tif (option.equals(\"phaserope\")) {this.phaserope = bool;}\n\t\telse if (option.equals(\"motor\")) {this.motor = bool;}\n\t\telse if (option.equals(\"motorwhencrouching\")) {this.motorwhencrouching = bool;}\n\t\telse if (option.equals(\"motorwhennotcrouching\")) {this.motorwhennotcrouching = bool;}\n\t\telse if (option.equals(\"smartmotor\")) {this.smartmotor = bool;}\n\t\telse if (option.equals(\"enderstaff\")) {this.enderstaff = bool;}\n\t\telse if (option.equals(\"repel\")) {this.repel = bool;}\n\t\telse if (option.equals(\"attract\")) {this.attract = bool;}\n\t\telse if (option.equals(\"doublehook\")) {this.doublehook = bool;}\n\t\telse if (option.equals(\"smartdoublemotor\")) {this.smartdoublemotor = bool;}\n\t\telse if (option.equals(\"motordampener\")) {this.motordampener = bool;}\n\t\telse if (option.equals(\"reelin\")) {this.reelin = bool;}\n\t\telse if (option.equals(\"pullbackwards\")) {this.pullbackwards = bool;}\n\t\telse if (option.equals(\"oneropepull\")) {this.oneropepull = bool;}\n\t\telse if (option.equals(\"sticky\")) {this.sticky = bool;}\n\t\telse if (option.equals(\"detachonkeyrelease\")) {this.detachonkeyrelease = bool;}\n\t\telse if (option.equals(\"rocket\")) {this.rocket = bool;}\n\t\telse {System.out.println(\"Option doesn't exist: \" + option);}\n\t}\n\t\n\tpublic boolean getBoolean(String option) {\n\t\tif (option.equals(\"phaserope\")) {return this.phaserope;}\n\t\telse if (option.equals(\"motor\")) {return this.motor;}\n\t\telse if (option.equals(\"motorwhencrouching\")) {return this.motorwhencrouching;}\n\t\telse if (option.equals(\"motorwhennotcrouching\")) {return this.motorwhennotcrouching;}\n\t\telse if (option.equals(\"smartmotor\")) {return this.smartmotor;}\n\t\telse if (option.equals(\"enderstaff\")) {return this.enderstaff;}\n\t\telse if (option.equals(\"repel\")) {return this.repel;}\n\t\telse if (option.equals(\"attract\")) {return this.attract;}\n\t\telse if (option.equals(\"doublehook\")) {return this.doublehook;}\n\t\telse if (option.equals(\"smartdoublemotor\")) {return this.smartdoublemotor;}\n\t\telse if (option.equals(\"motordampener\")) {return this.motordampener;}\n\t\telse if (option.equals(\"reelin\")) {return this.reelin;}\n\t\telse if (option.equals(\"pullbackwards\")) {return this.pullbackwards;}\n\t\telse if (option.equals(\"oneropepull\")) {return this.oneropepull;}\n\t\telse if (option.equals(\"sticky\")) {return this.sticky;}\n\t\telse if (option.equals(\"detachonkeyrelease\")) {return this.detachonkeyrelease;}\n\t\telse if (option.equals(\"rocket\")) {return this.rocket;}\n\t\tSystem.out.println(\"Option doesn't exist: \" + option);\n\t\treturn false;\n\t}\n\t\n\tpublic void setDouble(String option, double d) {\n\t\tif (option.equals(\"maxlen\")) {this.maxlen = d;}\n\t\telse if (option.equals(\"hookgravity\")) {this.hookgravity = d;}\n\t\telse if (option.equals(\"throwspeed\")) {this.throwspeed = d;}\n\t\telse if (option.equals(\"motormaxspeed\")) {this.motormaxspeed = d;}\n\t\telse if (option.equals(\"motoracceleration\")) {this.motoracceleration = d;}\n\t\telse if (option.equals(\"playermovementmult\")) {this.playermovementmult = d;}\n\t\telse if (option.equals(\"repelforce\")) {this.repelforce = d;}\n\t\telse if (option.equals(\"attractradius\")) {this.attractradius = d;}\n\t\telse if (option.equals(\"angle\")) {this.angle = d;}\n\t\telse if (option.equals(\"sneakingangle\")) {this.sneakingangle = d;}\n\t\telse if (option.equals(\"verticalthrowangle\")) {this.verticalthrowangle = d;}\n\t\telse if (option.equals(\"sneakingverticalthrowangle\")) {this.sneakingverticalthrowangle = d;}\n\t\telse if (option.equals(\"rocket_force\")) {this.rocket_force = d;}\n\t\telse if (option.equals(\"rocket_active_time\")) {this.rocket_active_time = d;}\n\t\telse if (option.equals(\"rocket_refuel_ratio\")) {this.rocket_refuel_ratio = d;}\n\t\telse if (option.equals(\"rocket_vertical_angle\")) {this.rocket_vertical_angle = d;}\n\t\telse {System.out.println(\"Option doesn't exist: \" + option);}\n\t}\n\t\n\tpublic double getDouble(String option) {\n\t\tif (option.equals(\"maxlen\")) {return maxlen;}\n\t\telse if (option.equals(\"hookgravity\")) {return hookgravity;}\n\t\telse if (option.equals(\"throwspeed\")) {return throwspeed;}\n\t\telse if (option.equals(\"motormaxspeed\")) {return motormaxspeed;}\n\t\telse if (option.equals(\"motoracceleration\")) {return motoracceleration;}\n\t\telse if (option.equals(\"playermovementmult\")) {return playermovementmult;}\n\t\telse if (option.equals(\"repelforce\")) {return repelforce;}\n\t\telse if (option.equals(\"attractradius\")) {return attractradius;}\n\t\telse if (option.equals(\"angle\")) {return angle;}\n\t\telse if (option.equals(\"sneakingangle\")) {return sneakingangle;}\n\t\telse if (option.equals(\"verticalthrowangle\")) {return verticalthrowangle;}\n\t\telse if (option.equals(\"sneakingverticalthrowangle\")) {return sneakingverticalthrowangle;}\n\t\telse if (option.equals(\"rocket_force\")) {return this.rocket_force;}\n\t\telse if (option.equals(\"rocket_active_time\")) {return rocket_active_time;}\n\t\telse if (option.equals(\"rocket_refuel_ratio\")) {return rocket_refuel_ratio;}\n\t\telse if (option.equals(\"rocket_vertical_angle\")) {return rocket_vertical_angle;}\n\t\tSystem.out.println(\"Option doesn't exist: \" + option);\n\t\treturn 0;\n\t}\n\t\n\tpublic void writeToBuf(ByteBuf buf) {\n\t\tfor (String option : booleanoptions) {\n\t\t\tbuf.writeBoolean(this.getBoolean(option));\n\t\t}\n\t\tfor (String option : doubleoptions) {\n\t\t\tbuf.writeDouble(this.getDouble(option));\n\t\t}\n\t}\n\t\n\tpublic void readFromBuf(ByteBuf buf) {\n\t\tfor (String option : booleanoptions) {\n\t\t\tthis.setBoolean(option, buf.readBoolean());\n\t\t}\n\t\tfor (String option : doubleoptions) {\n\t\t\tthis.setDouble(option, buf.readDouble());\n\t\t}\n\t}\n\n\tpublic String getName(String option) {\n\t\treturn \"grapplecustomization.\" + option + \".name\";\n\t}\n\t\n\tpublic String getDescription(String option) {\n\t\treturn \"grapplecustomization.\" + option + \".desc\";\n\t}\n\t\n\tpublic boolean isoptionvalid(String option) {\n\t\tif (option == \"motormaxspeed\" || option == \"motoracceleration\" || option == \"motorwhencrouching\" || option == \"motorwhennotcrouching\" || option == \"smartmotor\" || option == \"motordampener\" || option == \"pullbackwards\") {\n\t\t\treturn this.motor;\n\t\t}\n\t\t\n\t\tif (option == \"sticky\") {\n\t\t\treturn !this.phaserope;\n\t\t}\n\t\t\n\t\telse if (option == \"sneakingangle\") {\n\t\t\treturn this.doublehook && !this.reelin;\n\t\t}\n\t\t\n\t\telse if (option == \"repelforce\") {\n\t\t\treturn this.repel;\n\t\t}\n\t\t\n\t\telse if (option == \"attractradius\") {\n\t\t\treturn this.attract;\n\t\t}\n\t\t\n\t\telse if (option == \"angle\") {\n\t\t\treturn this.doublehook;\n\t\t}\n\t\t\n\t\telse if (option == \"smartdoublemotor\" || option == \"oneropepull\") {\n\t\t\treturn this.doublehook && this.motor;\n\t\t}\n\t\t\n\t\telse if (option == \"rocket_active_time\" || option == \"rocket_refuel_ratio\" || option == \"rocket_force\" || option == \"rocket_vertical_angle\") {\n\t\t\treturn this.rocket;\n\t\t}\n\t\t\n\t\treturn true;\n\t}\n\t\n\tpublic double getMax(String option, int upgrade) {\n\t\tif (option.equals(\"maxlen\")) {return upgrade == 1 ? GrappleConfig.getconf().max_upgrade_maxlen : GrappleConfig.getconf().max_maxlen;}\n\t\telse if (option.equals(\"hookgravity\")) {return upgrade == 1 ? GrappleConfig.getconf().max_upgrade_hookgravity : GrappleConfig.getconf().max_hookgravity;}\n\t\telse if (option.equals(\"throwspeed\")) {return upgrade == 1 ? GrappleConfig.getconf().max_upgrade_throwspeed : GrappleConfig.getconf().max_throwspeed;}\n\t\telse if (option.equals(\"motormaxspeed\")) {return upgrade == 1 ? GrappleConfig.getconf().max_upgrade_motormaxspeed : GrappleConfig.getconf().max_motormaxspeed;}\n\t\telse if (option.equals(\"motoracceleration\")) {return upgrade == 1 ? GrappleConfig.getconf().max_upgrade_motoracceleration : GrappleConfig.getconf().max_motoracceleration;}\n\t\telse if (option.equals(\"playermovementmult\")) {return upgrade == 1 ? GrappleConfig.getconf().max_upgrade_playermovementmult : GrappleConfig.getconf().max_playermovementmult;}\n\t\telse if (option.equals(\"repelforce\")) {return upgrade == 1 ? GrappleConfig.getconf().max_upgrade_repelforce : GrappleConfig.getconf().max_repelforce;}\n\t\telse if (option.equals(\"attractradius\")) {return upgrade == 1 ? GrappleConfig.getconf().max_upgrade_attractradius : GrappleConfig.getconf().max_attractradius;}\n\t\telse if (option.equals(\"angle\")) {return upgrade == 1 ? GrappleConfig.getconf().max_upgrade_angle : GrappleConfig.getconf().max_angle;}\n\t\telse if (option.equals(\"sneakingangle\")) {return upgrade == 1 ? GrappleConfig.getconf().max_upgrade_sneakingangle : GrappleConfig.getconf().max_sneakingangle;}\n\t\telse if (option.equals(\"verticalthrowangle\")) {return upgrade == 1 ? GrappleConfig.getconf().max_upgrade_verticalthrowangle : GrappleConfig.getconf().max_verticalthrowangle;}\n\t\telse if (option.equals(\"sneakingverticalthrowangle\")) {return upgrade == 1 ? GrappleConfig.getconf().max_upgrade_sneakingverticalthrowangle : GrappleConfig.getconf().max_sneakingverticalthrowangle;}\n\t\telse if (option.equals(\"rocket_force\")) {return upgrade == 1 ? GrappleConfig.getconf().max_upgrade_rocket_force: GrappleConfig.getconf().max_rocket_force;}\n\t\telse if (option.equals(\"rocket_active_time\")) {return upgrade == 1 ? GrappleConfig.getconf().max_upgrade_rocket_active_time : GrappleConfig.getconf().max_rocket_active_time;}\n\t\telse if (option.equals(\"rocket_refuel_ratio\")) {return upgrade == 1 ? GrappleConfig.getconf().max_upgrade_rocket_refuel_ratio : GrappleConfig.getconf().max_rocket_refuel_ratio;}\n\t\telse if (option.equals(\"rocket_vertical_angle\")) {return upgrade == 1 ? GrappleConfig.getconf().max_upgrade_rocket_vertical_angle : GrappleConfig.getconf().max_rocket_vertical_angle;}\n\t\tSystem.out.println(\"Option doesn't exist: \" + option);\n\t\treturn 0;\n\t}\n\t\n\tpublic double getMin(String option, int upgrade) {\n\t\tif (option.equals(\"hookgravity\")) {return upgrade == 1 ? GrappleConfig.getconf().min_upgrade_hookgravity : GrappleConfig.getconf().min_hookgravity;}\n\t\tif (option.equals(\"rocket_refuel_ratio\")) {return upgrade == 1 ? GrappleConfig.getconf().min_upgrade_rocket_refuel_ratio : GrappleConfig.getconf().min_rocket_refuel_ratio;}\n\t\t\n\t\treturn 0;\n\t}\n\t\n\tpublic int optionEnabled(String option) {\n\t\tif (option.equals(\"maxlen\")) {return GrappleConfig.getconf().enable_maxlen;}\n\t\telse if (option.equals(\"phaserope\")) {return GrappleConfig.getconf().enable_phaserope;}\n\t\telse if (option.equals(\"hookgravity\")) {return GrappleConfig.getconf().enable_hookgravity;}\n\t\telse if (option.equals(\"throwspeed\")) {return GrappleConfig.getconf().enable_throwspeed;}\n\t\telse if (option.equals(\"reelin\")) {return GrappleConfig.getconf().enable_reelin;}\n\t\telse if (option.equals(\"verticalthrowangle\")) {return GrappleConfig.getconf().enable_verticalthrowangle;}\n\t\telse if (option.equals(\"motor\")) {return GrappleConfig.getconf().enable_motor;}\n\t\telse if (option.equals(\"motormaxspeed\")) {return GrappleConfig.getconf().enable_motormaxspeed;}\n\t\telse if (option.equals(\"motoracceleration\")) {return GrappleConfig.getconf().enable_motoracceleration;}\n\t\telse if (option.equals(\"motorwhencrouching\")) {return GrappleConfig.getconf().enable_motorwhencrouching;}\n\t\telse if (option.equals(\"motorwhennotcrouching\")) {return GrappleConfig.getconf().enable_motorwhennotcrouching;}\n\t\telse if (option.equals(\"smartmotor\")) {return GrappleConfig.getconf().enable_smartmotor;}\n\t\telse if (option.equals(\"motordampener\")) {return GrappleConfig.getconf().enable_motordampener;}\n\t\telse if (option.equals(\"pullbackwards\")) {return GrappleConfig.getconf().enable_pullbackwards;}\n\t\telse if (option.equals(\"playermovementmult\")) {return GrappleConfig.getconf().enable_playermovementmult;}\n\t\telse if (option.equals(\"enderstaff\")) {return GrappleConfig.getconf().enable_enderstaff;}\n\t\telse if (option.equals(\"repel\")) {return GrappleConfig.getconf().enable_repel;}\n\t\telse if (option.equals(\"repelforce\")) {return GrappleConfig.getconf().enable_repelforce;}\n\t\telse if (option.equals(\"attract\")) {return GrappleConfig.getconf().enable_attract;}\n\t\telse if (option.equals(\"attractradius\")) {return GrappleConfig.getconf().enable_attractradius;}\n\t\telse if (option.equals(\"doublehook\")) {return GrappleConfig.getconf().enable_doublehook;}\n\t\telse if (option.equals(\"smartdoublemotor\")) {return GrappleConfig.getconf().enable_smartdoublemotor;}\n\t\telse if (option.equals(\"angle\")) {return GrappleConfig.getconf().enable_angle;}\n\t\telse if (option.equals(\"sneakingangle\")) {return GrappleConfig.getconf().enable_sneakingangle;}\n\t\telse if (option.equals(\"oneropepull\")) {return GrappleConfig.getconf().enable_oneropepull;}\n\t\telse if (option.equals(\"sneakingverticalthrowangle\")) {return GrappleConfig.getconf().enable_sneakingverticalthrowangle;}\n\t\telse if (option.equals(\"sticky\")) {return GrappleConfig.getconf().enable_sticky;}\n\t\telse if (option.equals(\"detachonkeyrelease\")) {return GrappleConfig.getconf().enable_detachonkeyrelease;}\n\t\telse if (option.equals(\"rocket\")) {return GrappleConfig.getconf().enable_rocket;}\n\t\telse if (option.equals(\"rocket_force\")) {return GrappleConfig.getconf().enable_rocket_force;}\n\t\telse if (option.equals(\"rocket_active_time\")) {return GrappleConfig.getconf().enable_rocket_active_time;}\n\t\telse if (option.equals(\"rocket_refuel_ratio\")) {return GrappleConfig.getconf().enable_rocket_refuel_ratio;}\n\t\telse if (option.equals(\"rocket_vertical_angle\")) {return GrappleConfig.getconf().enable_rocket_vertical_angle;}\n\t\tSystem.out.println(\"Unknown option\");\n\t\treturn 0;\n\t}\n}", "@Mod(modid = grapplemod.MODID, version = grapplemod.VERSION)\npublic class grapplemod {\n\n\tpublic grapplemod(){}\n\n public static final String MODID = \"grapplemod\";\n \n public static final String VERSION = \"1.12.2-v12.2\";\n\n public static Item grapplebowitem;\n public static Item motorhookitem;\n public static Item smarthookitem;\n public static Item doublemotorhookitem;\n public static Item rocketdoublemotorhookitem;\n public static Item enderhookitem;\n public static Item magnethookitem;\n public static Item rockethookitem;\n public static Item launcheritem;\n public static Item repelleritem;\n\n public static Item baseupgradeitem;\n public static Item doubleupgradeitem;\n public static Item forcefieldupgradeitem;\n public static Item magnetupgradeitem;\n public static Item motorupgradeitem;\n public static Item ropeupgradeitem;\n public static Item staffupgradeitem;\n public static Item swingupgradeitem;\n public static Item throwupgradeitem;\n public static Item limitsupgradeitem;\n public static Item rocketupgradeitem;\n\n public static Item longfallboots;\n \n public static final EnumEnchantmentType GRAPPLEENCHANTS_FEET = EnumHelper.addEnchantmentType(\"GRAPPLEENCHANTS_FEET\", (item) -> item instanceof ItemArmor && ((ItemArmor)item).armorType == EntityEquipmentSlot.FEET);\n \n public static WallrunEnchantment wallrunenchantment;\n public static DoublejumpEnchantment doublejumpenchantment;\n public static SlidingEnchantment slidingenchantment;\n\n\tpublic static Object instance;\n\t\n\tpublic static SimpleNetworkWrapper network;\n\t\n\tpublic static HashMap<Integer, grappleController> controllers = new HashMap<Integer, grappleController>(); // client side\n\tpublic static HashMap<BlockPos, grappleController> controllerpos = new HashMap<BlockPos, grappleController>();\n\tpublic static HashSet<Integer> attached = new HashSet<Integer>(); // server side\n\t\n\tpublic static HashMap<Integer, HashSet<grappleArrow>> allarrows = new HashMap<Integer, HashSet<grappleArrow>>(); // server side\n\t\n\tprivate static int controllerid = 0;\n\tpublic static int GRAPPLEID = controllerid++;\n\tpublic static int REPELID = controllerid++;\n\tpublic static int AIRID = controllerid++;\n\t\t\n\tpublic static boolean anyblocks = true;\n\tpublic static HashSet<Block> grapplingblocks;\n\tpublic static boolean removeblocks = false;\n\tpublic static HashSet<Block> grapplingbreaksblocks;\n\tpublic static boolean anybreakblocks = false;\n\tpublic static HashSet<Block> grapplingignoresblocks;\n\tpublic static boolean anyignoresblocks = false;\n\t\n\tpublic static Block blockGrappleModifier;\n\tpublic static ItemBlock itemBlockGrappleModifier;\n\t\n\tpublic ResourceLocation resourceLocation;\n\t\n\tpublic enum upgradeCategories {\n\t\tROPE (\"Rope\"), \n\t\tTHROW (\"Hook Thrower\"), \n\t\tMOTOR (\"Motor\"), \n\t\tSWING (\"Swing Speed\"), \n\t\tSTAFF (\"Ender Staff\"), \n\t\tFORCEFIELD (\"Forcefield\"), \n\t\tMAGNET (\"Hook Magnet\"), \n\t\tDOUBLE (\"Double Hook\"),\n\t\tLIMITS (\"Limits\"),\n\t\tROCKET (\"Rocket\");\n\t\t\n\t\tpublic String description;\n\t\tprivate upgradeCategories(String desc) {\n\t\t\tthis.description = desc;\n\t\t}\n\t\t\n\t\tpublic static upgradeCategories fromInt(int i) {\n\t\t\treturn upgradeCategories.values()[i];\n\t\t}\n\t\tpublic int toInt() {\n\t\t\tfor (int i = 0; i < size(); i++) {\n\t\t\t\tif (upgradeCategories.values()[i] == this) {\n\t\t\t\t\treturn i;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn -1;\n\t\t}\n\t\tpublic static int size() {\n\t\t\treturn upgradeCategories.values().length;\n\t\t}\n\t\tpublic Item getItem() {\n\t\t\tif (this == upgradeCategories.ROPE) {\n\t\t\t\treturn ropeupgradeitem;\n\t\t\t} else if (this == upgradeCategories.THROW) {\n\t\t\t\treturn throwupgradeitem;\n\t\t\t} else if (this == upgradeCategories.MOTOR) {\n\t\t\t\treturn motorupgradeitem;\n\t\t\t} else if (this == upgradeCategories.SWING) {\n\t\t\t\treturn swingupgradeitem;\n\t\t\t} else if (this == upgradeCategories.STAFF) {\n\t\t\t\treturn staffupgradeitem;\n\t\t\t} else if (this == upgradeCategories.FORCEFIELD) {\n\t\t\t\treturn forcefieldupgradeitem;\n\t\t\t} else if (this == upgradeCategories.MAGNET) {\n\t\t\t\treturn magnetupgradeitem;\n\t\t\t} else if (this == upgradeCategories.DOUBLE) {\n\t\t\t\treturn doubleupgradeitem;\n\t\t\t} else if (this == upgradeCategories.LIMITS) {\n\t\t\t\treturn limitsupgradeitem;\n\t\t\t} else if (this == upgradeCategories.ROCKET) {\n\t\t\t\treturn rocketupgradeitem;\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t};\n\t\n\tpublic static final CreativeTabs tabGrapplemod = (new CreativeTabs(\"tabGrapplemod\") {\n\t\t\n\t\t@Override\n\t\tpublic void displayAllRelevantItems(NonNullList<ItemStack> items) {\n\t\t\t// sort items\n\t\t\tsuper.displayAllRelevantItems(items);\n\t\t\tItem[] allitems = getAllItems();\n\t\t\tCollections.sort(items, new Comparator<ItemStack>() {\n\t\t\t\t@Override\n\t\t\t\tpublic int compare(ItemStack arg0, ItemStack arg1) {\n\t\t\t\t\treturn getIndex(arg0.getItem()) - getIndex(arg1.getItem());\n\t\t\t\t}\n\t\t\t\tpublic int getIndex(Item item) {\n\t\t\t\t\tint i = 0;\n\t\t\t\t\tfor (Item item2 : allitems) {\n\t\t\t\t\t\tif (item == item2) {\n\t\t\t\t\t\t\treturn i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\ti++;\n\t\t\t\t\t}\n\t\t\t\t\treturn i;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\t@Override\n\t\tpublic ItemStack getTabIconItem() {\n\t\t\treturn new ItemStack(grapplebowitem);\n\t\t}\n\t});\n\t\n\t@SidedProxy(clientSide=\"com.yyon.grapplinghook.ClientProxyClass\", serverSide=\"com.yyon.grapplinghook.ServerProxyClass\")\n\tpublic static CommonProxyClass proxy;\n\t\n\t@EventHandler\n\tpublic void load(FMLInitializationEvent event){\n\t}\n\n\tpublic void registerRenderers(){\n\t}\n\tpublic void generateNether(World world, Random random, int chunkX, int chunkZ){}\n\tpublic void generateSurface(World world, Random random, int chunkX, int chunkZ){}\n\tpublic int addFuel(ItemStack fuel){\n\t\treturn 0;\n\t}\n\n\tpublic void serverLoad(FMLServerStartingEvent event){\n\t}\n\t\n\tpublic static HashSet<Block> stringToBlocks(String s) {\n\t\tHashSet<Block> blocks = new HashSet<Block>();\n\t\t\n\t\tif (s.equals(\"\") || s.equals(\"none\") || s.equals(\"any\")) {\n\t\t\treturn blocks;\n\t\t}\n\t\t\n\t\tString[] blockstr = s.split(\",\");\n\t\t\n\t for(String str:blockstr){\n\t \tstr = str.trim();\n\t \tString modid;\n\t \tString name;\n\t \tif (str.contains(\":\")) {\n\t \t\tString[] splitstr = str.split(\":\");\n\t \t\tmodid = splitstr[0];\n\t \t\tname = splitstr[1];\n\t \t} else {\n\t \t\tmodid = \"minecraft\";\n\t \t\tname = str;\n\t \t}\n\t \t\n\t \tBlock b = Block.REGISTRY.getObject(new ResourceLocation(modid, name));\n\t \t\n\t \tblocks.add(b);\n\t }\n\t \n\t return blocks;\n\t}\n\t\n\tpublic static void updateGrapplingBlocks() {\n\t\tString s = GrappleConfig.getconf().grapplingBlocks;\n\t\tif (s.equals(\"any\") || s.equals(\"\")) {\n\t\t\ts = GrappleConfig.getconf().grapplingNonBlocks;\n\t\t\tif (s.equals(\"none\") || s.equals(\"\")) {\n\t\t\t\tanyblocks = true;\n\t\t\t} else {\n\t\t\t\tanyblocks = false;\n\t\t\t\tremoveblocks = true;\n\t\t\t}\n\t\t} else {\n\t\t\tanyblocks = false;\n\t\t\tremoveblocks = false;\n\t\t}\n\t\n\t\tif (!anyblocks) {\n\t\t\tgrapplingblocks = stringToBlocks(s);\n\t\t}\n\t\t\n\t\tgrapplingbreaksblocks = stringToBlocks(GrappleConfig.getconf().grappleBreakBlocks);\n\t\tanybreakblocks = grapplingbreaksblocks.size() != 0;\n\t\t\n\t\tgrapplingignoresblocks = stringToBlocks(GrappleConfig.getconf().grappleIgnoreBlocks);\n\t\tanyignoresblocks = grapplingignoresblocks.size() != 0;\n\t\t\n\t}\n\t\n\t@SubscribeEvent\n\tpublic void registerItems(RegistryEvent.Register<Item> event) {\n//\t\tSystem.out.println(\"REGISTERING ITEMS\");\n//\t\tSystem.out.println(grapplebowitem);\n\t event.getRegistry().registerAll(getAllItems());\n\n\t}\n\t\n\tpublic static Item[] getAllItems() {\n\t\treturn new Item[] {\n\t\t\t\tgrapplebowitem, \n\t\t\t\titemBlockGrappleModifier,\n\t\t\t\tenderhookitem, \n\t\t\t\tmagnethookitem,\n\t\t\t\trockethookitem,\n\t\t\t\tmotorhookitem, \n\t\t\t\tsmarthookitem, \n\t\t\t\tdoublemotorhookitem, \n\t\t\t\trocketdoublemotorhookitem, \n\t\t\t\tlauncheritem, \n\t\t\t\trepelleritem, \n\t\t\t\tlongfallboots, \n\t\t\t\tbaseupgradeitem, \n\t\t\t\tropeupgradeitem, \n\t\t\t\tthrowupgradeitem, \n\t\t\t\tmotorupgradeitem, \n\t\t\t\tswingupgradeitem, \n\t\t\t\tstaffupgradeitem, \n\t\t\t\tforcefieldupgradeitem, \n\t\t\t\tmagnetupgradeitem, \n\t\t\t\tdoubleupgradeitem, \n\t\t\t\trocketupgradeitem, \n\t\t\t\tlimitsupgradeitem, \n\t\t\t\t};\n\t}\n\t\n\t@SubscribeEvent\n\tpublic void registerEnchantments(RegistryEvent.Register<Enchantment> event) {\n\t event.getRegistry().registerAll(wallrunenchantment, doublejumpenchantment, slidingenchantment);\n\n\t}\n\t\n\t@EventHandler\n\tpublic void preInit(FMLPreInitializationEvent event){\n//\t\tSystem.out.println(\"PREINIT!!!\");\n\t\tgrapplebowitem = new grappleBow();\n\t\tgrapplebowitem.setRegistryName(\"grapplinghook\");\n\t\tmotorhookitem = new MotorHook();\n\t\tmotorhookitem.setRegistryName(\"motorhook\");\n\t\tsmarthookitem = new SmartHook();\n\t\tsmarthookitem.setRegistryName(\"smarthook\");\n\t\tdoublemotorhookitem = new DoubleMotorHook();\n\t\tdoublemotorhookitem.setRegistryName(\"doublemotorhook\");\n\t\trocketdoublemotorhookitem = new RocketDoubleMotorHook();\n\t\trocketdoublemotorhookitem.setRegistryName(\"rocketdoublemotorhook\");\n\t\tenderhookitem = new EnderHook();\n\t\tenderhookitem.setRegistryName(\"enderhook\");\n\t\tmagnethookitem = new MagnetHook();\n\t\tmagnethookitem.setRegistryName(\"magnethook\");\n\t\trockethookitem = new RocketHook();\n\t\trockethookitem.setRegistryName(\"rockethook\");\n\t\tlauncheritem = new launcherItem();\n\t\tlauncheritem.setRegistryName(\"launcheritem\");\n\t\tlongfallboots = new LongFallBoots(ItemArmor.ArmorMaterial.DIAMOND, 3);\n\t\tlongfallboots.setRegistryName(\"longfallboots\");\n\t\trepelleritem = new repeller();\n\t\trepelleritem.setRegistryName(\"repeller\");\n\t baseupgradeitem = new BaseUpgradeItem();\n\t baseupgradeitem.setRegistryName(\"baseupgradeitem\");\n\t doubleupgradeitem = new DoubleUpgradeItem();\n\t doubleupgradeitem.setRegistryName(\"doubleupgradeitem\");\n\t doubleupgradeitem.setContainerItem(doubleupgradeitem);\n\t forcefieldupgradeitem = new ForcefieldUpgradeItem();\n\t forcefieldupgradeitem.setRegistryName(\"forcefieldupgradeitem\");\n\t forcefieldupgradeitem.setContainerItem(forcefieldupgradeitem);\n\t magnetupgradeitem = new MagnetUpgradeItem();\n\t magnetupgradeitem.setRegistryName(\"magnetupgradeitem\");\n\t magnetupgradeitem.setContainerItem(magnetupgradeitem);\n\t motorupgradeitem = new MotorUpgradeItem();\n\t motorupgradeitem.setRegistryName(\"motorupgradeitem\");\n\t motorupgradeitem.setContainerItem(motorupgradeitem);\n\t ropeupgradeitem = new RopeUpgradeItem();\n\t ropeupgradeitem.setRegistryName(\"ropeupgradeitem\");\n\t ropeupgradeitem.setContainerItem(ropeupgradeitem);\n\t staffupgradeitem = new StaffUpgradeItem();\n\t staffupgradeitem.setRegistryName(\"staffupgradeitem\");\n\t staffupgradeitem.setContainerItem(staffupgradeitem);\n\t swingupgradeitem = new SwingUpgradeItem();\n\t swingupgradeitem.setRegistryName(\"swingupgradeitem\");\n\t swingupgradeitem.setContainerItem(swingupgradeitem);\n\t throwupgradeitem = new ThrowUpgradeItem();\n\t throwupgradeitem.setRegistryName(\"throwupgradeitem\");\n\t throwupgradeitem.setContainerItem(throwupgradeitem);\n\t limitsupgradeitem = new LimitsUpgradeItem();\n\t limitsupgradeitem.setRegistryName(\"limitsupgradeitem\");\n\t limitsupgradeitem.setContainerItem(limitsupgradeitem);\n\t rocketupgradeitem = new RocketUpgradeItem();\n\t rocketupgradeitem.setRegistryName(\"rocketupgradeitem\");\n\t rocketupgradeitem.setContainerItem(rocketupgradeitem);\n\t \n\t wallrunenchantment = new WallrunEnchantment();\n\t wallrunenchantment.setRegistryName(\"wallrunenchantment\");\n\t doublejumpenchantment = new DoublejumpEnchantment();\n\t doublejumpenchantment.setRegistryName(\"doublejumpenchantment\");\n\t slidingenchantment = new SlidingEnchantment();\n\t slidingenchantment.setRegistryName(\"slidingenchantment\");\n\t \n//\t\tSystem.out.println(grapplebowitem);\n\t\t\n\t\tresourceLocation = new ResourceLocation(grapplemod.MODID, \"grapplemod\");\n\t\t\n\t\tregisterEntity(grappleArrow.class, \"grappleArrow\");\n\t\t\n\t\tnetwork = NetworkRegistry.INSTANCE.newSimpleChannel(\"grapplemodchannel\");\n\t\tbyte id = 0;\n\t\tnetwork.registerMessage(PlayerMovementMessage.Handler.class, PlayerMovementMessage.class, id++, Side.SERVER);\n\t\tnetwork.registerMessage(GrappleAttachMessage.Handler.class, GrappleAttachMessage.class, id++, Side.CLIENT);\n\t\tnetwork.registerMessage(GrappleEndMessage.Handler.class, GrappleEndMessage.class, id++, Side.SERVER);\n\t\tnetwork.registerMessage(GrappleDetachMessage.Handler.class, GrappleDetachMessage.class, id++, Side.CLIENT);\n\t\tnetwork.registerMessage(DetachSingleHookMessage.Handler.class, DetachSingleHookMessage.class, id++, Side.CLIENT);\n\t\tnetwork.registerMessage(GrappleAttachPosMessage.Handler.class, GrappleAttachPosMessage.class, id++, Side.CLIENT);\n\t\tnetwork.registerMessage(SegmentMessage.Handler.class, SegmentMessage.class, id++, Side.CLIENT);\n\t\tnetwork.registerMessage(GrappleModifierMessage.Handler.class, GrappleModifierMessage.class, id++, Side.SERVER);\n\t\tnetwork.registerMessage(LoggedInMessage.Handler.class, LoggedInMessage.class, id++, Side.CLIENT);\n\t\tnetwork.registerMessage(KeypressMessage.Handler.class, KeypressMessage.class, id++, Side.SERVER);\n\t\t\n\t\tblockGrappleModifier = (BlockGrappleModifier)(new BlockGrappleModifier().setUnlocalizedName(\"block_grapple_modifier\"));\n\t\tblockGrappleModifier.setHardness(10F);\n\t\tblockGrappleModifier.setRegistryName(\"block_grapple_modifier\");\n\t ForgeRegistries.BLOCKS.register(blockGrappleModifier);\n\n\t itemBlockGrappleModifier = new ItemBlock(blockGrappleModifier);\n\t itemBlockGrappleModifier.setRegistryName(blockGrappleModifier.getRegistryName());\n\n\t // Each of your tile entities needs to be registered with a name that is unique to your mod.\n\t\tGameRegistry.registerTileEntity(TileEntityGrappleModifier.class, new ResourceLocation(grapplemod.MODID, \"tile_entity_grapple_modifier\"));\n\t\n\t MinecraftForge.EVENT_BUS.register(this);\n\t \n\t\tproxy.preInit(event);\n\t\t\n\t\ttabGrapplemod.setRelevantEnchantmentTypes(GRAPPLEENCHANTS_FEET);\n\t}\n\t\n\t@EventHandler\n\tpublic void Init(FMLInitializationEvent event) {\n\t\tproxy.init(event, this);\n\t}\n\t\n\t@EventHandler\n\tpublic void postInit(FMLPostInitializationEvent event) {\n\t\tproxy.postInit(event);\n\t\t\n\t\tgrapplemod.updateGrapplingBlocks();\n\t}\n\t\n\tint entityID = 0;\n\tpublic void registerEntity(Class<? extends Entity> entityClass, String name)\n\t{\n\t\tEntityRegistry.registerModEntity(resourceLocation, entityClass, name, entityID++, this, 900, 1, true);\n\t}\n\t\n\tpublic static void registerController(int entityId, grappleController controller) {\n\t\tif (controllers.containsKey(entityId)) {\n\t\t\tcontrollers.get(entityId).unattach();\n\t\t}\n\t\t\n\t\tcontrollers.put(entityId, controller);\n\t}\n\t\n\tpublic static void unregisterController(int entityId) {\n\t\tcontrollers.remove(entityId);\n\t}\n\n\tpublic static void receiveGrappleDetach(int id) {\n\t\tgrappleController controller = controllers.get(id);\n\t\tif (controller != null) {\n\t\t\tcontroller.receiveGrappleDetach();\n\t\t} else {\n\t\t\tSystem.out.println(\"Couldn't find controller\");\n\t\t}\n\t}\n\t\n\tpublic static void receiveGrappleDetachHook(int id, int hookid) {\n\t\tgrappleController controller = controllers.get(id);\n\t\tif (controller != null) {\n\t\t\tcontroller.receiveGrappleDetachHook(hookid);\n\t\t} else {\n\t\t\tSystem.out.println(\"Couldn't find controller\");\n\t\t}\n\t}\n\n\tpublic static void receiveEnderLaunch(int id, double x, double y, double z) {\n\t\tgrappleController controller = controllers.get(id);\n\t\tif (controller != null) {\n\t\t\tcontroller.receiveEnderLaunch(x, y, z);\n\t\t} else {\n\t\t\tSystem.out.println(\"Couldn't find controller\");\n\t\t}\n\t}\n\t\n\tpublic static void sendtocorrectclient(IMessage message, int playerid, World w) {\n\t\tEntity entity = w.getEntityByID(playerid);\n\t\tif (entity instanceof EntityPlayerMP) {\n\t\t\tgrapplemod.network.sendTo(message, (EntityPlayerMP) entity);\n\t\t} else {\n\t\t\tSystem.out.println(\"ERROR! couldn't find player\");\n\t\t}\n\t}\n\t\n\n\tpublic static void removesubarrow(int id) {\n\t\tHashSet<Integer> arrowIds = new HashSet<Integer>();\n\t\tarrowIds.add(id);\n\t\tgrapplemod.network.sendToServer(new GrappleEndMessage(-1, arrowIds));\n\t}\n\n\tpublic static void receiveGrappleEnd(int id, World world, HashSet<Integer> arrowIds) {\n\t\tif (grapplemod.attached.contains(id)) {\n\t\t\tgrapplemod.attached.remove(new Integer\n\t\t\t\t\t(id));\n\t\t} else {\n\t\t}\n\t\t\n\t\tfor (int arrowid : arrowIds) {\n\t \tEntity grapple = world.getEntityByID(arrowid);\n\t \t\tif (grapple instanceof grappleArrow) {\n\t \t\t\t((grappleArrow) grapple).removeServer();\n\t \t\t} else {\n\t\n\t \t\t}\n\t\t}\n \t\t\n \t\tEntity entity = world.getEntityByID(id);\n \t\tif (entity != null) {\n \t\tentity.fallDistance = 0;\n \t\t}\n \t\t\n \t\tgrapplemod.removeallmultihookarrows(id);\n\t}\n\tpublic static void addarrow(int id, grappleArrow arrow) {\n\t\tif (!allarrows.containsKey(id)) {\n\t\t\tallarrows.put(id, new HashSet<grappleArrow>());\n\t\t}\n\t\tallarrows.get(id).add(arrow);\n\t}\n\t\n\tpublic static void removeallmultihookarrows(int id) {\n\t\tif (!allarrows.containsKey(id)) {\n\t\t\tallarrows.put(id, new HashSet<grappleArrow>());\n\t\t}\n\t\tfor (grappleArrow arrow : allarrows.get(id)) {\n\t\t\tif (arrow != null && !arrow.isDead) {\n\t\t\t\tarrow.removeServer();\n\t\t\t}\n\t\t}\n\t\tallarrows.put(id, new HashSet<grappleArrow>());\n\t}\n\t\n\n\tpublic static NBTTagCompound getstackcompound(ItemStack stack, String key) {\n\t\tif (!stack.hasTagCompound()) {\n\t\t\tstack.setTagCompound(new NBTTagCompound());\n\t\t}\n\t\tNBTTagCompound basecompound = stack.getTagCompound();\n if (basecompound.hasKey(key, 10))\n {\n return basecompound.getCompoundTag(key);\n }\n else\n {\n NBTTagCompound nbttagcompound = new NBTTagCompound();\n stack.setTagInfo(key, nbttagcompound);\n return nbttagcompound;\n }\n\t}\n\t\n\n\t@SubscribeEvent\n\tpublic void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent eventArgs) {\n\t if(eventArgs.getModID().equals(\"grapplemod\")){\n\t\t\tSystem.out.println(\"grapplemod config updated\");\n\t\t\tConfigManager.sync(\"grapplemod\", Type.INSTANCE);;\n\t\t\t\n\t\t\tgrapplemod.updateGrapplingBlocks();\n\t\t}\n\t}\n\n\tpublic static void receiveKeypress(EntityPlayer player, Keys key, boolean isDown) {\n\t\tif (player != null) {\n\t\t\tItemStack stack = player.getHeldItemMainhand();\n\t\t\tif (stack != null) {\n\t\t\t\tItem item = stack.getItem();\n\t\t\t\tif (item instanceof KeypressItem) {\n\t\t\t\t\tif (isDown) {\n\t\t\t\t\t\t((KeypressItem)item).onCustomKeyDown(stack, player, key, true);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t((KeypressItem)item).onCustomKeyUp(stack, player, key, true);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstack = player.getHeldItemOffhand();\n\t\t\tif (stack != null) {\n\t\t\t\tItem item = stack.getItem();\n\t\t\t\tif (item instanceof KeypressItem) {\n\t\t\t\t\tif (isDown) {\n\t\t\t\t\t\t((KeypressItem)item).onCustomKeyDown(stack, player, key, false);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t((KeypressItem)item).onCustomKeyUp(stack, player, key, false);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static Rarity getRarityFromInt(int rarity_int) {\n\t\tRarity[] rarities = (new Rarity[] {Rarity.VERY_RARE, Rarity.RARE, Rarity.UNCOMMON, Rarity.COMMON});\n\t\tif (rarity_int < 0) {rarity_int = 0;}\n\t\tif (rarity_int >= rarities.length) {rarity_int = rarities.length-1;}\n\t\treturn rarities[rarity_int];\n\t}\n}", "public class grappleBow extends Item implements KeypressItem {\n\tpublic static HashMap<Entity, grappleArrow> grapplearrows1 = new HashMap<Entity, grappleArrow>();\n\tpublic static HashMap<Entity, grappleArrow> grapplearrows2 = new HashMap<Entity, grappleArrow>();\n\t\n\tpublic grappleBow() {\n\t\tsuper();\n\t\tmaxStackSize = 1;\n\t\tsetFull3D();\n\t\tsetUnlocalizedName(\"grapplinghook\");\n\t\t\n\t\tthis.setMaxDamage(GrappleConfig.getconf().default_durability);\n\t\t\n\t\tsetCreativeTab(grapplemod.tabGrapplemod);\n\t\t\n\t\tMinecraftForge.EVENT_BUS.register(this);\n\t}\n\n @Override\n\tpublic int getMaxItemUseDuration(ItemStack par1ItemStack)\n\t{\n\t\treturn 72000;\n\t}\n\t\n\tpublic boolean hasArrow(Entity entity) {\n\t\tgrappleArrow arrow1 = getArrowLeft(entity);\n\t\tgrappleArrow arrow2 = getArrowRight(entity);\n\t\treturn (arrow1 != null) || (arrow2 != null);\n\t}\n\t\n\t@Override\n\tpublic boolean getIsRepairable(ItemStack toRepair, ItemStack repair) {\n ItemStack mat = new ItemStack(Items.LEATHER, 1);\n if (mat != null && net.minecraftforge.oredict.OreDictionary.itemMatches(mat, repair, false)) return true;\n return super.getIsRepairable(toRepair, repair);\n\t}\n\n\tpublic void setArrowLeft(Entity entity, grappleArrow arrow) {\n\t\tgrappleBow.grapplearrows1.put(entity, arrow);\n\t}\n\tpublic void setArrowRight(Entity entity, grappleArrow arrow) {\n\t\tgrappleBow.grapplearrows2.put(entity, arrow);\n\t}\n\tpublic grappleArrow getArrowLeft(Entity entity) {\n\t\tif (grappleBow.grapplearrows1.containsKey(entity)) {\n\t\t\tgrappleArrow arrow = grappleBow.grapplearrows1.get(entity);\n\t\t\tif (arrow != null && !arrow.isDead) {\n\t\t\t\treturn arrow;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\tpublic grappleArrow getArrowRight(Entity entity) {\n\t\tif (grappleBow.grapplearrows2.containsKey(entity)) {\n\t\t\tgrappleArrow arrow = grappleBow.grapplearrows2.get(entity);\n\t\t\tif (arrow != null && !arrow.isDead) {\n\t\t\t\treturn arrow;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\t\n\t\n\tpublic void dorightclick(ItemStack stack, World worldIn, EntityLivingBase entityLiving, boolean righthand) {\n if (!worldIn.isRemote) {\n \t}\n\t}\n\t\n\tpublic void throwBoth(ItemStack stack, World worldIn, EntityLivingBase entityLiving, boolean righthand) {\n\t\tgrappleArrow arrow_left = getArrowLeft(entityLiving);\n\t\tgrappleArrow arrow_right = getArrowRight(entityLiving);\n\n\t\tif (arrow_left != null || arrow_right != null) {\n\t\t\tdetachBoth(entityLiving);\n \t\treturn;\n\t\t}\n\t\t\n \tGrappleCustomization custom = this.getCustomization(stack);\n \t\tdouble angle = custom.angle;\n \t\tdouble verticalangle = custom.verticalthrowangle;\n \t\tif (entityLiving.isSneaking()) {\n \t\t\tangle = custom.sneakingangle;\n \t\t\tverticalangle = custom.sneakingverticalthrowangle;\n \t\t}\n\n \tif (!(!custom.doublehook || angle == 0)) {\n \t\tthrowLeft(stack, worldIn, entityLiving, righthand);\n \t}\n\t\tthrowRight(stack, worldIn, entityLiving, righthand);\n\n\t\tstack.damageItem(1, entityLiving);\n worldIn.playSound((EntityPlayer)null, entityLiving.posX, entityLiving.posY, entityLiving.posZ, SoundEvents.ENTITY_ARROW_SHOOT, SoundCategory.NEUTRAL, 1.0F, 1.0F / (itemRand.nextFloat() * 0.4F + 1.2F) + 2.0F * 0.5F);\n\t}\n\t\n\tpublic boolean throwLeft(ItemStack stack, World worldIn, EntityLivingBase entityLiving, boolean righthand) {\n \tGrappleCustomization custom = this.getCustomization(stack);\n \t\n \t\tdouble angle = custom.angle;\n \t\tdouble verticalangle = custom.verticalthrowangle;\n \t\t\n \t\tif (entityLiving.isSneaking()) {\n \t\t\tangle = custom.sneakingangle;\n \t\t\tverticalangle = custom.sneakingverticalthrowangle;\n \t\t}\n \t\t\n \t\tEntityLivingBase player = entityLiving;\n \t\t\n \t\tvec anglevec = vec.fromAngles(Math.toRadians(-angle), Math.toRadians(verticalangle)); //new vec(0,0,1).rotate_yaw(Math.toRadians(angle)).rotate_pitch(Math.toRadians(verticalangle));\n \t\tanglevec = anglevec.rotate_pitch(Math.toRadians(-player.rotationPitch));\n \t\tanglevec = anglevec.rotate_yaw(Math.toRadians(player.rotationYaw));\n float velx = -MathHelper.sin((float) anglevec.getYaw() * 0.017453292F) * MathHelper.cos((float) anglevec.getPitch() * 0.017453292F);\n float vely = -MathHelper.sin((float) anglevec.getPitch() * 0.017453292F);\n float velz = MathHelper.cos((float) anglevec.getYaw() * 0.017453292F) * MathHelper.cos((float) anglevec.getPitch() * 0.017453292F);\n\t\tgrappleArrow entityarrow = this.createarrow(stack, worldIn, entityLiving, false, true);// new grappleArrow(worldIn, player, false);\n float extravelocity = (float) vec.motionvec(entityLiving).dist_along(new vec(velx, vely, velz));\n if (extravelocity < 0) { extravelocity = 0; }\n entityarrow.shoot((double) velx, (double) vely, (double) velz, entityarrow.getVelocity() + extravelocity, 0.0F);\n \n\t\tworldIn.spawnEntity(entityarrow);\n\t\tsetArrowLeft(entityLiving, entityarrow); \t\t\t\n\t\t\n\t\treturn true;\n\t}\n\t\n\tpublic void throwRight(ItemStack stack, World worldIn, EntityLivingBase entityLiving, boolean righthand) {\n \tGrappleCustomization custom = this.getCustomization(stack);\n \t\n \t\tdouble angle = custom.angle;\n \t\tdouble verticalangle = custom.verticalthrowangle;\n \t\tif (entityLiving.isSneaking()) {\n \t\t\tangle = custom.sneakingangle;\n \t\t\tverticalangle = custom.sneakingverticalthrowangle;\n \t\t}\n \t\t\n \tif (!custom.doublehook || angle == 0) {\n\t\t\tgrappleArrow entityarrow = this.createarrow(stack, worldIn, entityLiving, righthand, false);\n \t\tvec anglevec = new vec(0,0,1).rotate_pitch(Math.toRadians(verticalangle));\n \t\tanglevec = anglevec.rotate_pitch(Math.toRadians(-entityLiving.rotationPitch));\n \t\tanglevec = anglevec.rotate_yaw(Math.toRadians(entityLiving.rotationYaw));\n\t float velx = -MathHelper.sin((float) anglevec.getYaw() * 0.017453292F) * MathHelper.cos((float) anglevec.getPitch() * 0.017453292F);\n\t float vely = -MathHelper.sin((float) anglevec.getPitch() * 0.017453292F);\n\t float velz = MathHelper.cos((float) anglevec.getYaw() * 0.017453292F) * MathHelper.cos((float) anglevec.getPitch() * 0.017453292F);\n\t float extravelocity = (float) vec.motionvec(entityLiving).dist_along(new vec(velx, vely, velz));\n\t if (extravelocity < 0) { extravelocity = 0; }\n\t entityarrow.shoot((double) velx, (double) vely, (double) velz, entityarrow.getVelocity() + extravelocity, 0.0F);\n\t\t\tsetArrowRight(entityLiving, entityarrow);\n\t\t\tworldIn.spawnEntity(entityarrow);\n \t} else {\n \t\tEntityLivingBase player = entityLiving;\n \t\t\n \t\tvec anglevec = vec.fromAngles(Math.toRadians(angle), Math.toRadians(verticalangle)); //new vec(0,0,1).rotate_yaw(Math.toRadians(angle)).rotate_pitch(Math.toRadians(verticalangle));\n \t\tanglevec = anglevec.rotate_pitch(Math.toRadians(-player.rotationPitch));\n \t\tanglevec = anglevec.rotate_yaw(Math.toRadians(player.rotationYaw));\n\t float velx = -MathHelper.sin((float) anglevec.getYaw() * 0.017453292F) * MathHelper.cos((float) anglevec.getPitch() * 0.017453292F);\n\t float vely = -MathHelper.sin((float) anglevec.getPitch() * 0.017453292F);\n\t float velz = MathHelper.cos((float) anglevec.getYaw() * 0.017453292F) * MathHelper.cos((float) anglevec.getPitch() * 0.017453292F);\n\t\t\tgrappleArrow entityarrow = this.createarrow(stack, worldIn, entityLiving, true, true);//new grappleArrow(worldIn, player, true);\n// entityarrow.shoot(player, (float) anglevec.getPitch(), (float)anglevec.getYaw(), 0.0F, entityarrow.getVelocity(), 0.0F);\n\t float extravelocity = (float) vec.motionvec(entityLiving).dist_along(new vec(velx, vely, velz));\n\t if (extravelocity < 0) { extravelocity = 0; }\n\t entityarrow.shoot((double) velx, (double) vely, (double) velz, entityarrow.getVelocity() + extravelocity, 0.0F);\n \n\t\t\tworldIn.spawnEntity(entityarrow);\n\t\t\tsetArrowRight(entityLiving, entityarrow);\n\t\t}\n\t}\n\t\n\tpublic void detachBoth(EntityLivingBase entityLiving) {\n\t\tgrappleArrow arrow1 = getArrowLeft(entityLiving);\n\t\tgrappleArrow arrow2 = getArrowRight(entityLiving);\n\n\t\tsetArrowLeft(entityLiving, null);\n\t\tsetArrowRight(entityLiving, null);\n\t\t\n\t\tif (arrow1 != null) {\n\t\t\tarrow1.removeServer();\n\t\t}\n\t\tif (arrow2 != null) {\n\t\t\tarrow2.removeServer();\n\t\t}\n\n\t\tint id = entityLiving.getEntityId();\n\t\tgrapplemod.sendtocorrectclient(new GrappleDetachMessage(id), id, entityLiving.world);\n\n\t\tif (grapplemod.attached.contains(id)) {\n\t\t\tgrapplemod.attached.remove(new Integer(id));\n\t\t}\n\t}\n\t\n\tpublic void detachLeft(EntityLivingBase entityLiving) {\n\t\tgrappleArrow arrow1 = getArrowLeft(entityLiving);\n\t\t\n\t\tsetArrowLeft(entityLiving, null);\n\t\t\n\t\tif (arrow1 != null) {\n\t\t\tarrow1.removeServer();\n\t\t}\n\t\t\n\t\tint id = entityLiving.getEntityId();\n\t\t\n\t\t// remove controller if hook is attached\n\t\tif (getArrowRight(entityLiving) == null) {\n\t\t\tgrapplemod.sendtocorrectclient(new GrappleDetachMessage(id), id, entityLiving.world);\n\t\t} else {\n\t\t\tgrapplemod.sendtocorrectclient(new DetachSingleHookMessage(id, arrow1.getEntityId()), id, entityLiving.world);\n\t\t}\n\t\t\n\t\tif (grapplemod.attached.contains(id)) {\n\t\t\tgrapplemod.attached.remove(new Integer(id));\n\t\t}\n\t}\n\t\n\tpublic void detachRight(EntityLivingBase entityLiving) {\n\t\tgrappleArrow arrow2 = getArrowRight(entityLiving);\n\t\t\n\t\tsetArrowRight(entityLiving, null);\n\t\t\n\t\tif (arrow2 != null) {\n\t\t\tarrow2.removeServer();\n\t\t}\n\t\t\n\t\tint id = entityLiving.getEntityId();\n\t\t\n\t\t// remove controller if hook is attached\n\t\tif (getArrowLeft(entityLiving) == null) {\n\t\t\tgrapplemod.sendtocorrectclient(new GrappleDetachMessage(id), id, entityLiving.world);\n\t\t} else {\n\t\t\tgrapplemod.sendtocorrectclient(new DetachSingleHookMessage(id, arrow2.getEntityId()), id, entityLiving.world);\n\t\t}\n\t\t\n\t\tif (grapplemod.attached.contains(id)) {\n\t\t\tgrapplemod.attached.remove(new Integer(id));\n\t\t}\n\t}\n\t\n public double getAngle(EntityLivingBase entity, ItemStack stack) {\n \tGrappleCustomization custom = this.getCustomization(stack);\n \tif (entity.isSneaking()) {\n \t\treturn custom.sneakingangle;\n \t} else {\n \t\treturn custom.angle;\n \t}\n }\n\t\n\tpublic grappleArrow createarrow(ItemStack stack, World worldIn, EntityLivingBase entityLiving, boolean righthand, boolean isdouble) {\n\t\tgrappleArrow arrow = new grappleArrow(worldIn, entityLiving, righthand, this.getCustomization(stack), isdouble);\n\t\tgrapplemod.addarrow(entityLiving.getEntityId(), arrow);\n\t\treturn arrow;\n\t}\n \n @Override\n public ActionResult<ItemStack> onItemRightClick(World worldIn, EntityPlayer entityLiving, EnumHand hand)\n {\n \tItemStack stack = entityLiving.getHeldItem(hand);\n if (!worldIn.isRemote) {\n\t this.dorightclick(stack, worldIn, entityLiving, hand == EnumHand.MAIN_HAND);\n }\n entityLiving.setActiveHand(hand);\n return new ActionResult<ItemStack>(EnumActionResult.SUCCESS, stack);\n }\n\t\n\n\t@Override\n\tpublic void onPlayerStoppedUsing(ItemStack stack, World worldIn,\n\t\t\tEntityLivingBase entityLiving, int timeLeft) {\n\t\tif (!worldIn.isRemote) {\n//\t\t\tstack.getSubCompound(\"grapplemod\", true).setBoolean(\"extended\", (this.getArrow(entityLiving, worldIn) != null));\n\t\t}\n\t\tsuper.onPlayerStoppedUsing(stack, worldIn, entityLiving, timeLeft);\n\t}\n\n\t/**\n\t * returns the action that specifies what animation to play when the items is being used\n\t */\n @Override\n\tpublic EnumAction getItemUseAction(ItemStack par1ItemStack)\n\t{\n\t\treturn EnumAction.NONE;\n\t}\n\n @Override\n public boolean onLeftClickEntity(ItemStack stack, EntityPlayer player, Entity entity)\n {\n \treturn true;\n }\n \n\t@Override\n\tpublic void onCustomKeyDown(ItemStack stack, EntityPlayer player, KeypressItem.Keys key, boolean ismainhand) {\n\t\tif (player.world.isRemote) {\n\t\t\tif (key == KeypressItem.Keys.LAUNCHER) {\n\t\t\t\tif (this.getCustomization(stack).enderstaff) {\n\t\t\t\t\tgrapplemod.proxy.launchplayer(player);\n\t\t\t\t}\n\t\t\t} else if (key == KeypressItem.Keys.THROWLEFT || key == KeypressItem.Keys.THROWRIGHT || key == KeypressItem.Keys.THROWBOTH) {\n\t\t\t\tgrapplemod.network.sendToServer(new KeypressMessage(key, true));\n\t\t\t} else if (key == KeypressItem.Keys.ROCKET) {\n\t\t\t\tGrappleCustomization custom = this.getCustomization(stack);\n\t\t\t\tif (custom.rocket) {\n\t\t\t\t\tgrapplemod.proxy.startrocket(player, custom);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif (key == KeypressItem.Keys.THROWBOTH) {\n\t \tthrowBoth(stack, player.world, player, ismainhand);\n\t\t\t} else if (key == KeypressItem.Keys.THROWLEFT) {\n\t\t\t\tgrappleArrow arrow1 = getArrowLeft(player);\n\n\t \t\tif (arrow1 != null) {\n\t \t\t\tdetachLeft(player);\n\t\t \t\treturn;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tboolean threw = throwLeft(stack, player.world, player, ismainhand);\n\n\t\t\t\tif (threw) {\n\t\t\t\t\tstack.damageItem(1, player);\n\t\t\t player.world.playSound((EntityPlayer)null, player.posX, player.posY, player.posZ, SoundEvents.ENTITY_ARROW_SHOOT, SoundCategory.NEUTRAL, 1.0F, 1.0F / (itemRand.nextFloat() * 0.4F + 1.2F) + 2.0F * 0.5F);\n\t\t\t\t}\n\t\t\t} else if (key == KeypressItem.Keys.THROWRIGHT) {\n\t\t\t\tgrappleArrow arrow2 = getArrowRight(player);\n\n\t \t\tif (arrow2 != null) {\n\t \t\t\tdetachRight(player);\n\t\t \t\treturn;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tthrowRight(stack, player.world, player, ismainhand);\n\n\t\t\t\tstack.damageItem(1, player);\n\t\t player.world.playSound((EntityPlayer)null, player.posX, player.posY, player.posZ, SoundEvents.ENTITY_ARROW_SHOOT, SoundCategory.NEUTRAL, 1.0F, 1.0F / (itemRand.nextFloat() * 0.4F + 1.2F) + 2.0F * 0.5F);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void onCustomKeyUp(ItemStack stack, EntityPlayer player, KeypressItem.Keys key, boolean ismainhand) {\n\t\tif (player.world.isRemote) {\n\t\t\tif (key == KeypressItem.Keys.THROWLEFT || key == KeypressItem.Keys.THROWRIGHT || key == KeypressItem.Keys.THROWBOTH) {\n\t\t\t\tgrapplemod.network.sendToServer(new KeypressMessage(key, false));\n\t\t\t}\n\t\t} else {\n\t \tGrappleCustomization custom = this.getCustomization(stack);\n\t \t\n\t \tif (custom.detachonkeyrelease) {\n\t \t\tgrappleArrow arrow_left = getArrowLeft(player);\n\t \t\tgrappleArrow arrow_right = getArrowRight(player);\n\t \t\t\n\t\t\t\tif (key == KeypressItem.Keys.THROWBOTH) {\n\t\t\t\t\tdetachBoth(player);\n\t\t\t\t} else if (key == KeypressItem.Keys.THROWLEFT) {\n\t\t \t\tif (arrow_left != null) detachLeft(player);\n\t\t\t\t} else if (key == KeypressItem.Keys.THROWRIGHT) {\n\t\t \t\tif (arrow_right != null) detachRight(player);\n\t\t\t\t}\n\t \t}\n\t\t}\n\t}\n \n @Override\n public boolean hitEntity(ItemStack stack, EntityLivingBase target, EntityLivingBase attacker)\n {\n \treturn true;\n }\n \n @Override\n public boolean onBlockStartBreak(ItemStack itemstack, BlockPos k, EntityPlayer player)\n {\n return true;\n }\n \n public GrappleCustomization getCustomization(ItemStack itemstack) {\n \tif (itemstack.hasTagCompound()) {\n \tGrappleCustomization custom = new GrappleCustomization();\n \t\tcustom.loadNBT(itemstack.getTagCompound());\n \treturn custom;\n \t} else {\n \t\tGrappleCustomization custom = this.getDefaultCustomization();\n\n\t\t\tNBTTagCompound nbt = custom.writeNBT();\n\t\t\t\n\t\t\titemstack.setTagCompound(nbt);\n \t\t\n \t\treturn custom;\n \t}\n }\n \n public GrappleCustomization getDefaultCustomization() {\n \treturn new GrappleCustomization();\n }\n \n\t@Override\n @SideOnly(Side.CLIENT)\n\tpublic void addInformation(ItemStack stack, World world, List<String> list, ITooltipFlag par4)\n\t{\n\t\tGrappleCustomization custom = getCustomization(stack);\n\n\t\t\n\t\tif (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {\n\t\t\tif (!custom.detachonkeyrelease) {\n\t\t\t\tlist.add(ClientProxyClass.key_boththrow.getDisplayName() + \" \" + grapplemod.proxy.localize(\"grappletooltip.throw.desc\"));\n\t\t\t\tlist.add(ClientProxyClass.key_boththrow.getDisplayName() + \" \" + grapplemod.proxy.localize(\"grappletooltip.release.desc\"));\n\t\t\t\tlist.add(grapplemod.proxy.localize(\"grappletooltip.double.desc\") + ClientProxyClass.key_boththrow.getDisplayName() + \" \" + grapplemod.proxy.localize(\"grappletooltip.releaseandthrow.desc\"));\n\t\t\t} else {\n\t\t\t\tlist.add(ClientProxyClass.key_boththrow.getDisplayName() + \" \" + grapplemod.proxy.localize(\"grappletooltip.throwhold.desc\"));\n\t\t\t}\n\t\t\tlist.add(grapplemod.proxy.getkeyname(CommonProxyClass.keys.keyBindForward) + \", \" +\n\t\t\t\t\tgrapplemod.proxy.getkeyname(CommonProxyClass.keys.keyBindLeft) + \", \" +\n\t\t\t\t\tgrapplemod.proxy.getkeyname(CommonProxyClass.keys.keyBindBack) + \", \" +\n\t\t\t\t\tgrapplemod.proxy.getkeyname(CommonProxyClass.keys.keyBindRight) +\n\t\t\t\t\t\" \" + grapplemod.proxy.localize(\"grappletooltip.swing.desc\"));\n\t\t\tlist.add(ClientProxyClass.key_jumpanddetach.getDisplayName() + \" \" + grapplemod.proxy.localize(\"grappletooltip.jump.desc\"));\n\t\t\tlist.add(ClientProxyClass.key_slow.getDisplayName() + \" \" + grapplemod.proxy.localize(\"grappletooltip.slow.desc\"));\n\t\t\tlist.add(ClientProxyClass.key_climb.getDisplayName() + \" + \" + grapplemod.proxy.getkeyname(CommonProxyClass.keys.keyBindForward) + \" / \" + \n\t\t\t\t\tClientProxyClass.key_climbup.getDisplayName() + \n\t\t\t\t\t\" \" + grapplemod.proxy.localize(\"grappletooltip.climbup.desc\"));\n\t\t\tlist.add(ClientProxyClass.key_climb.getDisplayName() + \" + \" + grapplemod.proxy.getkeyname(CommonProxyClass.keys.keyBindBack) + \" / \" + \n\t\t\t\t\tClientProxyClass.key_climbdown.getDisplayName() + \n\t\t\t\t\t\" \" + grapplemod.proxy.localize(\"grappletooltip.climbdown.desc\"));\n\t\t\tif (custom.enderstaff) {\n\t\t\t\tlist.add(ClientProxyClass.key_enderlaunch.getDisplayName() + \" \" + grapplemod.proxy.localize(\"grappletooltip.enderlaunch.desc\"));\n\t\t\t}\n\t\t\tif (custom.rocket) {\n\t\t\t\tlist.add(ClientProxyClass.key_rocket.getDisplayName() + \" \" + grapplemod.proxy.localize(\"grappletooltip.rocket.desc\"));\n\t\t\t}\n\t\t\tif (custom.motor) {\n\t\t\t\tif (custom.motorwhencrouching && !custom.motorwhennotcrouching) {\n\t\t\t\t\tlist.add(ClientProxyClass.key_motoronoff.getDisplayName() + \" \" + grapplemod.proxy.localize(\"grappletooltip.motoron.desc\"));\n\t\t\t\t}\n\t\t\t\telse if (!custom.motorwhencrouching && custom.motorwhennotcrouching) {\n\t\t\t\t\tlist.add(ClientProxyClass.key_motoronoff.getDisplayName() + \" \" + grapplemod.proxy.localize(\"grappletooltip.motoroff.desc\"));\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (custom.doublehook) {\n\t\t\t\tif (!custom.detachonkeyrelease) {\n\t\t\t\t\tlist.add(ClientProxyClass.key_leftthrow.getDisplayName() + \" \" + grapplemod.proxy.localize(\"grappletooltip.throwleft.desc\"));\n\t\t\t\t\tlist.add(ClientProxyClass.key_rightthrow.getDisplayName() + \" \" + grapplemod.proxy.localize(\"grappletooltip.throwright.desc\"));\n\t\t\t\t} else {\n\t\t\t\t\tlist.add(ClientProxyClass.key_leftthrow.getDisplayName() + \" \" + grapplemod.proxy.localize(\"grappletooltip.throwlefthold.desc\"));\n\t\t\t\t\tlist.add(ClientProxyClass.key_rightthrow.getDisplayName() + \" \" + grapplemod.proxy.localize(\"grappletooltip.throwrighthold.desc\"));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlist.add(ClientProxyClass.key_rightthrow.getDisplayName() + \" \" + grapplemod.proxy.localize(\"grappletooltip.throwalt.desc\"));\n\t\t\t}\n\t\t} else {\n\t\t\tif (Keyboard.isKeyDown(Keyboard.KEY_LCONTROL)) {\n\t\t\t\tfor (String option : GrappleCustomization.booleanoptions) {\n\t\t\t\t\tif (custom.isoptionvalid(option) && custom.getBoolean(option)) {\n\t\t\t\t\t\tlist.add(grapplemod.proxy.localize(custom.getName(option)));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (String option : GrappleCustomization.doubleoptions) {\n\t\t\t\t\tif (custom.isoptionvalid(option)) {\n\t\t\t\t\t\tlist.add(grapplemod.proxy.localize(custom.getName(option)) + \": \" + Math.floor(custom.getDouble(option) * 100) / 100);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (custom.doublehook) {\n\t\t\t\t\tlist.add(grapplemod.proxy.localize(custom.getName(\"doublehook\")));\n\t\t\t\t}\n\t\t\t\tif (custom.motor) {\n\t\t\t\t\tif (custom.smartmotor) {\n\t\t\t\t\t\tlist.add(grapplemod.proxy.localize(custom.getName(\"smartmotor\")));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlist.add(grapplemod.proxy.localize(custom.getName(\"motor\")));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (custom.enderstaff) {\n\t\t\t\t\tlist.add(grapplemod.proxy.localize(custom.getName(\"enderstaff\")));\n\t\t\t\t}\n\t\t\t\tif (custom.rocket) {\n\t\t\t\t\tlist.add(grapplemod.proxy.localize(custom.getName(\"rocket\")));\n\t\t\t\t}\n\t\t\t\tif (custom.attract) {\n\t\t\t\t\tlist.add(grapplemod.proxy.localize(custom.getName(\"attract\")));\n\t\t\t\t}\n\t\t\t\tif (custom.repel) {\n\t\t\t\t\tlist.add(grapplemod.proxy.localize(custom.getName(\"repel\")));\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tlist.add(\"\");\n\t\t\t\tlist.add(grapplemod.proxy.localize(\"grappletooltip.shiftcontrols.desc\"));\n\t\t\t\tlist.add(grapplemod.proxy.localize(\"grappletooltip.controlconfiguration.desc\"));\n\t\t\t}\n\t\t}\n\t\t\n\n\t}\n\n\t\n\t@Override\n @SideOnly(Side.CLIENT)\n public ItemStack getDefaultInstance()\n {\n ItemStack stack = new ItemStack(this);\n this.getCustomization(stack);\n return stack;\n }\n\t\n\t@Override\n public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> items)\n {\n if (this.isInCreativeTab(tab))\n {\n \tItemStack stack = new ItemStack(this);\n \tthis.getCustomization(stack);\n items.add(stack);\n }\n }\n\t\n\t@Override\n\tpublic boolean onDroppedByPlayer(ItemStack item, EntityPlayer player) {\n\t\tint id = player.getEntityId();\n\t\tgrapplemod.sendtocorrectclient(new GrappleDetachMessage(id), id, player.world);\n\t\t\n\t\tif (grapplemod.attached.contains(id)) {\n\t\t\tgrapplemod.attached.remove(id);\n\t\t}\n\t\t\n\t\tif (grapplearrows1.containsKey(player)) {\n\t\t\tgrappleArrow arrow1 = grapplearrows1.get(player);\n\t\t\tsetArrowLeft(player, null);\n\t\t\tif (arrow1 != null) {\n\t\t\t\tarrow1.removeServer();\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (grapplearrows2.containsKey(player)) {\n\t\t\tgrappleArrow arrow2 = grapplearrows2.get(player);\n\t\t\tsetArrowLeft(player, null);\n\t\t\tif (arrow2 != null) {\n\t\t\t\tarrow2.removeServer();\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn super.onDroppedByPlayer(item, player);\n\t}\n}", "public class BaseUpgradeItem extends Item {\n\tpublic String unlocalizedname;\n\tpublic grapplemod.upgradeCategories category;\n\t\n\tpublic BaseUpgradeItem() {\n\t\tsuper();\n\t\tmaxStackSize = 1;\n\t\tsetvars();\n\t\tsetFull3D();\n\t\tsetUnlocalizedName(unlocalizedname);\n\t\t\n\t\tsetCreativeTab(grapplemod.tabGrapplemod);\n\t}\n\t\n\tpublic void setvars() {\n\t\tunlocalizedname = \"baseupgradeitem\";\n\t\tcategory = null;\n\t\tmaxStackSize = 64;\n\t}\n}" ]
import java.util.Map; import javax.annotation.Nullable; import com.yyon.grapplinghook.GrappleConfig; import com.yyon.grapplinghook.GrappleCustomization; import com.yyon.grapplinghook.grapplemod; import com.yyon.grapplinghook.items.grappleBow; import com.yyon.grapplinghook.items.upgrades.BaseUpgradeItem; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Enchantments; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.EnumBlockRenderType; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.NonNullList; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.TextComponentString; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly;
package com.yyon.grapplinghook.blocks; public class BlockGrappleModifier extends Block { public BlockGrappleModifier() { super(Material.ROCK); setCreativeTab(grapplemod.tabGrapplemod); } @Override public boolean hasTileEntity(IBlockState state) { return true; } // Called when the block is placed or loaded client side to get the tile entity // for the block // Should return a new instance of the tile entity for the block @Override public TileEntity createTileEntity(World world, IBlockState state) { return new TileEntityGrappleModifier(); } // the block will render in the SOLID layer. See // http://greyminecraftcoder.blogspot.co.at/2014/12/block-rendering-18.html for // more information. @SideOnly(Side.CLIENT) public BlockRenderLayer getBlockLayer() { return BlockRenderLayer.SOLID; } @Override public boolean isOpaqueCube(IBlockState state) { return true; } @Override public boolean isFullCube(IBlockState state) { return true; } // render using a BakedModel // not required because the default (super method) is MODEL @Override public EnumBlockRenderType getRenderType(IBlockState iBlockState) { return EnumBlockRenderType.MODEL; } @Override public void getDrops(NonNullList<ItemStack> drops, IBlockAccess world, BlockPos pos, IBlockState state, int fortune) { super.getDrops(drops, world, pos, state, fortune); TileEntity ent = world.getTileEntity(pos); TileEntityGrappleModifier tileent = (TileEntityGrappleModifier) ent; for (grapplemod.upgradeCategories category : grapplemod.upgradeCategories.values()) { if (tileent.unlockedCategories.containsKey(category) && tileent.unlockedCategories.get(category)) { drops.add(new ItemStack(category.getItem())); } } } @Override public boolean removedByPlayer(IBlockState state, World world, BlockPos pos, EntityPlayer player, boolean willHarvest) { if (willHarvest) return true; //If it will harvest, delay deletion of the block until after getDrops return super.removedByPlayer(state, world, pos, player, willHarvest); } /** * Spawns the block's drops in the world. By the time this is called the Block has possibly been set to air via * Block.removedByPlayer */ @Override public void harvestBlock(World world, EntityPlayer player, BlockPos pos, IBlockState state, @Nullable TileEntity te, ItemStack tool) { super.harvestBlock(world, player, pos, state, te, tool); world.setBlockToAir(pos); } @Override public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { ItemStack helditemstack = playerIn.getHeldItemMainhand(); Item helditem = helditemstack.getItem(); if (helditem instanceof BaseUpgradeItem) { if (!worldIn.isRemote) { TileEntity ent = worldIn.getTileEntity(pos); TileEntityGrappleModifier tileent = (TileEntityGrappleModifier) ent; grapplemod.upgradeCategories category = ((BaseUpgradeItem) helditem).category; if (tileent.isUnlocked(category)) { playerIn.sendMessage(new TextComponentString("Already has upgrade: " + category.description)); } else { if (!playerIn.capabilities.isCreativeMode) { playerIn.setHeldItem(EnumHand.MAIN_HAND, ItemStack.EMPTY); } tileent.unlockCategory(category); playerIn.sendMessage(new TextComponentString("Applied upgrade: " + category.description)); } } } else if (helditem instanceof grappleBow) { if (!worldIn.isRemote) { TileEntity ent = worldIn.getTileEntity(pos); TileEntityGrappleModifier tileent = (TileEntityGrappleModifier) ent;
GrappleCustomization custom = tileent.customization;
1
mini2Dx/miniscript
core/src/test/java/org/mini2Dx/miniscript/core/dummy/DummyScriptExecutorPool.java
[ "public abstract class GameScript<S> {\n\tprivate static final AtomicInteger ID_GENERATOR = new AtomicInteger(0);\n\t\n\tprivate final int id;\n\t\n\tpublic GameScript() {\n\t\tsuper();\n\t\tid = ID_GENERATOR.incrementAndGet();\n\t}\n\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\n\tpublic abstract S getScript();\n\n\tpublic abstract boolean hasScript();\n\n\tpublic abstract void setScript(S script);\n\n\tpublic static void offsetIds(int offset) {\n\t\tID_GENERATOR.set(offset);\n\t}\n}", "public abstract class GameScriptingEngine implements Runnable {\n\t/**\n\t * Returns the most recently created {@link GameScriptingEngine}\n\t */\n\tpublic static GameScriptingEngine MOST_RECENT_INSTANCE = null;\n\n\tpublic static Locks LOCK_PROVIDER = new JvmLocks();\n\n\tprivate static final int DEFAULT_MAX_CONCURRENT_SCRIPTS = 2;\n\n\tprivate final ScriptInvocationPool scriptInvocationPool = new ScriptInvocationPool();\n\tprivate final ScriptInvocationQueue scriptInvocationQueue = new ScriptInvocationQueue();\n\tfinal Queue<ScriptNotification> scriptNotifications = new ReadWriteArrayQueue<ScriptNotification>();\n\tprivate final InteractiveScriptListener interactiveScriptListener;\n\n\tfinal ReadWriteArrayQueue<GameFuture> queuedFutures = new ReadWriteArrayQueue<>();\n\tfinal ReadWriteIntMap<GameFuture> runningFutures = new ReadWriteIntMap<GameFuture>();\n\tprivate final ReadWriteIntMap<ScriptExecutionTask<?>> runningScripts = new ReadWriteIntMap<ScriptExecutionTask<?>>();\n\tprivate final IntSet completedFutures = new IntSet();\n\tprivate final IntSet completedScripts = new IntSet();\n\n\tprivate final List<String> tmpRunningScripts = new ArrayList<>();\n\n\tprivate final ThreadPoolProvider threadPoolProvider;\n\tprivate final ScriptExecutorPool<?> scriptExecutorPool;\n\n\tprivate ScheduledFuture cleanupTask;\n\tprivate boolean cancelReallocatedFutures = true;\n\n\tprivate Thread gameThread = null;\n\n\tprivate final AtomicBoolean shuttingDown = new AtomicBoolean(false);\n\n\t/**\n\t * Constructs a scripting engine backed by a thread pool with the maximum\n\t * amount of concurrent scripts set to 2.\n\t * Sandboxing is enabled if the implementation supports it.\n\t */\n\tpublic GameScriptingEngine() {\n\t\tthis(DEFAULT_MAX_CONCURRENT_SCRIPTS);\n\t}\n\n\tpublic GameScriptingEngine(ThreadPoolProvider threadPoolProvider) {\n\t\tthis(DEFAULT_MAX_CONCURRENT_SCRIPTS, threadPoolProvider);\n\t}\n\n\t/**\n\t * Constructs a scripting engine backed by a thread pool. Sandboxing is\n\t * enabled if the implementation supports it.\n\t * \n\t * @param maxConcurrentScripts\n\t * The maximum amount of concurrently running scripts. WARNING:\n\t * this is a 'requested' amount and may be less due to the amount\n\t * of available processors on the player's machine.\n\t */\n\tpublic GameScriptingEngine(int maxConcurrentScripts) {\n\t\tthis(new NoopClasspathScriptProvider(), maxConcurrentScripts);\n\t}\n\n\tpublic GameScriptingEngine(int maxConcurrentScripts, ThreadPoolProvider threadPoolProvider) {\n\t\tthis(new NoopClasspathScriptProvider(), maxConcurrentScripts, threadPoolProvider);\n\t}\n\n\t/**\n\t * Constructs a scripting engine backed by a thread pool. Sandboxing is\n\t * enabled if the implementation supports it.\n\t * @param classpathScriptProvider The auto-generated {@link ClasspathScriptProvider} for the game\n\t * @param maxConcurrentScripts The maximum amount of concurrently running scripts. WARNING:\n\t * this is a 'requested' amount and may be less due to the amount\n\t * of available processors on the player's machine.\n\t */\n\tpublic GameScriptingEngine(ClasspathScriptProvider classpathScriptProvider, int maxConcurrentScripts) {\n\t\tsuper();\n\t\tinteractiveScriptListener = new InteractiveScriptListener(this, scriptInvocationQueue);\n\t\tscriptExecutorPool = createScriptExecutorPool(classpathScriptProvider, maxConcurrentScripts, isSandboxingSupported());\n\n\t\tthreadPoolProvider = new DefaultThreadPoolProvider(maxConcurrentScripts + 1);\n\t\tinit(maxConcurrentScripts);\n\t}\n\n\tpublic GameScriptingEngine(ClasspathScriptProvider classpathScriptProvider, int maxConcurrentScripts, ThreadPoolProvider threadPoolProvider) {\n\t\tsuper();\n\t\tinteractiveScriptListener = new InteractiveScriptListener(this, scriptInvocationQueue);\n\t\tscriptExecutorPool = createScriptExecutorPool(classpathScriptProvider, maxConcurrentScripts, isSandboxingSupported());\n\n\t\tthis.threadPoolProvider = threadPoolProvider;\n\t\tinit(maxConcurrentScripts);\n\t}\n\n\t/**\n\t * Constructs a scripting engine backed by a thread pool with the maximum\n\t * amount of concurrent scripts set to the amount of processors + 1.\n\t * \n\t * @param sandboxed\n\t * True if script sandboxing should be enabled\n\t */\n\tpublic GameScriptingEngine(boolean sandboxed) {\n\t\tthis(new NoopClasspathScriptProvider(), sandboxed);\n\t}\n\n\tpublic GameScriptingEngine(ThreadPoolProvider threadPoolProvider, boolean sandboxed) {\n\t\tthis(new NoopClasspathScriptProvider(), threadPoolProvider, sandboxed);\n\t}\n\n\t/**\n\t * Constructs a scripting engine backed by a thread pool with the maximum\n\t * amount of concurrent scripts set to 2.\n\t * @param classpathScriptProvider The auto-generated {@link ClasspathScriptProvider} for the game\n\t * @param sandboxed True if script sandboxing should be enabled\n\t */\n\tpublic GameScriptingEngine(ClasspathScriptProvider classpathScriptProvider, boolean sandboxed) {\n\t\tthis(classpathScriptProvider,DEFAULT_MAX_CONCURRENT_SCRIPTS, sandboxed);\n\t}\n\n\tpublic GameScriptingEngine(ClasspathScriptProvider classpathScriptProvider, ThreadPoolProvider threadPoolProvider, boolean sandboxed) {\n\t\tthis(classpathScriptProvider,DEFAULT_MAX_CONCURRENT_SCRIPTS, threadPoolProvider, sandboxed);\n\t}\n\n\t/**\n\t * Constructs a scripting engine backed by a thread pool.\n\t * \n\t * @param maxConcurrentScripts\n\t * The maximum amount of concurrently running scripts. WARNING:\n\t * this is a 'requested' amount and may be less due to the amount\n\t * of available processors on the player's machine.\n\t * @param sandboxed\n\t * True if script sandboxing should be enabled\n\t */\n\tpublic GameScriptingEngine(int maxConcurrentScripts, boolean sandboxed) {\n\t\tthis(new NoopClasspathScriptProvider(), maxConcurrentScripts, sandboxed);\n\t}\n\n\tpublic GameScriptingEngine(int maxConcurrentScripts, ThreadPoolProvider threadPoolProvider, boolean sandboxed) {\n\t\tthis(new NoopClasspathScriptProvider(), maxConcurrentScripts, threadPoolProvider, sandboxed);\n\t}\n\n\t/**\n\t * Constructs a scripting engine backed by a thread pool.\n\t * @param classpathScriptProvider The auto-generated {@link ClasspathScriptProvider} for the game\n\t * @param maxConcurrentScripts The maximum amount of concurrently running scripts. WARNING:\n\t * this is a 'requested' amount and may be less due to the amount\n\t * of available processors on the player's machine.\n\t * @param sandboxed True if script sandboxing should be enabled\n\t */\n\tpublic GameScriptingEngine(ClasspathScriptProvider classpathScriptProvider,\n\t int maxConcurrentScripts, boolean sandboxed) {\n\t\tsuper();\n\t\tinteractiveScriptListener = new InteractiveScriptListener(this, scriptInvocationQueue);\n\t\tscriptExecutorPool = createScriptExecutorPool(classpathScriptProvider, maxConcurrentScripts, sandboxed);\n\n\t\tthreadPoolProvider = new DefaultThreadPoolProvider(maxConcurrentScripts + 1);\n\t\tinit(maxConcurrentScripts);\n\t}\n\n\tpublic GameScriptingEngine(ClasspathScriptProvider classpathScriptProvider,\n\t int maxConcurrentScripts, ThreadPoolProvider threadPoolProvider, boolean sandboxed) {\n\t\tsuper();\n\t\tinteractiveScriptListener = new InteractiveScriptListener(this, scriptInvocationQueue);\n\t\tscriptExecutorPool = createScriptExecutorPool(classpathScriptProvider, maxConcurrentScripts, sandboxed);\n\n\t\tthis.threadPoolProvider = threadPoolProvider;\n\t\tinit(maxConcurrentScripts);\n\t}\n\n\tprivate void init(int maxConcurrentScripts) {\n\t\tfor(int i = 0; i < maxConcurrentScripts; i++) {\n\t\t\tthreadPoolProvider.scheduleAtFixedRate(this, 16L, 16L, TimeUnit.MILLISECONDS);\n\t\t}\n\t\tthreadPoolProvider.scheduleAtFixedRate(new Runnable() {\n\t\t\t@Override\n\t\t\tpublic void run() {\n\t\t\t\ttry {\n\t\t\t\t\tcleanupCompletedFutures();\n\t\t\t\t\tcleanupCompletedScripts();\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t}, 0L, 1L, TimeUnit.SECONDS);\n\t\tMOST_RECENT_INSTANCE = this;\n\t}\n\n\t/**\n\t * Shuts down the thread pool and cleans up resources\n\t */\n\tpublic void dispose() {\n\t\tdispose(false);\n\t}\n\n\t/**\n\t * Shuts down the thread pool and cleans up resources\n\t * @param interruptScripts True if running scripts should be interrupted\n\t */\n\tpublic void dispose(boolean interruptScripts) {\n\t\tshuttingDown.set(true);\n\n\t\tif(cleanupTask != null) {\n\t\t\tcleanupTask.cancel(false);\n\t\t\tcleanupTask = null;\n\t\t}\n\t\tthreadPoolProvider.shutdown(interruptScripts);\n\n\t\tif(!interruptScripts) {\n\t\t\treturn;\n\t\t}\n\t\tcancelAllQueuedScripts();\n\t\tskipAllQueuedGameFutures();\n\t\tskipAllScripts();\n\t}\n\n\t/**\n\t * Checks if sandboxing is supported by the {@link GameScriptingEngine}\n\t * implementation\n\t * \n\t * @return True if sandboxing is supported\n\t */\n\tpublic abstract boolean isSandboxingSupported();\n\n\t/**\n\t * Checks if scripts can be synchronously run within other scripts\n\t *\n\t * @return True if scripts can be invoke synchronously within scripts\n\t */\n\tpublic abstract boolean isEmbeddedSynchronousScriptSupported();\n\n\tprotected abstract ScriptExecutorPool<?> createScriptExecutorPool(ClasspathScriptProvider classpathScriptProvider,\n\t int poolSize, boolean sandboxing);\n\n\t/**\n\t * Updates all {@link GameFuture}s\n\t * \n\t * @param delta\n\t * The time (in seconds) since the last frame update\n\t */\n\tpublic void update(float delta) {\n\t\tif(gameThread == null) {\n\t\t\tgameThread = Thread.currentThread();\n\t\t}\n\n\t\tfor (GameFuture gameFuture : runningFutures.values()) {\n\t\t\tif(gameFuture == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tgameFuture.evaluate(delta);\n\t\t}\n\n\t\twhile (!queuedFutures.isEmpty()) {\n\t\t\tGameFuture nextFuture = queuedFutures.poll();\n\t\t\tGameFuture previousFuture = runningFutures.put(nextFuture.getFutureId(), nextFuture);\n\t\t\tif (previousFuture == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!cancelReallocatedFutures) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tpreviousFuture.skipFuture();\n\t\t\t} catch (Exception e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\n\t\twhile (!scriptNotifications.isEmpty()) {\n\t\t\tscriptNotifications.poll().process();\n\t\t}\n\t}\n\n\t/**\n\t * This should not be invoked by the developer. Call {@link #update(float)}\n\t * instead.\n\t */\n\t@Override\n\tpublic void run() {\n\t\tif(shuttingDown.get()) {\n\t\t\treturn;\n\t\t}\n\t\tlong startTime = System.currentTimeMillis();\n\t\tScriptInvocation scriptInvocation = null;\n\t\ttry {\n\t\t\twhile ((scriptInvocation = scriptInvocationQueue.poll()) != null) {\n\t\t\t\tif(shuttingDown.get()) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfinal ScriptInvocationListener invocationListener;\n\t\t\t\tif(scriptInvocation.isInteractive()) {\n\t\t\t\t\tinteractiveScriptListener.track(scriptInvocation.getScriptId(), scriptInvocation.getInvocationListener());\n\t\t\t\t\tinvocationListener = interactiveScriptListener;\n\t\t\t\t} else {\n\t\t\t\t\tinvocationListener = scriptInvocation.getInvocationListener();\n\t\t\t\t}\n\n\t\t\t\tScriptExecutionTask<?> executionTask = scriptExecutorPool.execute(scriptInvocation.getTaskId(),\n\t\t\t\t\t\tscriptInvocation.getScriptId(), scriptInvocation.getScriptBindings(), invocationListener, false);\n\t\t\t\tFuture<?> taskFuture = threadPoolProvider.submit(executionTask);\n\t\t\t\texecutionTask.setTaskFuture(taskFuture);\n\t\t\t\trunningScripts.put(executionTask.getTaskId(), executionTask);\n\t\t\t\tscriptInvocation.release();\n\t\t\t}\n\t\t} catch (NoSuchScriptException e) {\n\t\t\tif(scriptInvocation != null) {\n\t\t\t\tif(scriptInvocation.getInvocationListener() != null) {\n\t\t\t\t\tscriptInvocation.getInvocationListener().onScriptException(scriptInvocation.getScriptId(), e);\n\t\t\t\t}\n\t\t\t\tinteractiveScriptListener.onScriptException(scriptInvocation.getScriptId(), e);\n\t\t\t} else {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\tif(shuttingDown.get()) {\n\t\t\treturn;\n\t\t}\n\t}\n\n\tprivate void cleanupCompletedFutures() {\n\t\tfor (GameFuture gameFuture : runningFutures.values()) {\n\t\t\tif(gameFuture == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (gameFuture.isReadyForGC()) {\n\t\t\t\tcompletedFutures.add(gameFuture.getFutureId());\n\t\t\t}\n\t\t}\n\t\tfinal IntSet.IntSetIterator iterator = completedFutures.iterator();\n\t\twhile(iterator.hasNext) {\n\t\t\tfinal int futureId = iterator.next();\n\t\t\trunningFutures.remove(futureId);\n\t\t}\n\t\tcompletedFutures.clear();\n\t}\n\n\tprivate void cleanupCompletedScripts() {\n\t\tfor (ScriptExecutionTask<?> scriptExecutionTask : runningScripts.values()) {\n\t\t\tif(scriptExecutionTask == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (scriptExecutionTask.isFinished()) {\n\t\t\t\tscriptExecutionTask.cleanup();\n\t\t\t\tcompletedScripts.add(scriptExecutionTask.getTaskId());\n\t\t\t}\n\t\t}\n\t\tfinal IntSet.IntSetIterator iterator = completedScripts.iterator();\n\t\twhile(iterator.hasNext) {\n\t\t\tfinal int taskId = iterator.next();\n\t\t\trunningScripts.remove(taskId);\n\t\t}\n\t\tcompletedScripts.clear();\n\t}\n\n\t/**\n\t * Skips all currently running scripts\n\t */\n\tpublic void skipAllScripts() {\n\t\tfor (ScriptExecutionTask<?> scriptExecutionTask : runningScripts.values()) {\n\t\t\tif(scriptExecutionTask == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tscriptExecutionTask.skipScript();\n\t\t}\n\t}\n\n\t/**\n\t * Skips all running instances of a script\n\t * \n\t * @param scriptId\n\t * The ID of the script to skip\n\t */\n\tpublic void skipScript(int scriptId) {\n\t\tfinal IntMap.Keys keys = runningScripts.keys();\n\t\twhile(keys.hasNext) {\n\t\t\tfinal int taskId = keys.next();\n\t\t\tScriptExecutionTask<?> scriptExecutionTask = runningScripts.get(taskId);\n\t\t\tif (scriptExecutionTask == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (scriptExecutionTask.getScriptId() != scriptId) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tscriptExecutionTask.skipScript();\n\t\t}\n\t}\n\n\t/**\n\t * Skips a specific running instance of a script\n\t *\n\t * @param taskId The ID of the task to skip\n\t */\n\tpublic void skipScriptByTaskId(int taskId) {\n\t\tfinal IntMap.Keys keys = runningScripts.keys();\n\t\twhile(keys.hasNext) {\n\t\t\tfinal int otherTaskId = keys.next();\n\t\t\tif(taskId != otherTaskId) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tScriptExecutionTask<?> scriptExecutionTask = runningScripts.get(taskId);\n\t\t\tif (scriptExecutionTask == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tscriptExecutionTask.skipScript();\n\t\t}\n\t}\n\n\t/**\n\t * Skips all currently running {@link GameFuture}s\n\t */\n\tpublic void skipAllRunningGameFutures() {\n\t\tfor (GameFuture gameFuture : runningFutures.values()) {\n\t\t\tif(gameFuture == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tgameFuture.skipFuture();\n\t\t}\n\t}\n\n\t/**\n\t * Skips all currently queued {@link GameFuture}s\n\t */\n\tpublic void skipAllQueuedGameFutures() {\n\t\twhile(!queuedFutures.isEmpty()) {\n\t\t\tfinal GameFuture gameFuture = queuedFutures.poll();\n\t\t\tif(gameFuture == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tgameFuture.skipFuture();\n\t\t}\n\t}\n\n\t/**\n\t * Removes all currently running {@link GameFuture}s without sending skipFuture event\n\t */\n\tpublic void cancelAllRunningGameFutures() {\n\t\trunningFutures.clear();\n\t}\n\n\t/**\n\t * Removes all currently queued {@link GameFuture}s without sending skipFuture event\n\t */\n\tpublic void cancelAllQueuedGameFutures() {\n\t\tqueuedFutures.clear();\n\t}\n\n\t/**\n\t * Removes all currently queued {@link GameFuture}s without sending skipFuture event\n\t */\n\tpublic void cancelAllQueuedScripts() {\n\t\tcancelAllQueuedScripts(true);\n\t}\n\n\t/**\n\t * Removes all currently queued {@link GameFuture}s without sending skipFuture event\n\t * @param notifyListeners If true will notify invocation listeners of script cancellation\n\t */\n\tpublic void cancelAllQueuedScripts(boolean notifyListeners) {\n\t\tif(!notifyListeners) {\n\t\t\tscriptInvocationQueue.clear();\n\t\t\treturn;\n\t\t}\n\n\t\tfinal List<ScriptInvocation> scriptInvocations = new ArrayList<>();\n\t\tscriptInvocationQueue.clear(scriptInvocations);\n\t\tnotifyScriptCancelled(scriptInvocations);\n\t}\n\n\t/**\n\t * Removes all currently queued scripts with a given script ID\n\t */\n\tpublic void cancelQueuedScript(int scriptId) {\n\t\tcancelQueuedScript(scriptId, true);\n\t}\n\n\t/**\n\t * Removes a specific queued script by its task ID\n\t */\n\tpublic void cancelQueuedScriptByTaskId(int taskId) {\n\t\tcancelQueuedScriptByTaskId(taskId, true);\n\t}\n\n\t/**\n\t * Removes all currently queued scripts with a given script ID\n\t * @param notifyListeners If true will notify invocation listeners of script cancellation\n\t */\n\tpublic void cancelQueuedScript(int scriptId, boolean notifyListeners) {\n\t\tfinal List<ScriptInvocation> scriptInvocations = new ArrayList<>();\n\t\tscriptInvocationQueue.cancelByScriptId(scriptId, scriptInvocations);\n\t\tif(!notifyListeners) {\n\t\t\tscriptInvocations.clear();\n\t\t\treturn;\n\t\t}\n\n\t\tnotifyScriptCancelled(scriptInvocations);\n\t}\n\n\t/**\n\t * Removes a specific queued script by its task ID\n\t * @param notifyListeners If true will notify invocation listeners of script cancellation\n\t */\n\tpublic void cancelQueuedScriptByTaskId(int taskId, boolean notifyListeners) {\n\t\tfinal List<ScriptInvocation> scriptInvocations = new ArrayList<>();\n\t\tscriptInvocationQueue.cancelByTaskId(taskId, scriptInvocations);\n\t\tif(!notifyListeners) {\n\t\t\tscriptInvocations.clear();\n\t\t\treturn;\n\t\t}\n\n\t\tnotifyScriptCancelled(scriptInvocations);\n\t}\n\n\t/**\n\t * Clears all interactive scripts queued\n\t */\n\tpublic void cancelAllQueuedInteractiveScripts() {\n\t\tcancelAllQueuedInteractiveScripts(true);\n\t}\n\n\t/**\n\t * Clears all non-interactive scripts queued\n\t */\n\tpublic void cancelAllQueuedNonInteractiveScripts() {\n\t\tcancelAllQueuedNonInteractiveScripts(true);\n\t}\n\n\t/**\n\t * Clears all interactive scripts queued\n\t * @param notifyListeners If true will send the scriptSkipped event any listener associated with a cancelled invoke\n\t */\n\tpublic void cancelAllQueuedInteractiveScripts(boolean notifyListeners) {\n\t\tif(!notifyListeners) {\n\t\t\tscriptInvocationQueue.clearInteractiveScriptQueue();\n\t\t\treturn;\n\t\t}\n\n\t\tfinal List<ScriptInvocation> scriptInvocations = new ArrayList<>();\n\t\tscriptInvocationQueue.clearInteractiveScriptQueue(scriptInvocations);\n\t\tnotifyScriptCancelled(scriptInvocations);\n\t}\n\n\t/**\n\t * Clears all non-interactive scripts queued\n\t * @param notifyListeners If true will send the scriptSkipped event any listener associated with a cancelled invoke\n\t */\n\tpublic void cancelAllQueuedNonInteractiveScripts(boolean notifyListeners) {\n\t\tif(!notifyListeners) {\n\t\t\tscriptInvocationQueue.clearNonInteractiveScriptQueue();\n\t\t\treturn;\n\t\t}\n\n\t\tfinal List<ScriptInvocation> scriptInvocations = new ArrayList<>();\n\t\tscriptInvocationQueue.clearNonInteractiveScriptQueue(scriptInvocations);\n\t\tnotifyScriptCancelled(scriptInvocations);\n\t}\n\n\t/**\n\t * Cancels a queued script or skips it if it is currently running\n\t * @param scriptId The script ID\n\t */\n\tpublic void skipOrCancelScript(int scriptId) {\n\t\ttry {\n\t\t\tskipScript(scriptId);\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\ttry {\n\t\t\tcancelQueuedScript(scriptId);\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t/**\n\t * Cancels a specific invocation of a script by its task ID, or skips it if it is currently running\n\t * @param taskId The task ID\n\t */\n\tpublic void skipOrCancelScriptByTaskId(int taskId) {\n\t\ttry {\n\t\t\tskipScriptByTaskId(taskId);\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\ttry {\n\t\t\tcancelQueuedScriptByTaskId(taskId);\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t/**\n\t * Compiles a script for execution. Note it is best to call this\n\t * sequentially before any script executions to avoid throwing a\n\t * {@link InsufficientCompilersException}.\n\t *\n\t * Note: If the filepath has already been compiled, the script will not be compiled and the previous compilation is used.\n\t *\n\t * @param filepath The filepath to store for the script\n\t * @param scriptContent\n\t * The text contents of the script\n\t * @return The unique id for the script\n\t * @throws InsufficientCompilersException\n\t * Thrown if there are no script compilers available\n\t * @throws InsufficientCompilersException\n\t * Thrown if there are no script compilers available\n\t */\n\tpublic int compileScript(String filepath, String scriptContent) throws InsufficientCompilersException {\n\t\tfinal int existingId = scriptExecutorPool.getCompiledScriptId(filepath);\n\t\tif(existingId > -1) {\n\t\t\treturn existingId;\n\t\t}\n\t\treturn scriptExecutorPool.preCompileScript(filepath, scriptContent);\n\t}\n\n\t/**\n\t * Compiles a script for execution. Note it is best to call this\n\t * sequentially before any script executions to avoid throwing a\n\t * {@link InsufficientCompilersException}.\n\t *\n\t * @param scriptContent\n\t * The text contents of the script\n\t * @return The unique id for the script\n\t * @throws InsufficientCompilersException\n\t * Thrown if there are no script compilers available\n\t * @throws InsufficientCompilersException\n\t * Thrown if there are no script compilers available\n\t */\n\tpublic int compileScript(String scriptContent) throws InsufficientCompilersException {\n\t\treturn compileScript(String.valueOf(scriptContent.hashCode()), scriptContent);\n\t}\n\n\t/**\n\t * Returns the script ID for a given filepath\n\t * @param filepath The filepath to lookup\n\t * @return -1 if the script has not been compiled\n\t */\n\tpublic int getCompiledScriptId(String filepath) {\n\t\treturn scriptExecutorPool.getCompiledScriptId(filepath);\n\t}\n\n\t/**\n\t * Compiles a script for execution. Note it is best to call this\n\t * sequentially before any script executions to avoid throwing a\n\t * {@link InsufficientCompilersException}\n\t * \n\t * @param inputStream\n\t * The {@link InputStream} to read the script contents from\n\t * @return The unique id for the script\n\t * @throws InsufficientCompilersException\n\t * Thrown if there are no script compilers available\n\t * @throws IOException\n\t * Throw if the {@link InputStream} could not be read or closed\n\t */\n\tpublic int compileScript(String filepath, InputStream inputStream) throws InsufficientCompilersException, IOException {\n\t\tScanner scanner = new Scanner(inputStream);\n\t\tscanner.useDelimiter(\"\\\\A\");\n\t\tString contents = scanner.hasNext() ? scanner.next() : \"\";\n\t\tscanner.close();\n\t\tinputStream.close();\n\t\treturn compileScript(filepath, contents);\n\t}\n\n\t/**\n\t * Queues a compiled script for execution in the engine's thread pool\n\t * \n\t * @param scriptId\n\t * The id of the script to run\n\t * @param scriptBindings\n\t * The variable bindings for the script\n\t * @return The unique task ID for this invocation\n\t */\n\tpublic int invokeCompiledScript(int scriptId, ScriptBindings scriptBindings) {\n\t\treturn invokeCompiledScript(scriptId, scriptBindings, null);\n\t}\n\n\t/**\n\t * Queues a compiled script for execution in the engine's thread pool\n\t * \n\t * @param scriptId\n\t * The id of the script to run\n\t * @param scriptBindings\n\t * The variable bindings for the script\n\t * @param invocationListener\n\t * A {@link ScriptInvocationListener} to list for invocation\n\t * results\n\t * @return The unique task ID for this invocation\n\t */\n\tpublic int invokeCompiledScript(int scriptId, ScriptBindings scriptBindings,\n\t\t\tScriptInvocationListener invocationListener) {\n\t\treturn invokeCompiledScript(scriptId, scriptBindings, invocationListener, 0);\n\t}\n\n\t/**\n\t * Queues a compiled script for execution in the engine's thread pool\n\t *\n\t * @param scriptId\n\t * The id of the script to run\n\t * @param scriptBindings\n\t * The variable bindings for the script\n\t * @param invocationListener\n\t * A {@link ScriptInvocationListener} to list for invocation results\n\t * @param priority The script execution priority (higher value = higher priority)\n\t * @return The unique task ID for this invocation\n\t */\n\tpublic int invokeCompiledScript(int scriptId, ScriptBindings scriptBindings,\n\t\t\t\t\t\t\t\t\t ScriptInvocationListener invocationListener, int priority) {\n\t\treturn invokeCompiledScript(scriptId, scriptBindings, invocationListener, priority, false);\n\t}\n\n\t/**\n\t * Queues a compiled script for execution in the engine's thread pool\n\t *\n\t * @param scriptId\n\t * The id of the script to run\n\t * @param scriptBindings\n\t * The variable bindings for the script\n\t * @param invocationListener\n\t * A {@link ScriptInvocationListener} to list for invocation results\n\t * @param priority The script execution priority (higher value = higher priority)\n\t * @return The unique task ID for this invocation\n\t */\n\tpublic int invokeCompiledScript(int scriptId, ScriptBindings scriptBindings,\n\t ScriptInvocationListener invocationListener, int priority, boolean interactive) {\n\t\tfinal ScriptInvocation invocation = scriptInvocationPool.allocate(scriptId, scriptBindings, invocationListener, priority, interactive);\n\t\tscriptInvocationQueue.offer(invocation);\n\t\treturn invocation.getTaskId();\n\t}\n\n\t/**\n\t * Compiles and queues a script for execution in the engine's thread pool\n\t * \n\t * @param scriptContent\n\t * The text content of the script\n\t * @param scriptBindings\n\t * The variable bindings for the script\n\t * @return The unique id for the script\n\t * @throws InsufficientCompilersException\n\t * Thrown if there are no script compilers available\n\t */\n\tpublic int invokeScript(String scriptContent, ScriptBindings scriptBindings) throws InsufficientCompilersException {\n\t\treturn invokeScript(scriptContent, scriptBindings, null);\n\t}\n\n\t/**\n\t * Compiles and queues a script for execution in the engine's thread pool\n\t * \n\t * @param scriptContent\n\t * The text content of the script\n\t * @param scriptBindings\n\t * The variable bindings for the script\n\t * @param invocationListener\n\t * A {@link ScriptInvocationListener} to list for invocation\n\t * results\n\t * @return The unique id for the script\n\t * @throws InsufficientCompilersException\n\t * Thrown if there are no script compilers available\n\t */\n\tpublic int invokeScript(String scriptContent, ScriptBindings scriptBindings,\n\t\t\tScriptInvocationListener invocationListener) throws InsufficientCompilersException {\n\t\tint scriptId = compileScript(String.valueOf(scriptContent.hashCode()), scriptContent);\n\t\tinvokeCompiledScript(scriptId, scriptBindings, invocationListener);\n\t\treturn scriptId;\n\t}\n\n\t/**\n\t * Compiles and queues a script for execution in the engine's thread pool\n\t *\n\t * @param scriptContent\n\t * The text content of the script\n\t * @param scriptBindings\n\t * The variable bindings for the script\n\t * @param invocationListener\n\t * A {@link ScriptInvocationListener} to list for invocation\n\t * results\n\t * @param priority The script execution priority (higher value = higher priority)\n\t * @return The unique id for the script\n\t * @throws InsufficientCompilersException\n\t * Thrown if there are no script compilers available\n\t */\n\tpublic int invokeScript(String scriptContent, ScriptBindings scriptBindings,\n\t\t\t\t\t\t\tScriptInvocationListener invocationListener, int priority) throws InsufficientCompilersException {\n\t\tint scriptId = compileScript(String.valueOf(scriptContent.hashCode()), scriptContent);\n\t\tinvokeCompiledScript(scriptId, scriptBindings, invocationListener, priority);\n\t\treturn scriptId;\n\t}\n\n\t/**\n\t * Executes a compiled script synchronously on the thread calling this method.\n\t * \n\t * Warning: If no {@link ScriptExecutor}s are available this will block\n\t * until one is available\n\t *\n\t * @param taskId The task id\n\t * @param scriptId The script id\n\t * @param scriptBindings The variable bindings for the script\n\t */\n\tpublic void invokeCompiledScriptSync(int taskId, int scriptId, ScriptBindings scriptBindings) {\n\t\tinvokeCompiledScriptSync(taskId, scriptId, scriptBindings, null);\n\t}\n\n\t/**\n\t * Executes a compiled script synchronously on the thread calling this method.\n\t * \n\t * Warning: If no {@link ScriptExecutor}s are available this will block\n\t * until one is available\n\t *\n\t * @param taskId The task id\n\t * @param scriptId The script id\n\t * @param scriptBindings The variable bindings for the script\n\t * @param invocationListener\n\t * A {@link ScriptInvocationListener} to list for invocation\n\t * results\n\t */\n\tpublic void invokeCompiledScriptSync(int taskId, int scriptId, ScriptBindings scriptBindings,\n\t\t\t\t\t\t\t\t\t\t ScriptInvocationListener invocationListener) {\n\t\tScriptExecutionTask<?> executionTask = scriptExecutorPool.execute(taskId, scriptId, scriptBindings, invocationListener, true);\n\t\trunningScripts.put(executionTask.getTaskId(), executionTask);\n\t\texecutionTask.run();\n\t}\n\n\t/**\n\t * Returns the list of currently running scripts.\n\t *\n\t * Note: This list reference is re-used on every invocation of this method\n\t * @return An empty list if nothing running\n\t */\n\tpublic List<String> getRunningScripts() {\n\t\ttmpRunningScripts.clear();\n\t\tfinal IntMap.Keys keys = runningScripts.keys();\n\t\twhile(keys.hasNext) {\n\t\t\tfinal int taskId = keys.next();\n\t\t\tScriptExecutionTask<?> scriptExecutionTask = runningScripts.get(taskId);\n\t\t\tif (scriptExecutionTask == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttmpRunningScripts.add(scriptExecutorPool.getCompiledScriptPath(scriptExecutionTask.getScriptId()));\n\t\t}\n\t\treturn tmpRunningScripts;\n\t}\n\n\t/**\n\t * Returns the total scripts (interactive + non-interactive) queued\n\t * @return 0 if none\n\t */\n\tpublic int getTotalScriptsQueued() {\n\t\treturn scriptInvocationQueue.size();\n\t}\n\n\t/**\n\t * Returns the total interactive scripts queued\n\t * @return 0 if none\n\t */\n\tpublic int getTotalInteractiveScriptsQueued() {\n\t\treturn scriptInvocationQueue.getInteractiveScriptsQueued();\n\t}\n\n\t/**\n\t * Returns the total non-interactive scripts queued\n\t * @return 0 if none\n\t */\n\tpublic int getTotalNonInteractiveScriptsQueued() {\n\t\treturn scriptInvocationQueue.getNonInteractiveScriptsQueued();\n\t}\n\n\t/**\n\t * Returns true if interactive script is running\n\t * @return\n\t */\n\tpublic boolean isInteractiveScriptRunning() {\n\t\treturn scriptInvocationQueue.isInteractiveScriptRunnung();\n\t}\n\n\tvoid submitGameFuture(GameFuture gameFuture) {\n\t\tif(gameThread != null && gameThread == Thread.currentThread()) {\n\t\t\tqueuedFutures.offer(gameFuture);\n\t\t} else {\n\t\t\tqueuedFutures.lazyOffer(gameFuture);\n\t\t}\n\t}\n\n\t/**\n\t * Sets if newly {@link GameFuture}s should cancel a previously scheduled\n\t * {@link GameFuture} with the same ID. IDs attempt be unique but if there\n\t * are {@link GameFuture}s that never complete IDs may come into conflict\n\t * after millions of generated {@link GameFuture}s. Defaults to true.\n\t * \n\t * @param cancelReallocatedFutures\n\t * True if existing {@link GameFuture}s with same ID should be\n\t * cancelled\n\t */\n\tpublic void setCancelReallocatedFutures(boolean cancelReallocatedFutures) {\n\t\tthis.cancelReallocatedFutures = cancelReallocatedFutures;\n\t}\n\n\n\tprivate void notifyScriptCancelled(List<ScriptInvocation> scriptInvocations) {\n\t\tfor(ScriptInvocation invocation : scriptInvocations) {\n\t\t\tif(invocation.getInvocationListener() == null) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfinal ScriptInvocationListener invocationListener = invocation.getInvocationListener();\n\t\t\tif(invocationListener.callOnGameThread()) {\n\t\t\t\tscriptNotifications\n\t\t\t\t\t\t.offer(new ScriptCancelledNotification(invocationListener, invocation.getScriptId()));\n\t\t\t} else {\n\t\t\t\tinvocationListener.onScriptCancelled(invocation.getScriptId());\n\t\t\t}\n\t\t}\n\t\tscriptInvocations.clear();\n\t}\n}", "public class ScriptBindings implements Map<String, Object> {\n\tpublic static final String SCRIPT_ID_VAR = \"scriptId\";\n\tpublic static final String SCRIPT_PARENT_ID_VAR = \"scriptParentId\";\n\tpublic static final String SCRIPT_INVOKE_VAR = \"scripts\";\n\n\tprivate final Map<String, Object> bindings = Collections.synchronizedMap(new HashMap<String, Object>());\n\n\t/**\n\t * Creates a duplicate instance of this {@link ScriptBindings}\n\t * \n\t * @return A new {@link ScriptBindings} instance containing all the same\n\t * bindings as this instance\n\t */\n\tpublic ScriptBindings duplicate() {\n\t\tScriptBindings result = new ScriptBindings();\n\t\tresult.putAll(bindings);\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic int size() {\n\t\treturn bindings.size();\n\t}\n\n\t@Override\n\tpublic boolean isEmpty() {\n\t\treturn bindings.isEmpty();\n\t}\n\n\t@Override\n\tpublic boolean containsKey(Object key) {\n\t\treturn bindings.containsKey(key);\n\t}\n\n\t@Override\n\tpublic boolean containsValue(Object value) {\n\t\treturn bindings.containsValue(value);\n\t}\n\n\t@Override\n\tpublic Object get(Object key) {\n\t\treturn bindings.get(key);\n\t}\n\n\t@Override\n\tpublic Object put(String key, Object value) {\n\t\treturn bindings.put(key, value);\n\t}\n\n\t@Override\n\tpublic Object remove(Object key) {\n\t\treturn bindings.remove(key);\n\t}\n\n\t@Override\n\tpublic void putAll(Map<? extends String, ? extends Object> m) {\n\t\tbindings.putAll(m);\n\t}\n\n\t@Override\n\tpublic void clear() {\n\t\tbindings.clear();\n\t}\n\n\t@Override\n\tpublic Set<String> keySet() {\n\t\treturn bindings.keySet();\n\t}\n\n\t@Override\n\tpublic Collection<Object> values() {\n\t\treturn bindings.values();\n\t}\n\n\t@Override\n\tpublic Set<java.util.Map.Entry<String, Object>> entrySet() {\n\t\treturn bindings.entrySet();\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder result = new StringBuilder(\"ScriptBindings [\");\n\t\tfor (String key : bindings.keySet()) {\n\t\t\tresult.append(key);\n\t\t\tresult.append(\"=\");\n\t\t\tresult.append(bindings.get(key));\n\t\t\tresult.append(\", \");\n\t\t}\n\t\tresult.delete(result.length() - 2, result.length());\n\t\tresult.append(\"]\");\n\t\treturn result.toString();\n\t}\n}", "public class ScriptExecutionTask<S> implements Runnable {\n\tprivate final int taskId;\n\tprivate final int scriptId;\n\tprivate final GameScriptingEngine scriptingEngine;\n\tprivate final ScriptExecutor<S> executor;\n\tprivate final GameScript<S> script;\n\tprivate final ScriptBindings scriptBindings;\n\tprivate final ScriptInvocationListener scriptInvocationListener;\n\tprivate final boolean syncCall;\n\n\tprivate final AtomicBoolean completed = new AtomicBoolean(false);\n\tprivate Future<?> taskFuture;\n\n\tpublic ScriptExecutionTask(int taskId, GameScriptingEngine gameScriptingEngine, ScriptExecutor<S> executor,\n\t\t\t\t\t\t\t int scriptId, GameScript<S> script, ScriptBindings scriptBindings,\n\t\t\t\t\t\t\t ScriptInvocationListener scriptInvocationListener, boolean syncCall) {\n\t\tthis.taskId = taskId;\n\t\tthis.scriptingEngine = gameScriptingEngine;\n\t\tthis.executor = executor;\n\t\tthis.scriptId = scriptId;\n\t\tthis.script = script;\n\t\tthis.scriptBindings = scriptBindings;\n\t\tthis.scriptInvocationListener = scriptInvocationListener;\n\t\tthis.syncCall = syncCall;\n\t}\n\n\t@Override\n\tpublic void run() {\n\t\ttry {\n\t\t\tif(scriptInvocationListener != null) {\n\t\t\t\tif(scriptInvocationListener instanceof InteractiveScriptListener) {\n\t\t\t\t\tfinal ScriptInvocationListener actualListener = ((InteractiveScriptListener) scriptInvocationListener).getInvocationListener();\n\t\t\t\t\tinvokeOnScriptBegin(actualListener);\n\t\t\t\t} else {\n\t\t\t\t\tinvokeOnScriptBegin(scriptInvocationListener);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tScriptExecutionResult executionResult = executor.execute(scriptId, script, scriptBindings,\n\t\t\t\t\tscriptInvocationListener != null);\n\t\t\tif (scriptInvocationListener != null) {\n\t\t\t\tif (scriptInvocationListener.callOnGameThread()) {\n\t\t\t\t\tscriptingEngine.scriptNotifications.offer(\n\t\t\t\t\t\t\tnew ScriptSuccessNotification(scriptInvocationListener, script.getId(), executionResult));\n\t\t\t\t} else {\n\t\t\t\t\tscriptInvocationListener.onScriptSuccess(script.getId(), executionResult);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (InterruptedException | ScriptSkippedException e) {\n\t\t\tif (scriptInvocationListener != null) {\n\t\t\t\tif (scriptInvocationListener.callOnGameThread()) {\n\t\t\t\t\tscriptingEngine.scriptNotifications\n\t\t\t\t\t\t\t.offer(new ScriptSkippedNotification(scriptInvocationListener, script.getId()));\n\t\t\t\t} else {\n\t\t\t\t\tscriptInvocationListener.onScriptSkipped(script.getId());\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\tif (scriptInvocationListener != null) {\n\t\t\t\tif (scriptInvocationListener.callOnGameThread()) {\n\t\t\t\t\tscriptingEngine.scriptNotifications\n\t\t\t\t\t\t\t.offer(new ScriptExceptionNotification(scriptInvocationListener, script.getId(), e));\n\t\t\t\t} else {\n\t\t\t\t\tscriptInvocationListener.onScriptException(script.getId(), e);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\t// Clear interrupted bit\n\t\tThread.interrupted();\n\t\tcompleted.set(true);\n\t}\n\n\tprivate void invokeOnScriptBegin(ScriptInvocationListener listener) throws InterruptedException {\n\t\tif(listener == null) {\n\t\t\treturn;\n\t\t}\n\t\tif(listener.callOnGameThread() && !syncCall) {\n\t\t\tfinal ScriptBeginNotification beginNotification = new ScriptBeginNotification(listener, scriptId);\n\t\t\tscriptingEngine.scriptNotifications.offer(beginNotification);\n\n\t\t\twhile(!beginNotification.isProcessed()) {\n\t\t\t\tsynchronized(beginNotification) {\n\t\t\t\t\tbeginNotification.wait();\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tlistener.onScriptBegin(scriptId);\n\t\t}\n\t}\n\n\tpublic void skipScript() {\n\t\tif (taskFuture.isDone()) {\n\t\t\treturn;\n\t\t}\n\t\tif (!taskFuture.cancel(true)) {\n\n\t\t}\n\t}\n\n\tpublic boolean isFinished() {\n\t\treturn completed.get();\n\t}\n\n\tpublic void cleanup() {\n\t\texecutor.release();\n\t}\n\n\tpublic int getTaskId() {\n\t\treturn taskId;\n\t}\n\n\tpublic int getScriptId() {\n\t\treturn script.getId();\n\t}\n\n\tpublic void setTaskFuture(Future<?> taskFuture) {\n\t\tthis.taskFuture = taskFuture;\n\t}\n}", "public interface ScriptExecutor<S> {\n\n\tpublic GameScript<S> compile(String script);\n\n\tpublic ScriptExecutionResult execute(int scriptId, GameScript<S> script, ScriptBindings bindings, boolean returnResult)\n\t\t\tthrows Exception;\n\n\tpublic void executeEmbedded(int parentScriptId, int scriptId, GameScript<S> script, EmbeddedScriptInvoker embeddedScriptInvoker, ScriptBindings bindings) throws Exception;\n\n\tpublic void release();\n}", "public interface ScriptExecutorPool<S> {\n\n\tpublic int getCompiledScriptId(String filepath);\n\n\tpublic String getCompiledScriptPath(int scriptId);\n\n\tpublic int preCompileScript(String filepath, String scriptContent) throws InsufficientCompilersException;\n\n\tpublic ScriptExecutionTask<?> execute(int taskId, int scriptId, ScriptBindings scriptBindings,\n\t\t\tScriptInvocationListener invocationListener, boolean syncCall);\n\n\tpublic void release(ScriptExecutor<S> executor);\n\t\n\tpublic GameScriptingEngine getGameScriptingEngine();\n}", "public interface ScriptInvocationListener {\n\t/**\n\t * Called just before a script begins execution. Note: If callOnGameThread() is true,\n\t * the script will not begin until this callback is processed on the game thread\n\t * @param scriptId The script id\n\t */\n\tpublic default void onScriptBegin(int scriptId) {\n\n\t}\n\n\t/**\n\t * Called when a script is cancelled while in the invoke queue.\n\t *\n\t * @param scriptId The script id\n\t */\n\tpublic default void onScriptCancelled(int scriptId) {\n\t}\n\n\t/**\n\t * Called when a script successfully completes\n\t * \n\t * @param scriptId\n\t * The script id\n\t * @param executionResult\n\t * The variable bindings after execution\n\t */\n\tpublic void onScriptSuccess(int scriptId, ScriptExecutionResult executionResult);\n\n\t/**\n\t * Called when a script is skipped during execution\n\t * \n\t * @param scriptId\n\t * The script id\n\t */\n\tpublic void onScriptSkipped(int scriptId);\n\n\t/**\n\t * Called when an exception occurs during script execution\n\t * \n\t * @param scriptId\n\t * The script id\n\t * @param e\n\t * The exception that occurred\n\t */\n\tpublic void onScriptException(int scriptId, Exception e);\n\n\t/**\n\t * Returns if this {@link ScriptInvocationListener} should be notified on\n\t * the game thread\n\t * \n\t * @return False if this should be notified on the\n\t * {@link GameScriptingEngine} thread pool\n\t */\n\tpublic boolean callOnGameThread();\n}", "public class InsufficientCompilersException extends Exception {\n\tprivate static final long serialVersionUID = 2947579725300422095L;\n\n\tpublic InsufficientCompilersException() {\n\t\tsuper(\"There were insufficient compilers available to compile the provided script\");\n\t}\n}", "public class ScriptExecutorUnavailableException extends RuntimeException {\n\tprivate static final long serialVersionUID = -8409957449519524312L;\n\n\tpublic ScriptExecutorUnavailableException(int scriptId) {\n\t\tsuper(\"Unable to execute script \" + scriptId + \" due to no available \" + ScriptExecutor.class.getSimpleName());\n\t}\n}" ]
import org.mini2Dx.miniscript.core.GameScriptingEngine; import org.mini2Dx.miniscript.core.ScriptBindings; import org.mini2Dx.miniscript.core.ScriptExecutionTask; import org.mini2Dx.miniscript.core.ScriptExecutor; import org.mini2Dx.miniscript.core.ScriptExecutorPool; import org.mini2Dx.miniscript.core.ScriptInvocationListener; import org.mini2Dx.miniscript.core.exception.InsufficientCompilersException; import org.mini2Dx.miniscript.core.exception.ScriptExecutorUnavailableException; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import org.mini2Dx.miniscript.core.GameScript;
/** * The MIT License (MIT) * * Copyright (c) 2016 Thomas Cashman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.mini2Dx.miniscript.core.dummy; /** * An implementation for {@link ScriptExecutorPool} for unit tests */ public class DummyScriptExecutorPool implements ScriptExecutorPool<DummyScript> { private final Map<Integer, GameScript<DummyScript>> scripts = new ConcurrentHashMap<Integer, GameScript<DummyScript>>(); private final Map<String, Integer> filepathsToScriptIds = new ConcurrentHashMap<String, Integer>(); private final Map<Integer, String> scriptIdsToFilepaths = new ConcurrentHashMap<Integer, String>(); private final BlockingQueue<ScriptExecutor<DummyScript>> executors; private final GameScriptingEngine gameScriptingEngine; public DummyScriptExecutorPool(GameScriptingEngine gameScriptingEngine, int poolSize) { this.gameScriptingEngine = gameScriptingEngine; executors = new ArrayBlockingQueue<ScriptExecutor<DummyScript>>(poolSize); for (int i = 0; i < poolSize; i++) { executors.offer(new DummyScriptExecutor(this)); } } @Override public int preCompileScript(String filepath, String scriptContent) throws InsufficientCompilersException { ScriptExecutor<DummyScript> executor = executors.poll(); if (executor == null) { throw new InsufficientCompilersException(); } GameScript<DummyScript> script = executor.compile(scriptContent); executor.release(); scripts.put(script.getId(), script); filepathsToScriptIds.put(filepath, script.getId()); scriptIdsToFilepaths.put(script.getId(), filepath); return script.getId(); } @Override public int getCompiledScriptId(String filepath) { return filepathsToScriptIds.get(filepath); } @Override public String getCompiledScriptPath(int scriptId) { return scriptIdsToFilepaths.get(scriptId); } @Override public ScriptExecutionTask<?> execute(int taskId, int scriptId, ScriptBindings scriptBindings,
ScriptInvocationListener invocationListener, boolean syncCall) {
6
thx/RAP
src/main/java/com/taobao/rigel/rap/mock/service/impl/MockMgrImpl.java
[ "public class Patterns {\n public static final String MOCK_TEMPLATE_PATTERN = \"\\\\$\\\\{([_a-zA-Z][_a-zA-Z0-9.]*)=?((.*?))\\\\}\";\n public static final String ILLEGAL_NAME_CHAR = \"[^ 0-9a-zA-Z_]\";\n public static final String LEGAL_ACCOUNT_CHAR = \"[0-9a-zA-Z_]\";\n public static final String LEGAL_NAME_CHAR = \"[0-9a-zA-Z_ ]\";\n}", "public class SystemSettings {\r\n\r\n public static final String APP_PATH = ServletActionContext\r\n .getServletContext().getRealPath(\"/\");\r\n public static final String STATIC_ROOT = APP_PATH + \"stat\" + File.separator;\r\n\r\n public static final String projectContext = \"\";\r\n\r\n public static final int MOCK_SERVICE_TIMEOUT = 1000;\r\n\r\n public static String GET_DEFAULT_USER_SETTINGS(String key) {\r\n if (key == null || key.isEmpty()) {\r\n return null;\r\n }\r\n\r\n if (key.equals(\"inform\")) {\r\n return \"\";\r\n }\r\n\r\n return null;\r\n\r\n }\r\n\r\n ;\r\n}\r", "public class Rule {\n private int actionId;\n private String rules;\n private Date updateTime;\n\n public int getActionId() {\n return actionId;\n }\n\n public void setActionId(int actionId) {\n this.actionId = actionId;\n }\n\n public String getRules() {\n return rules;\n }\n\n public void setRules(String rules) {\n this.rules = rules;\n }\n\n public Date getUpdateTime() {\n return updateTime;\n }\n\n public void setUpdateTime(Date updateTime) {\n this.updateTime = updateTime;\n }\n}", "public interface MockDao {\n /**\n * get rule by action id\n *\n * @param actionId\n * @return\n */\n Rule getRule(int actionId);\n\n /**\n * delete rule by action id\n *\n * @param actionId\n * @return 0 success, -1 error\n */\n int removeRule(int actionId);\n\n /**\n * set rule, rule.actionId must be set\n *\n * @param rule\n * @return\n */\n int updateRule(Rule rule);\n\n /**\n * add new rule for action\n *\n * @param rule\n * @return\n */\n int addRule(Rule rule);\n}", "public class Action implements java.io.Serializable {\r\n\r\n private int id;\r\n private int disableCache;\r\n private String name;\r\n private String description;\r\n private String requestType = \"1\";\r\n private String requestUrl;\r\n private Set<Parameter> requestParameterList = new HashSet<Parameter>();\r\n private Set<Parameter> responseParameterList = new HashSet<Parameter>();\r\n private String responseTemplate;\r\n private Set<Page> pageList = new HashSet<Page>();\r\n private String remarks;\r\n\r\n public static List<Action> loadList(List<Map<String, Object>> result) {\r\n List<Action> list = new ArrayList<Action>();\r\n for (Map<String, Object> row : result) {\r\n Action obj = new Action();\r\n obj.setDescription((String) row.get(\"description\"));\r\n obj.setId((Integer) row.get(\"id\"));\r\n obj.setName((String) row.get(\"name\"));\r\n obj.setRemarks((String) row.get(\"remarks\"));\r\n obj.setRequestType((String) row.get(\"request_type\"));\r\n obj.setRequestUrl((String) row.get(\"request_url\"));\r\n list.add(obj);\r\n }\r\n return list;\r\n }\r\n\r\n public int getId() {\r\n return id;\r\n }\r\n\r\n public void setId(int id) {\r\n this.id = id;\r\n }\r\n\r\n public int getDisableCache() {\r\n return disableCache;\r\n }\r\n\r\n public void setDisableCache(int disableCache) {\r\n this.disableCache = disableCache;\r\n }\r\n\r\n public String getName() {\r\n return name;\r\n }\r\n\r\n public void setName(String name) {\r\n this.name = name;\r\n }\r\n\r\n public String getDescription() {\r\n return description;\r\n }\r\n\r\n public void setDescription(String description) {\r\n this.description = description == null ? \"\" : description;\r\n }\r\n\r\n public String getRequestType() {\r\n return requestType;\r\n }\r\n\r\n public void setRequestType(String requestType) {\r\n if (requestType == null || requestType == \"\")\r\n return;\r\n this.requestType = requestType;\r\n }\r\n\r\n public String getMethod() {\r\n if (this.requestType.equals(\"2\")) {\r\n return \"POST\";\r\n } else if (this.requestType.equals(\"3\")) {\r\n return \"PUT\";\r\n } else if (this.requestType.equals(\"4\")) {\r\n return \"DELETE\";\r\n } else {\r\n return \"GET\"; // in default\r\n }\r\n }\r\n\r\n public String getRequestUrl() {\r\n return requestUrl;\r\n }\r\n\r\n public void setRequestUrl(String requestUrl) {\r\n this.requestUrl = requestUrl == null ? \"\" : requestUrl;\r\n }\r\n\r\n public void addParameter(Parameter parameter, boolean isRequest) {\r\n if (isRequest) {\r\n getRequestParameterList().add(parameter);\r\n parameter.getActionRequestList().add(this);\r\n } else {\r\n getResponseParameterList().add(parameter);\r\n parameter.getActionResponseList().add(this);\r\n }\r\n }\r\n\r\n public Set<Parameter> getRequestParameterList() {\r\n return requestParameterList;\r\n }\r\n\r\n public void setRequestParameterList(Set<Parameter> requestParameterList) {\r\n this.requestParameterList = requestParameterList;\r\n }\r\n\r\n public Set<Parameter> getResponseParameterList() {\r\n return responseParameterList;\r\n }\r\n\r\n public void setResponseParameterList(Set<Parameter> responseParameterList) {\r\n this.responseParameterList = responseParameterList;\r\n }\r\n\r\n public List<Parameter> getRequestParameterListOrdered() {\r\n Set<Parameter> parameterList = getRequestParameterList();\r\n List<Parameter> parameterListOrdered = new ArrayList<Parameter>();\r\n parameterListOrdered.addAll(parameterList);\r\n Collections.sort(parameterListOrdered, new ParameterComparator());\r\n return parameterListOrdered;\r\n }\r\n\r\n public List<Parameter> getResponseParameterListOrdered() {\r\n Set<Parameter> parameterList = getResponseParameterList();\r\n List<Parameter> parameterListOrdered = new ArrayList<Parameter>();\r\n parameterListOrdered.addAll(parameterList);\r\n Collections.sort(parameterListOrdered, new ParameterComparator());\r\n return parameterListOrdered;\r\n }\r\n\r\n public String getResponseTemplate() {\r\n return responseTemplate;\r\n }\r\n\r\n public void setResponseTemplate(String responseTemplate) {\r\n this.responseTemplate = responseTemplate == null ? \"\"\r\n : responseTemplate;\r\n }\r\n\r\n public Set<Page> getPageList() {\r\n return pageList;\r\n }\r\n\r\n public void setPageList(Set<Page> pageList) {\r\n this.pageList = pageList;\r\n }\r\n\r\n public void update(Action action) {\r\n setDescription(action.getDescription());\r\n setName(action.getName());\r\n setRequestType(action.getRequestType());\r\n setRequestUrl(action.getRequestUrl());\r\n setResponseTemplate(action.getResponseTemplate());\r\n }\r\n\r\n public String toString() {\r\n StringBuilder stringBuilder = new StringBuilder();\r\n\r\n stringBuilder.append(\"{\\\"id\\\":\" + getId() + \",\");\r\n stringBuilder.append(\"\\\"name\\\":\\\"\" + StringUtils.escapeInJ(getName())\r\n + \"\\\",\");\r\n stringBuilder.append(\"\\\"description\\\":\\\"\"\r\n + StringUtils.escapeInJ(getDescription()) + \"\\\",\");\r\n stringBuilder.append(\"\\\"requestType\\\":\\\"\" + getRequestType() + \"\\\",\");\r\n stringBuilder.append(\"\\\"requestUrl\\\":\\\"\"\r\n + StringUtils.escapeInJ(getRequestUrl()) + \"\\\",\");\r\n stringBuilder.append(\"\\\"responseTemplate\\\":\\\"\"\r\n + StringUtils.escapeInJ(getResponseTemplate()) + \"\\\",\");\r\n stringBuilder.append(\"\\\"requestParameterList\\\":\");\r\n\r\n stringBuilder.append(\"[\");\r\n Iterator<Parameter> iterator = getRequestParameterListOrdered()\r\n .iterator();\r\n while (iterator.hasNext()) {\r\n stringBuilder.append(iterator.next());\r\n if (iterator.hasNext()) {\r\n stringBuilder.append(\",\");\r\n }\r\n }\r\n stringBuilder.append(\"],\");\r\n\r\n stringBuilder.append(\"\\\"responseParameterList\\\":\");\r\n\r\n stringBuilder.append(\"[\");\r\n iterator = getResponseParameterListOrdered().iterator();\r\n while (iterator.hasNext()) {\r\n stringBuilder.append(iterator.next());\r\n if (iterator.hasNext()) {\r\n stringBuilder.append(\",\");\r\n }\r\n }\r\n stringBuilder.append(\"]}\");\r\n return stringBuilder.toString();\r\n }\r\n\r\n public String getRemarks() {\r\n return remarks;\r\n }\r\n\r\n public void setRemarks(String remarks) {\r\n this.remarks = remarks;\r\n }\r\n\r\n /**\r\n * get request parameter list HTML for file exporting reason: velocity\r\n * doesn't support macro recursion.\r\n *\r\n * @return\r\n */\r\n public String getRequestParameterListHTML() {\r\n return getParameterListHTML(requestParameterList);\r\n }\r\n\r\n public String getResponseParameterListHTML() {\r\n return getParameterListHTML(responseParameterList);\r\n }\r\n\r\n private String getParameterListHTML(Set<Parameter> list) {\r\n StringBuilder html = new StringBuilder();\r\n html\r\n .append(\"<table class=\\\"param-table\\\">\")\r\n .append(\"<thead>\")\r\n .append(\"<th class=\\\"th-name\\\">Name</th>\")\r\n .append(\"<th class=\\\"th-identifier\\\">Identifier</th>\")\r\n .append(\"<th class=\\\"th-type\\\">Type</th>\")\r\n .append(\"<th class=\\\"th-remark\\\">Remark</th>\")\r\n .append(\"</thead>\");\r\n getParameterListHTMLSub(html, list, (short) 1);\r\n html.append(\"</table>\");\r\n return html.toString();\r\n }\r\n\r\n private void getParameterListHTMLSub(StringBuilder html, Set<Parameter> list, short level) {\r\n for (Parameter p : list) {\r\n html\r\n .append(\"<tr class=\\\"tr-level-\" + level + \"\\\">\")\r\n .append(\"<td class=\\\"td-name\\\">\" + levelMark(level) + StringUtils.escapeInH(p.getName()) + \"</td>\")\r\n .append(\"<td class=\\\"td-identifier\\\">\" + StringUtils.escapeInH(p.getIdentifier()) + \"</td>\")\r\n .append(\"<td class=\\\"td-type\\\">\" + StringUtils.escapeInH(p.getDataType()) + \"</td>\")\r\n .append(\"<td class=\\\"td-remark\\\">\" + StringUtils.escapeInH(p.getRemark()) + \"</td>\")\r\n .append(\"</tr>\");\r\n if (p.getParameterList() != null || p.getParameterList().size() > 0) {\r\n getParameterListHTMLSub(html, p.getParameterList(), (short) (level + 1));\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * level 1: level 2:--- level 3:------ ...\r\n *\r\n * @param level started from 1\r\n * @return\r\n */\r\n private String levelMark(short level) {\r\n StringBuilder sb = new StringBuilder();\r\n for (short i = 1; i < level; i++) {\r\n sb.append(\"---\");\r\n }\r\n return sb.toString();\r\n }\r\n\r\n public String getRequestUrlRel() {\r\n String url = this.requestUrl;\r\n if (url == null || url.isEmpty()) {\r\n return \"xxxxxxxxxxxxxxxxEMPTY URLxxxxxxxxxxxxxxxxx\";\r\n }\r\n if (url.contains(\"https://\")) {\r\n url = url.substring(url.indexOf(\"/\", 7));\r\n } else if (url.contains(\"http://\")) {\r\n url = url.substring(url.indexOf(\"/\", 8));\r\n }\r\n return url;\r\n }\r\n\r\n public enum TYPE {REQUEST, RESPONSE}\r\n\r\n}\r", "public class Parameter implements java.io.Serializable {\n\n private int id;\n private String mockData;\n private String name;\n private String identifier;\n private String identifierChange;\n private String remarkChange;\n private String dataType;\n private String remark;\n private Set<Action> actionRequestList = new HashSet<Action>();\n private Set<Action> actionResponseList = new HashSet<Action>();\n private String validator = \"\";\n private Set<Parameter> parameterList = new HashSet<Parameter>();\n private Set<Parameter> complexParamerterList = new HashSet<Parameter>();\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getMockData() {\n return mockData;\n }\n\n public void setMockData(String mockData) {\n this.mockData = mockData;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = (name == null ? \"\" : name);\n }\n\n public String getIdentifier() {\n if (identifierChange != null) {\n return identifierChange;\n } else {\n return identifier;\n }\n }\n\n public void setIdentifier(String identifier) {\n this.identifier = (identifier == null ? \"\" : identifier);\n }\n\n public String getIdentifierChange() {\n\n return identifierChange;\n }\n\n public void setIdentifierChange(String identifierChange) {\n this.identifierChange = identifierChange;\n }\n\n public String getRemarkChange() {\n return remarkChange;\n }\n\n public void setRemarkChange(String remarkChange) {\n this.remarkChange = remarkChange;\n }\n\n public String getMockIdentifier() {\n String rv = \"\";\n if (identifier == null || identifier.isEmpty()) {\n return \"\\\"emptyIdentifier\\\"\";\n }\n\n rv = identifier;\n if (rv != null && !rv.isEmpty()) {\n int index = rv.indexOf(\"|\");\n if (index > -1) {\n rv = rv.substring(0, index);\n }\n }\n return \"\\\"\" + rv + \"\\\"\";\n }\n\n public String getIdentifierWithoutMockjsRule() {\n String rv;\n if (identifier == null || identifier.isEmpty()) {\n return \"emptyIdentifier\";\n }\n\n rv = identifier;\n if (rv != null && !rv.isEmpty()) {\n int index = rv.indexOf(\"|\");\n if (index > -1) {\n rv = rv.substring(0, index);\n }\n }\n return rv;\n }\n\n public String getMockJSIdentifier() {\n String rv = \"\";\n if (identifier == null || identifier.isEmpty()) {\n return \"\\\"emptyIdentifier\\\"\";\n }\n rv = identifier;\n return \"\\\"\" + rv + \"\\\"\";\n }\n\n public String getDataType() {\n if (this.dataType == null || this.dataType.trim().isEmpty()) {\n return \"\";\n }\n return dataType;\n }\n\n public void setDataType(String dataType) {\n this.dataType = (dataType == null ? \"\" : dataType);\n }\n\n public String getRemark() {\n if (remarkChange != null) {\n return remarkChange;\n }\n return (remark == null ? \"\" : remark);\n }\n\n public void setRemark(String remark) {\n this.remark = remark;\n }\n\n public Set<Action> getActionRequestList() {\n return actionRequestList;\n }\n\n public void setActionRequestList(Set<Action> actionRequestList) {\n this.actionRequestList = actionRequestList;\n }\n\n public Set<Action> getActionResponseList() {\n return actionResponseList;\n }\n\n public void setActionResponseList(Set<Action> actionResponseList) {\n this.actionResponseList = actionResponseList;\n }\n\n public String getValidator() {\n return validator;\n }\n\n public void setValidator(String validator) {\n this.validator = validator;\n }\n\n public Set<Parameter> getParameterList() {\n return parameterList;\n }\n\n public void setParameterList(Set<Parameter> parameterList) {\n this.parameterList = parameterList;\n }\n\n public void update(Parameter parameter) {\n setDataType(parameter.getDataType());\n setIdentifier(parameter.getIdentifier());\n setName(parameter.getName());\n setRemark(parameter.getRemark());\n setValidator(parameter.getValidator());\n }\n\n public List<Parameter> getParameterListOrdered() {\n Set<Parameter> parameterList = getParameterList();\n List<Parameter> parameterListOrdered = new ArrayList<Parameter>();\n parameterListOrdered.addAll(parameterList);\n Collections.sort(parameterListOrdered, new ParameterComparator());\n return parameterListOrdered;\n }\n\n public Set<Parameter> getComplexParameterList() {\n return complexParamerterList;\n }\n\n public void setComplexParameterList(Set<Parameter> complexParameterList) {\n this.complexParamerterList = complexParameterList;\n }\n\n public void addChild(Parameter parameter) {\n getParameterList().add(parameter);\n parameter.getComplexParameterList().add(this);\n }\n\n public String toString() {\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"{\\\"id\\\":\" + getId() + \",\");\n stringBuilder.append(\"\\\"identifier\\\":\\\"\"\n + StringUtils.escapeInJ(getIdentifier()) + \"\\\",\");\n stringBuilder.append(\"\\\"name\\\":\\\"\" + StringUtils.escapeInJ(getName())\n + \"\\\",\");\n stringBuilder.append(\"\\\"remark\\\":\\\"\"\n + StringUtils.escapeInJ(getRemark()) + \"\\\",\");\n stringBuilder.append(\"\\\"parameterList\\\":\");\n stringBuilder.append(\"[\");\n Iterator<Parameter> iterator = getParameterListOrdered().iterator();\n while (iterator.hasNext()) {\n stringBuilder.append(iterator.next());\n if (iterator.hasNext()) {\n stringBuilder.append(\",\");\n }\n }\n stringBuilder.append(\"],\");\n stringBuilder.append(\"\\\"validator\\\":\\\"\"\n + StringUtils.escapeInJ(getValidator()) + \"\\\",\");\n stringBuilder.append(\"\\\"dataType\\\":\\\"\"\n + StringUtils.escapeInJ(getDataType()) + \"\\\"}\");\n return stringBuilder.toString();\n }\n\n public String getRemarkWithoutMockjsRule() {\n if (remark != null && remark.contains(\"@mock=\")) {\n return remark.substring(0, remark.indexOf(\"@mock=\"));\n } else {\n return remark;\n }\n }\n\n public String getMockJsRules() {\n if (remark == null || remark.isEmpty() || (!remark.contains(\"@mock=\"))) {\n return null;\n }\n return remark.substring(remark.indexOf(\"@mock=\") + 6);\n\n }\n\n\n public String getJSONSchemaDataType() {\n if (dataType != null && dataType.contains(\"array\")) {\n return \"array\";\n }\n return this.dataType;\n }\n\n public boolean hasMockJSData() {\n return this.getMockJsRules() != null;\n }\n\n\n}", "public interface ProjectDao {\n\n /**\n * get project list\n *\n * @param user\n * @param curPageNum\n * @param pageSize\n * @return\n */\n List<Project> getProjectList(User user, int curPageNum, int pageSize);\n\n /**\n * get new project\n *\n * @param project\n * @return always 0\n */\n int addProject(Project project);\n\n /**\n * update project\n *\n * @param id\n * @param projectData\n * @param deletedObjectListData\n * @return\n */\n String updateProject(int id, String projectData,\n String deletedObjectListData, Map<Integer, Integer> actionIdMap);\n\n /**\n * update project\n *\n * @param project\n * @return\n */\n int updateProject(Project project);\n\n /**\n * remove project\n *\n * @param id\n * @return\n */\n int removeProject(int id);\n\n /**\n * get project\n *\n * @param id\n * @return\n */\n Project getProjectSummary(int id);\n\n /**\n * get module\n *\n * @param id\n * @return\n */\n Module getModule(int id);\n\n /**\n * get page\n *\n * @param id\n * @return\n */\n Object getPage(int id);\n\n\n /**\n * get action\n *\n * @param id\n * @return\n */\n Action getAction(int id);\n\n /**\n * save project\n *\n * @param project\n * @return\n */\n int saveProject(Project project);\n\n /**\n * get project list number\n *\n * @param user\n * @return\n */\n int getProjectListNum(User user);\n\n /**\n * get matched action list based on URL pattern\n *\n * @param projectId\n * @param pattern\n * @return\n */\n List<Action> getMatchedActionList(int projectId, String pattern);\n\n /**\n * clear all mock data of objects in specified project\n *\n * @param projectId project id\n * @return affected rows num\n */\n public int resetMockData(int projectId);\n\n /**\n * get project list by group\n *\n * @param id\n * @return\n */\n List<Project> getProjectListByGroup(int id);\n\n /**\n * search all projects (for admin use)\n *\n * @param key\n * @return\n */\n List<Project> search(String key);\n\n List<Project> getProjectList();\n\n int getProjectListNum();\n\n int getModuleNum();\n\n int getPageNum();\n\n int getActionNum();\n\n int getParametertNum();\n\n int getCheckInNum();\n\n int getMockNumInTotal();\n\n List<Project> selectMockNumTopNProjectList(int limit);\n\n /**\n * get project id by action id\n *\n * @param actionId\n * @return\n */\n Integer getProjectIdByActionId(int actionId);\n\n void updateProjectNum(Project project);\n\n\n /**\n * transfer a project to another user\n * @param projectId\n * @param creatorId\n */\n void updateCreatorId(int projectId, int creatorId);\n\n Project getProject(int id);\n\n /**\n * get member id list of specified project\n *\n * @param projectId\n * @return\n */\n List<Integer> getMemberIdsOfProject(int projectId);\n}", "public interface ProjectMgr {\r\n\r\n /**\r\n * get project list\r\n *\r\n * @param user\r\n * @param curPageNum\r\n * @param pageSize\r\n * @return\r\n */\r\n List<Project> getProjectList(User user, int curPageNum, int pageSize);\r\n\r\n /**\r\n * add new project\r\n *\r\n * @param project\r\n * @return\r\n */\r\n int addProject(Project project);\r\n\r\n /**\r\n * remove project\r\n *\r\n * @param id\r\n * @return\r\n */\r\n int removeProject(int id);\r\n\r\n /**\r\n * update project\r\n *\r\n * @param project\r\n * @return\r\n */\r\n int updateProject(Project project);\r\n\r\n /**\r\n * get project by id\r\n *\r\n * @param id\r\n * @return\r\n */\r\n Project getProjectSummary(int id);\r\n\r\n Project getProject(int id, String ver);\r\n\r\n /**\r\n * with project data\r\n *\r\n * @param id\r\n * @return\r\n */\r\n Project getProject(int id);\r\n\r\n /**\r\n * get module by id\r\n *\r\n * @param id\r\n * @return\r\n */\r\n Module getModule(int id);\r\n\r\n /**\r\n * get page by id\r\n *\r\n * @param id\r\n * @return\r\n */\r\n Page getPage(int id);\r\n\r\n /**\r\n * update project\r\n *\r\n * @param id\r\n * @param projectData\r\n * @param deletedObjectListData\r\n * @return\r\n */\r\n String updateProject(int id, String projectData,\r\n String deletedObjectListData, Map<Integer, Integer> actionIdMap);\r\n\r\n /**\r\n * get number of project list usually used for pager\r\n *\r\n * @param user\r\n * @return\r\n */\r\n int getProjectListNum(User user);\r\n\r\n /**\r\n * set action.remarks as paramIdList eg-> action.remarks = \"id,name,age\";\r\n * used for parameter identifier spelling validation [*caution*] only\r\n * calculating response parameters\r\n *\r\n * @param action action to be filled with paramIdList info\r\n */\r\n void loadParamIdListForAction(Action action);\r\n\r\n /**\r\n * load paramIdList for page\r\n *\r\n * @param page\r\n */\r\n void loadParamIdListForPage(Page page);\r\n\r\n /**\r\n * get matched action list based on URL pattern\r\n *\r\n * @param projectId\r\n * @param pattern\r\n * @return\r\n */\r\n List<Action> getMatchedActionList(int projectId, String pattern);\r\n\r\n /**\r\n * get project list by group id\r\n *\r\n * @param id\r\n * @return\r\n */\r\n List<Project> getProjectListByGroup(int id);\r\n\r\n /**\r\n * search all projects (for admin)\r\n *\r\n * @param key\r\n * @return\r\n */\r\n List<Project> search(String key);\r\n\r\n /**\r\n * search project by user\r\n *\r\n * @param key\r\n * @param curUserId\r\n * @return\r\n */\r\n List<Project> search(String key, int curUserId);\r\n\r\n /**\r\n * get action\r\n *\r\n * @param id\r\n * @return\r\n */\r\n Action getAction(int id);\r\n\r\n Action getAction(int id, String ver, int projectId);\r\n\r\n /**\r\n * update doc\r\n *\r\n * @param projectId\r\n */\r\n void updateDoc(int projectId);\r\n\r\n List<Project> getProjectList();\r\n\r\n int getProjectNum();\r\n\r\n int getModuleNum();\r\n\r\n int getPageNum();\r\n\r\n int getActionNum();\r\n\r\n int getParametertNum();\r\n\r\n int getCheckInNum();\r\n\r\n int getMockNumInTotal();\r\n\r\n List<Project> selectMockNumTopNProjectList(int limit);\r\n\r\n /**\r\n * update Action.disableCache\r\n *\r\n * @param projectId\r\n */\r\n void updateCache(int projectId);\r\n\r\n /**\r\n * get project id by action id\r\n *\r\n * @param actionId\r\n * @return\r\n */\r\n Integer getProjectIdByActionId(int actionId);\r\n\r\n void updateProjectNum(Project project);\r\n\r\n /**\r\n * clear project model cache(without project data) by projectId\r\n * influence projects list\r\n *\r\n * @param projectId\r\n */\r\n void clearProjectInfoCache(int projectId);\r\n\r\n /**\r\n * clear project data cache\r\n * influence workspace\r\n *\r\n * @param projectId\r\n */\r\n void clearProjectDocCache(int projectId);\r\n\r\n /**\r\n * get member user id list of specifid project\r\n *\r\n * @param projectId\r\n * @return\r\n */\r\n List<Integer> getMemberIdsOfProject(int projectId);\r\n\r\n}\r" ]
import com.google.gson.Gson; import com.taobao.rigel.rap.common.config.Patterns; import com.taobao.rigel.rap.common.config.SystemSettings; import com.taobao.rigel.rap.common.utils.*; import com.taobao.rigel.rap.mock.bo.Rule; import com.taobao.rigel.rap.mock.dao.MockDao; import com.taobao.rigel.rap.mock.service.MockMgr; import com.taobao.rigel.rap.project.bo.Action; import com.taobao.rigel.rap.project.bo.Parameter; import com.taobao.rigel.rap.project.dao.ProjectDao; import com.taobao.rigel.rap.project.service.ProjectMgr; import nl.flotsam.xeger.Xeger; import org.apache.logging.log4j.LogManager; import sun.misc.Cache; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.*; import java.util.concurrent.*; import java.util.regex.Matcher; import java.util.regex.Pattern;
package com.taobao.rigel.rap.mock.service.impl; public class MockMgrImpl implements MockMgr { interface Callback { void onSuccess(String result); } private static final org.apache.logging.log4j.Logger logger = LogManager.getLogger(MockMgrImpl.class); private final String ERROR_PATTERN = "{\"isOk\":false,\"msg\":\"路径为空,请查看是否接口未填写URL.\"}"; private final String ERROR_SEARCH = "{\"isOk\":false,\"msg\":\"请求参数不合法。\"}"; // 请查看是否含有 script、img、iframe 等标签 private ProjectDao projectDao; private ProjectMgr projectMgr; private MockDao mockDao; private int uid = 10000; private Map<String, List<String>> requestParams; private boolean isMockJsData = false; /** * random seed */ private int _num = 1; private String[] NAME_LIB = {"霍雍", "行列", "幻刺", "金台", "望天", "李牧", "三冰", "自勉", "思霏", "诚冉", "甘苦", "勇智", "墨汁老湿", "圣香", "定球", "征宇", "灵兮", "永盛", "小婉", "紫丞", "少侠", "木谦", "周亮", "宝山", "张中", "晓哲", "夜沨"}; private String[] LOCATION_LIB = {"北京 朝阳区", "北京 海淀区", "北京 昌平区", "吉林 长春 绿园区", "吉林 吉林 丰满区"}; private String[] PHONE_LIB = {"15813243928", "13884928343", "18611683243", "18623432532", "18611582432"}; public static Map<String, List<String>> getUrlParameters(String url) throws UnsupportedEncodingException { Map<String, List<String>> params = new HashMap<String, List<String>>(); String[] urlParts = url.split("\\?"); if (urlParts.length > 1) { String query = urlParts[1]; for (String param : query.split("&")) { String pair[] = param.split("="); if (pair.length == 0) { continue; } String key = URLDecoder.decode(pair[0], "UTF-8"); String value = ""; if (pair.length > 1) { value = URLDecoder.decode(pair[1], "UTF-8"); } List<String> values = params.get(key); if (values == null) { values = new ArrayList<String>(); params.put(key, values); } values.add(value); } } return params; } public MockDao getMockDao() { return mockDao; } public void setMockDao(MockDao mockDao) { this.mockDao = mockDao; } public ProjectMgr getProjectMgr() { return projectMgr; } public void setProjectMgr(ProjectMgr projectMgr) { this.projectMgr = projectMgr; } private boolean isPatternLegal(String pattern) { if (pattern == null || pattern.isEmpty()) { return false; } String path = pattern; if (path.indexOf("/") == 0) { path = path.substring(1); } if (path.contains("?")) { path = path.substring(0, path.indexOf("?")); } if (path.isEmpty()) { return false; } return true; } private boolean isSearchLegal(String pattern) throws UnsupportedEncodingException { if (pattern == null || pattern.isEmpty()) { return true; } String search = pattern; if (search.contains("?")) { search = search.substring(search.indexOf("?")); search = URLDecoder.decode(search, "UTF-8"); if(search.toLowerCase().indexOf("<img") != -1) return false; if(search.toLowerCase().indexOf("<script") != -1) return false; if(search.toLowerCase().indexOf("</script>") != -1) return false; if(search.toLowerCase().indexOf("<iframe") != -1) return false; if(search.toLowerCase().indexOf("</iframe>") != -1) return false; } return true; } public ProjectDao getProjectDao() { return projectDao; } public void setProjectDao(ProjectDao projectDao) { this.projectDao = projectDao; } public String generateData(int projectId, String pattern, Map<String, Object> options) throws UnsupportedEncodingException { if (!isPatternLegal(pattern)) { return ERROR_PATTERN; } _num = 1; String originalPattern = pattern; if (pattern.contains("?")) { pattern = pattern.substring(0, pattern.indexOf("?")); }
List<Action> aList = projectMgr
4
ground-context/ground
modules/common/test/edu/berkeley/ground/common/model/usage/LineageGraphTest.java
[ "public static String convertFromClassToString(Object object) {\n return Json.stringify(Json.toJson(object));\n}", "public static Object convertFromStringToClass(String body, Class<?> klass) {\n return Json.fromJson(Json.parse(body), klass);\n}", "public static String readFromFile(String filename) throws GroundException {\n try {\n String content = new Scanner(new File(filename)).useDelimiter(\"\\\\Z\").next();\n\n return content;\n } catch (FileNotFoundException e) {\n throw new GroundException(ExceptionType.OTHER, String.format(\"File %s not found\", filename));\n }\n}", "public enum GroundType {\n STRING(String.class, \"string\", Types.VARCHAR) {\n @Override\n public Object parse(String str) {\n return str;\n }\n },\n INTEGER(Integer.class, \"integer\", Types.INTEGER) {\n @Override\n public Object parse(String str) {\n return Integer.parseInt(str);\n }\n },\n BOOLEAN(Boolean.class, \"boolean\", Types.BOOLEAN) {\n @Override\n public Object parse(String str) {\n return Boolean.parseBoolean(str);\n }\n },\n LONG(Long.class, \"long\", Types.BIGINT) {\n @Override\n public Object parse(String str) {\n return Long.parseLong(str);\n }\n };\n\n private final Class<?> klass;\n private final String name;\n private final int sqlType;\n\n GroundType(Class<?> klass, String name, int sqlType) {\n this.klass = klass;\n this.name = name;\n this.sqlType = sqlType;\n }\n\n /**\n * Returns the SQL type as defined in java.sql.Types corresponding to this GroundType\n *\n * @return an integer the corresponding SQL Type\n */\n public int getSqlType() {\n return sqlType;\n }\n\n public abstract Object parse(String str);\n\n public Class<?> getTypeClass() {\n return this.klass;\n }\n\n /**\n * Return a type based on the string name.\n *\n * @param str the name of the type\n * @return the corresponding GroundType\n * @throws GroundException no such type\n */\n @JsonCreator\n public static GroundType fromString(String str) throws GroundException {\n if (str == null) {\n return null;\n }\n try {\n return GroundType.valueOf(str.toUpperCase());\n } catch (IllegalArgumentException iae) {\n throw new GroundException(ExceptionType.OTHER, String.format(\"Invalid type: %s.\", str));\n }\n }\n\n @Override\n public String toString() {\n return this.name;\n }\n}", "public class Tag {\n\n @JsonProperty(\"id\")\n private long id;\n\n @JsonProperty(\"key\")\n private final String key;\n\n @JsonProperty(\"value\")\n private final Object value;\n\n @JsonProperty(\"type\")\n private final GroundType valueType;\n\n /**\n * Create a new tag.\n *\n * @param id the id of the version containing this tag\n * @param key the key of the tag\n * @param value the value of the tag\n * @param valueType the type of the value\n */\n @JsonCreator\n public Tag(@JsonProperty(\"item_id\") long id, @JsonProperty(\"key\") String key, @JsonProperty(\"value\") Object value,\n @JsonProperty(\"type\") GroundType valueType)\n throws edu.berkeley.ground.common.exception.GroundException {\n\n if (!((value != null) == (valueType != null))\n || (value != null && !(value.getClass().equals(valueType.getTypeClass())))) {\n\n throw new GroundException(ExceptionType.OTHER, \"Mismatch between value (\" + value + \") and given type (\" + valueType.toString() + \").\");\n }\n\n if (value != null) {\n assert (value.getClass().equals(valueType.getTypeClass()));\n }\n\n this.id = id;\n this.key = key;\n this.value = value;\n this.valueType = valueType;\n }\n\n public long getId() {\n return this.id;\n }\n\n public String getKey() {\n return this.key;\n }\n\n public Object getValue() {\n return this.value;\n }\n\n public GroundType getValueType() {\n return this.valueType;\n }\n\n @Override\n public boolean equals(Object other) {\n if (!(other instanceof Tag)) {\n return false;\n }\n\n Tag otherTag = (Tag) other;\n\n return this.key.equals(otherTag.key)\n && Objects.equals(this.value, otherTag.value)\n && Objects.equals(this.valueType, otherTag.valueType);\n }\n}" ]
import static edu.berkeley.ground.common.util.ModelTestUtils.convertFromClassToString; import static edu.berkeley.ground.common.util.ModelTestUtils.convertFromStringToClass; import static edu.berkeley.ground.common.util.ModelTestUtils.readFromFile; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import edu.berkeley.ground.common.model.version.GroundType; import edu.berkeley.ground.common.model.version.Tag; import java.util.HashMap; import java.util.Map; import org.junit.Test;
/** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.berkeley.ground.common.model.usage; public class LineageGraphTest { @Test public void serializesToJSON() throws Exception { Map<String, Tag> tagsMap = new HashMap<>(); tagsMap.put("testtag", new Tag(1, "testtag", "tag", GroundType.STRING)); LineageGraph lineageGraph = new LineageGraph(1, "test", "testKey", tagsMap);
final String expected = convertFromClassToString(convertFromStringToClass(readFromFile
2
romelo333/notenoughwands1.8.8
src/main/java/romelo333/notenoughwands/Items/GenericWand.java
[ "public class ConfigSetup {\n public static String CATEGORY_GENERAL = \"general\";\n public static String CATEGORY_WANDS = \"wandsettings\";\n public static String CATEGORY_MOVINGBLACKLIST = \"movingblacklist\";\n public static String CATEGORY_CAPTUREBLACKLIST = \"captureblacklist\";\n\n public static boolean interactionProtection = false;\n public static int clientSideProtection = -1;\n public static boolean showDurabilityBarForRF = true;\n\n public static String wandSettingPreset = \"default\";\n public static WandUsage wandUsage = WandUsage.DEFAULT;\n\n private static Configuration mainConfig;\n\n public static void init() {\n mainConfig = new Configuration(new File(NotEnoughWands.setup.getModConfigDir(), \"notenoughwands.cfg\"));\n Configuration cfg = mainConfig;\n try {\n cfg.load();\n\n cfg.addCustomCategoryComment(ConfigSetup.CATEGORY_GENERAL, \"General configuration\");\n cfg.addCustomCategoryComment(ConfigSetup.CATEGORY_WANDS, \"Wand configuration\");\n\n wandSettingPreset = cfg.getString(\"wandSettingPreset\", CATEGORY_GENERAL, wandSettingPreset, \"A global setting to control all wands at once for RF/XP/Durability usage. \" +\n \"If set to 'default' then every wand can configure this on its own (i.e. normal mode). You can also use 'easy_rf', 'normal_rf', or 'hard_rf' to set the wands \" +\n \"to use RF in various difficulty modes\");\n if (\"easy_rf\".equals(wandSettingPreset) || \"easyrf\".equals(wandSettingPreset) || \"easy\".equals(wandSettingPreset)) {\n wandUsage = WandUsage.EASY_RF;\n } else if (\"normal_rf\".equals(wandSettingPreset) || \"normalrf\".equals(wandSettingPreset) || \"normal\".equals(wandSettingPreset) || \"rf\".equals(wandSettingPreset)) {\n wandUsage = WandUsage.NORMAL_RF;\n } else if (\"hard_rf\".equals(wandSettingPreset) || \"hardrf\".equals(wandSettingPreset) || \"hard\".equals(wandSettingPreset)) {\n wandUsage = WandUsage.HARD_RF;\n } else {\n wandUsage = WandUsage.DEFAULT;\n }\n\n BlackListSettings.setupCapturingWandBlacklist(cfg);\n BlackListSettings.setupMovingWandBlacklist(cfg);\n\n interactionProtection = cfg.get(ConfigSetup.CATEGORY_GENERAL, \"interactionProtection\", interactionProtection, \"If this is true then the protection wand will prevent ALL kind of interaction with protected blocks. If this is false then only block breaking is prevented\").getBoolean();\n clientSideProtection = cfg.get(ConfigSetup.CATEGORY_GENERAL, \"clientSideProtection\", clientSideProtection, \"If this is >= 1 then the protection data will be synced to the client with this frequency (in ticks). This makes protection cleaner at the cost of network traffic\").getInt();\n showDurabilityBarForRF = cfg.get(ConfigSetup.CATEGORY_GENERAL, \"showDurabilityBarForRF\", showDurabilityBarForRF, \"Set this to false if you don't want the durability bar for wands using RF\").getBoolean();\n } catch (Exception e1) {\n NotEnoughWands.setup.getLogger().log(Level.ERROR, \"Problem loading config file!\", e1);\n }\n }\n\n public static Configuration getMainConfig() {\n return mainConfig;\n }\n\n public static void postInit() {\n if (mainConfig.hasChanged()) {\n mainConfig.save();\n }\n }\n}", "@SideOnly(Side.CLIENT)\npublic class KeyBindings {\n\n public static KeyBinding wandModifier;\n public static KeyBinding wandSubMode;\n\n public static void init() {\n wandModifier = new KeyBinding(\"key.modifier\", KeyConflictContext.IN_GAME, Keyboard.KEY_EQUALS, \"key.categories.notenoughwands\");\n wandSubMode = new KeyBinding(\"key.submode\", KeyConflictContext.IN_GAME, Keyboard.KEY_NONE, \"key.categories.notenoughwands\");\n ClientRegistry.registerKeyBinding(wandModifier);\n ClientRegistry.registerKeyBinding(wandSubMode);\n }\n}", "@Mod(modid = NotEnoughWands.MODID, name=\"Not Enough Wands\",\n dependencies =\n \"required-after:mcjtylib_ng@[\" + NotEnoughWands.MIN_MCJTYLIB_VER + \",);\" +\n \"after:forge@[\" + NotEnoughWands.MIN_FORGE11_VER + \",);\" +\n \"after:redstoneflux@[\" + NotEnoughWands.MIN_COFH_VER + \",)\",\n acceptedMinecraftVersions = \"[1.12,1.13)\",\n version = NotEnoughWands.VERSION)\npublic class NotEnoughWands implements ModBase {\n public static final String MODID = \"notenoughwands\";\n public static final String VERSION = \"1.8.1\";\n public static final String MIN_FORGE11_VER = \"13.19.0.2176\";\n public static final String MIN_COFH_VER = \"2.0.0\";\n public static final String MIN_MCJTYLIB_VER = \"3.5.0\";\n\n @SidedProxy(clientSide=\"romelo333.notenoughwands.setup.ClientProxy\", serverSide=\"romelo333.notenoughwands.setup.ServerProxy\")\n public static IProxy proxy;\n public static ModSetup setup = new ModSetup();\n\n @Mod.Instance(\"NotEnoughWands\")\n public static NotEnoughWands instance;\n\n /**\n * Run before anything else. Read your config, create blocks, items, etc, and\n * register them with the GameRegistry.\n */\n @Mod.EventHandler\n public void preInit(FMLPreInitializationEvent e) {\n setup.preInit(e);\n proxy.preInit(e);\n }\n\n /**\n * Do your mod setup. Build whatever data structures you care about. Register recipes.\n */\n @Mod.EventHandler\n public void init(FMLInitializationEvent e) {\n setup.init(e);\n proxy.init(e);\n }\n\n /**\n * Handle interaction with other mods, complete your setup based on this.\n */\n @Mod.EventHandler\n public void postInit(FMLPostInitializationEvent e) {\n setup.postInit(e);\n proxy.postInit(e);\n }\n\n @Override\n public String getModId() {\n return NotEnoughWands.MODID;\n }\n\n @Override\n public void openManual(EntityPlayer player, int bookindex, String page) {\n // @todo\n }\n}", "public class ProtectedBlocks extends AbstractWorldData<ProtectedBlocks> {\n\n private static final String NAME = \"NEWProtectedBlocks\";\n\n // Persisted data\n private Map<GlobalCoordinate, Integer> blocks = new HashMap<>(); // Map from coordinate -> ID\n\n // Cache which caches the protected blocks per dimension and per chunk position.\n private Map<Pair<Integer,ChunkPos>,Set<BlockPos>> perDimPerChunkCache = new HashMap<>();\n\n private Map<Integer,Integer> counter = new HashMap<>(); // Keep track of number of protected blocks per ID\n private int lastId = 1;\n\n // Client side protected blocks.\n public static int clientSideWorld = Integer.MAX_VALUE;\n public static Map<ChunkPos, Set<BlockPos>> clientSideProtectedBlocks = new HashMap<>();\n\n public ProtectedBlocks(String name) {\n super(name);\n }\n\n @Override\n public void clear() {\n blocks.clear();\n perDimPerChunkCache.clear();\n counter.clear();\n lastId = -1;\n }\n\n public static ProtectedBlocks getProtectedBlocks(World world){\n return getData(world, ProtectedBlocks.class, NAME);\n }\n\n public static boolean isProtectedClientSide(World world, BlockPos pos){\n ChunkPos chunkPos = new ChunkPos(pos);\n if (!clientSideProtectedBlocks.containsKey(chunkPos)) {\n return false;\n }\n Set<BlockPos> positions = clientSideProtectedBlocks.get(chunkPos);\n return positions.contains(pos);\n }\n\n public int getNewId() {\n lastId++;\n save();\n return lastId-1;\n }\n\n private void decrementProtection(Integer oldId) {\n int cnt = counter.containsKey(oldId) ? counter.get(oldId) : 0;\n cnt--;\n counter.put(oldId, cnt);\n }\n\n private void incrementProtection(Integer newId) {\n int cnt = counter.containsKey(newId) ? counter.get(newId) : 0;\n cnt++;\n counter.put(newId, cnt);\n }\n\n public int getProtectedBlockCount(int id) {\n return counter.containsKey(id) ? counter.get(id) : 0;\n }\n\n private int getMaxProtectedBlocks(int id) {\n if (id == -1) {\n return ModItems.masterProtectionWand.maximumProtectedBlocks;\n } else {\n return ModItems.protectionWand.maximumProtectedBlocks;\n }\n }\n\n public boolean protect(EntityPlayer player, World world, BlockPos pos, int id) {\n GlobalCoordinate key = new GlobalCoordinate(pos, world.provider.getDimension());\n if (id != -1 && blocks.containsKey(key)) {\n Tools.error(player, \"This block is already protected!\");\n return false;\n }\n if (blocks.containsKey(key)) {\n // Block is protected but we are using the master wand so we first clear the protection.\n decrementProtection(blocks.get(key));\n }\n\n int max = getMaxProtectedBlocks(id);\n if (max != 0 && getProtectedBlockCount(id) >= max) {\n Tools.error(player, \"Maximum number of protected blocks reached!\");\n return false;\n }\n\n blocks.put(key, id);\n clearCache(key);\n\n incrementProtection(id);\n\n save();\n return true;\n }\n\n public boolean unprotect(EntityPlayer player, World world, BlockPos pos, int id) {\n GlobalCoordinate key = new GlobalCoordinate(pos, world.provider.getDimension());\n if (!blocks.containsKey(key)) {\n Tools.error(player, \"This block is not protected!\");\n return false;\n }\n if (id != -1 && blocks.get(key) != id) {\n Tools.error(player, \"You have no permission to unprotect this block!\");\n return false;\n }\n decrementProtection(blocks.get(key));\n blocks.remove(key);\n clearCache(key);\n save();\n return true;\n }\n\n public int clearProtections(World world, int id) {\n Set<GlobalCoordinate> toRemove = new HashSet<GlobalCoordinate>();\n for (Map.Entry<GlobalCoordinate, Integer> entry : blocks.entrySet()) {\n if (entry.getValue() == id) {\n toRemove.add(entry.getKey());\n }\n }\n\n int cnt = 0;\n for (GlobalCoordinate coordinate : toRemove) {\n cnt++;\n blocks.remove(coordinate);\n clearCache(coordinate);\n }\n counter.put(id, 0);\n\n save();\n return cnt;\n }\n\n public boolean isProtected(World world, BlockPos pos){\n return blocks.containsKey(new GlobalCoordinate(pos, world.provider.getDimension()));\n }\n\n public boolean hasProtections() {\n return !blocks.isEmpty();\n }\n\n public void fetchProtectedBlocks(Set<BlockPos> coordinates, World world, int x, int y, int z, float radius, int id) {\n radius *= radius;\n for (Map.Entry<GlobalCoordinate, Integer> entry : blocks.entrySet()) {\n if (entry.getValue() == id || (id == -2 && entry.getValue() != -1)) {\n GlobalCoordinate block = entry.getKey();\n if (block.getDimension() == world.provider.getDimension()) {\n BlockPos c = block.getCoordinate();\n float sqdist = (x - c.getX()) * (x - c.getX()) + (y - c.getY()) * (y - c.getY()) + (z - c.getZ()) * (z - c.getZ());\n if (sqdist < radius) {\n coordinates.add(c);\n }\n }\n }\n }\n }\n\n private void clearCache(GlobalCoordinate pos) {\n ChunkPos chunkpos = new ChunkPos(pos.getCoordinate());\n perDimPerChunkCache.remove(Pair.of(pos.getDimension(), chunkpos));\n }\n\n public Map<ChunkPos,Set<BlockPos>> fetchProtectedBlocks(World world, BlockPos pos) {\n Map<ChunkPos,Set<BlockPos>> result = new HashMap<>();\n ChunkPos chunkpos = new ChunkPos(pos);\n\n fetchProtectedBlocks(result, world, new ChunkPos(chunkpos.x-1, chunkpos.z-1));\n fetchProtectedBlocks(result, world, new ChunkPos(chunkpos.x , chunkpos.z-1));\n fetchProtectedBlocks(result, world, new ChunkPos(chunkpos.x+1, chunkpos.z-1));\n fetchProtectedBlocks(result, world, new ChunkPos(chunkpos.x-1, chunkpos.z ));\n fetchProtectedBlocks(result, world, new ChunkPos(chunkpos.x , chunkpos.z ));\n fetchProtectedBlocks(result, world, new ChunkPos(chunkpos.x+1, chunkpos.z ));\n fetchProtectedBlocks(result, world, new ChunkPos(chunkpos.x-1, chunkpos.z+1));\n fetchProtectedBlocks(result, world, new ChunkPos(chunkpos.x , chunkpos.z+1));\n fetchProtectedBlocks(result, world, new ChunkPos(chunkpos.x+1, chunkpos.z+1));\n\n return result;\n }\n\n public void fetchProtectedBlocks(Map<ChunkPos,Set<BlockPos>> allresults, World world, ChunkPos chunkpos) {\n Pair<Integer, ChunkPos> key = Pair.of(world.provider.getDimension(), chunkpos);\n if (perDimPerChunkCache.containsKey(key)) {\n allresults.put(chunkpos, perDimPerChunkCache.get(key));\n return;\n }\n\n Set<BlockPos> result = new HashSet<>();\n\n for (Map.Entry<GlobalCoordinate, Integer> entry : blocks.entrySet()) {\n GlobalCoordinate block = entry.getKey();\n if (block.getDimension() == world.provider.getDimension()) {\n ChunkPos bc = new ChunkPos(block.getCoordinate());\n if (bc.equals(chunkpos)) {\n result.add(block.getCoordinate());\n }\n }\n }\n allresults.put(chunkpos, result);\n perDimPerChunkCache.put(key, result);\n }\n\n @Override\n public void readFromNBT(NBTTagCompound tagCompound) {\n lastId = tagCompound.getInteger(\"lastId\");\n blocks.clear();\n perDimPerChunkCache.clear();;\n counter.clear();\n NBTTagList list = tagCompound.getTagList(\"blocks\", Constants.NBT.TAG_COMPOUND);\n for (int i = 0; i<list.tagCount();i++){\n NBTTagCompound tc = list.getCompoundTagAt(i);\n GlobalCoordinate block = new GlobalCoordinate(new BlockPos(tc.getInteger(\"x\"),tc.getInteger(\"y\"),tc.getInteger(\"z\")),tc.getInteger(\"dim\"));\n int id = tc.getInteger(\"id\");\n blocks.put(block, id);\n incrementProtection(id);\n }\n }\n\n @Override\n public NBTTagCompound writeToNBT(NBTTagCompound tagCompound) {\n tagCompound.setInteger(\"lastId\", lastId);\n NBTTagList list = new NBTTagList();\n for (Map.Entry<GlobalCoordinate, Integer> entry : blocks.entrySet()) {\n GlobalCoordinate block = entry.getKey();\n NBTTagCompound tc = new NBTTagCompound();\n tc.setInteger(\"x\", block.getCoordinate().getX());\n tc.setInteger(\"y\", block.getCoordinate().getY());\n tc.setInteger(\"z\", block.getCoordinate().getZ());\n tc.setInteger(\"dim\", block.getDimension());\n tc.setInteger(\"id\", entry.getValue());\n list.appendTag(tc);\n }\n tagCompound.setTag(\"blocks\",list);\n return tagCompound;\n }\n}", "public class ItemCapabilityProvider implements ICapabilityProvider {\n\n private final ItemStack itemStack;\n private final IEnergyItem item;\n\n public ItemCapabilityProvider(ItemStack itemStack, IEnergyItem item) {\n this.itemStack = itemStack;\n this.item = item;\n }\n\n @Override\n public boolean hasCapability(Capability<?> capability, @Nullable EnumFacing facing) {\n if (capability == CapabilityEnergy.ENERGY) {\n return true;\n }\n return false;\n }\n\n @Override\n public <T> T getCapability(Capability<T> capability, @Nullable EnumFacing facing) {\n if (capability == CapabilityEnergy.ENERGY) {\n return (T) new IEnergyStorage() {\n @Override\n public int receiveEnergy(int maxReceive, boolean simulate) {\n return item.receiveEnergy(itemStack, maxReceive, simulate);\n }\n\n @Override\n public int extractEnergy(int maxExtract, boolean simulate) {\n return item.extractEnergy(itemStack, maxExtract, simulate);\n }\n\n @Override\n public int getEnergyStored() {\n return item.getEnergyStored(itemStack);\n }\n\n @Override\n public int getMaxEnergyStored() {\n return item.getMaxEnergyStored(itemStack);\n }\n\n @Override\n public boolean canExtract() {\n return true;\n }\n\n @Override\n public boolean canReceive() {\n return true;\n }\n };\n }\n return null;\n }\n}", "public class Tools {\n public static void error(EntityPlayer player, String msg) {\n player.sendStatusMessage(new TextComponentString(TextFormatting.RED + msg), false);\n }\n\n public static void notify(EntityPlayer player, String msg) {\n player.sendStatusMessage(new TextComponentString(TextFormatting.GREEN + msg), false);\n }\n\n @Nonnull\n public static ItemStack consumeInventoryItem(Item item, int meta, InventoryPlayer inv, EntityPlayer player) {\n if (player.capabilities.isCreativeMode) {\n return new ItemStack(item, 1, meta);\n }\n int i = finditem(item, meta, inv);\n\n if (i < 0) {\n return ItemStack.EMPTY;\n } else {\n ItemStack stackInSlot = inv.getStackInSlot(i);\n ItemStack result = stackInSlot.copy();\n result.setCount(1);\n int amount = -1;\n stackInSlot.grow(amount);\n if (stackInSlot.getCount() == 0) {\n inv.setInventorySlotContents(i, ItemStack.EMPTY);\n }\n\n return result;\n }\n }\n\n public static void giveItem(World world, EntityPlayer player, Block block, int meta, int cnt, BlockPos pos) {\n ItemStack oldStack = new ItemStack(block, cnt, meta);\n giveItem(world, player, pos, oldStack);\n }\n\n public static void giveItem(World world, EntityPlayer player, BlockPos pos, ItemStack oldStack) {\n if (!player.inventory.addItemStackToInventory(oldStack)) {\n // Not enough room. Spawn item in world.\n EntityItem entityItem = new EntityItem(world, pos.getX(), pos.getY(), pos.getZ(), oldStack);\n world.spawnEntity(entityItem);\n }\n }\n\n public static int finditem(Item item, int meta, InventoryPlayer inv) {\n for (int i = 0; i < 36; ++i) {\n ItemStack stack = inv.getStackInSlot(i);\n if (!stack.isEmpty() && stack.getItem() == item && meta == stack.getItemDamage()) {\n return i;\n }\n }\n\n return -1;\n }\n\n public static NBTTagCompound getTagCompound(ItemStack stack) {\n NBTTagCompound tagCompound = stack.getTagCompound();\n if (tagCompound == null){\n tagCompound = new NBTTagCompound();\n stack.setTagCompound(tagCompound);\n }\n return tagCompound;\n }\n\n public static String getBlockName(Block block, int meta) {\n ItemStack s = new ItemStack(block,1,meta);\n if (s.getItem() == null) {\n return null;\n }\n return s.getDisplayName();\n }\n\n public static int getPlayerXP(EntityPlayer player) {\n return (int)(getExperienceForLevel(player.experienceLevel) + (player.experience * player.xpBarCap()));\n }\n\n public static boolean addPlayerXP(EntityPlayer player, int amount) {\n int experience = getPlayerXP(player) + amount;\n if (experience < 0) {\n return false;\n }\n player.experienceTotal = experience;\n player.experienceLevel = getLevelForExperience(experience);\n int expForLevel = getExperienceForLevel(player.experienceLevel);\n player.experience = (experience - expForLevel) / (float)player.xpBarCap();\n return true;\n }\n\n public static int getExperienceForLevel(int level) {\n if (level == 0) { return 0; }\n if (level > 0 && level < 16) {\n return level * 17;\n } else if (level > 15 && level < 31) {\n return (int)(1.5 * Math.pow(level, 2) - 29.5 * level + 360);\n } else {\n return (int)(3.5 * Math.pow(level, 2) - 151.5 * level + 2220);\n }\n }\n\n public static int getXpToNextLevel(int level) {\n int levelXP = getLevelForExperience(level);\n int nextXP = getExperienceForLevel(level + 1);\n return nextXP - levelXP;\n }\n\n public static int getLevelForExperience(int experience) {\n int i = 0;\n while (getExperienceForLevel(i) <= experience) {\n i++;\n }\n return i - 1;\n }\n\n // Server side: play a sound to all nearby players\n public static void playSound(World worldObj, String soundName, double x, double y, double z, double volume, double pitch) {\n SoundEvent event = SoundEvent.REGISTRY.getObject(new ResourceLocation(soundName));\n playSound(worldObj, event, x, y, z, volume, pitch);\n }\n\n public static void playSound(World worldObj, SoundEvent soundEvent, double x, double y, double z, double volume, double pitch) {\n SPacketSoundEffect soundEffect = new SPacketSoundEffect(soundEvent, SoundCategory.BLOCKS, x, y, z, (float) volume, (float) pitch);\n\n for (int j = 0; j < worldObj.playerEntities.size(); ++j) {\n EntityPlayerMP entityplayermp = (EntityPlayerMP)worldObj.playerEntities.get(j);\n double d7 = x - entityplayermp.posX;\n double d8 = y - entityplayermp.posY;\n double d9 = z - entityplayermp.posZ;\n double d10 = d7 * d7 + d8 * d8 + d9 * d9;\n\n if (d10 <= 256.0D) {\n entityplayermp.connection.sendPacket(soundEffect);\n }\n }\n }\n\n}" ]
import mcjty.lib.client.BlockOutlineRenderer; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.TextFormatting; import net.minecraft.world.World; import net.minecraft.world.storage.loot.LootEntryItem; import net.minecraft.world.storage.loot.LootPool; import net.minecraft.world.storage.loot.conditions.LootCondition; import net.minecraft.world.storage.loot.functions.LootFunction; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import romelo333.notenoughwands.ConfigSetup; import romelo333.notenoughwands.KeyBindings; import romelo333.notenoughwands.NotEnoughWands; import romelo333.notenoughwands.ProtectedBlocks; import romelo333.notenoughwands.varia.ItemCapabilityProvider; import romelo333.notenoughwands.varia.Tools; import java.util.ArrayList; import java.util.List; import java.util.Set;
package romelo333.notenoughwands.Items; //import net.minecraft.client.entity.EntityClientPlayerMP; public class GenericWand extends Item implements IEnergyItem { protected int needsxp = 0; protected int needsrf = 0; protected int maxrf = 0; protected int lootRarity = 10; private static List<GenericWand> wands = new ArrayList<>(); @SideOnly(Side.CLIENT) public void registerModel() { ModelLoader.setCustomModelResourceLocation(this, 0, new ModelResourceLocation(getRegistryName(), "inventory")); } @Override public ICapabilityProvider initCapabilities(ItemStack stack, NBTTagCompound nbt) {
return new ItemCapabilityProvider(stack, this);
4
cuberact/cuberact-json
src/test/java/org/cuberact/json/parser/JsonParserTest.java
[ "public abstract class Json implements Serializable {\r\n\r\n @Serial\r\n private static final long serialVersionUID = 1L;\r\n\r\n public abstract JsonType type();\r\n\r\n public final String toString() {\r\n return toString(JsonFormatter.PRETTY());\r\n }\r\n\r\n public final String toString(JsonFormatter formatter) {\r\n JsonOutputStringBuilder writer = new JsonOutputStringBuilder();\r\n toOutput(Objects.requireNonNull(formatter, \"formatter\"), writer);\r\n return writer.getResult().toString();\r\n }\r\n\r\n public abstract void toOutput(JsonFormatter formatter, JsonOutput<?> output);\r\n\r\n\r\n public final void convertJsonNumbers(Function<JsonNumber, Object> converter, boolean callOnChildren) {\r\n if (this instanceof JsonObject) {\r\n JsonObject jo = (JsonObject) this;\r\n for (Map.Entry<String, Object> entry : jo.iterable()) {\r\n if (entry.getValue() instanceof JsonNumber) {\r\n entry.setValue(converter.apply((JsonNumber) entry.getValue()));\r\n } else if (callOnChildren && entry.getValue() instanceof Json) {\r\n ((Json) entry.getValue()).convertJsonNumbers(converter, true);\r\n }\r\n }\r\n } else {\r\n JsonArray ja = (JsonArray) this;\r\n for (int i = 0; i < ja.size(); i++) {\r\n Object o = ja.get(i);\r\n if (o instanceof JsonNumber) {\r\n ja.set(i, converter.apply((JsonNumber) o));\r\n } else if (callOnChildren && o instanceof Json) {\r\n ((Json) o).convertJsonNumbers(converter, true);\r\n }\r\n }\r\n }\r\n }\r\n\r\n @SuppressWarnings(\"unchecked\")\r\n <E> E getValueAsType(Object value, Class<E> type) {\r\n if (value == null) {\r\n return null;\r\n }\r\n if (type.isAssignableFrom(value.getClass())) {\r\n return (E) value;\r\n }\r\n if (value instanceof JsonNumber) {\r\n return (E) ((JsonNumber) value).asNumber((Class<Number>) type);\r\n }\r\n throw new JsonException(\"Wrong value type. Expected \" + type.getName() + \", but actual is \" + value.getClass().getName());\r\n }\r\n}\r", "public class JsonArray extends Json {\r\n\r\n @Serial\r\n private static final long serialVersionUID = 1L;\r\n\r\n private final List<Object> data = new ArrayList<>();\r\n\r\n @Override\r\n public JsonType type() {\r\n return JsonType.ARRAY;\r\n }\r\n\r\n public Object get(int index) {\r\n try {\r\n return data.get(index);\r\n } catch (Throwable t) {\r\n throw new JsonException(t);\r\n }\r\n }\r\n\r\n public JsonObject getObj(int index) {\r\n return getInternal(index, JsonObject.class);\r\n }\r\n\r\n public JsonArray getArr(int index) {\r\n return getInternal(index, JsonArray.class);\r\n }\r\n\r\n public String getString(int index) {\r\n return getInternal(index, String.class);\r\n }\r\n\r\n public Integer getInt(int index) {\r\n return getInternal(index, Integer.class);\r\n }\r\n\r\n public Long getLong(int index) {\r\n return getInternal(index, Long.class);\r\n }\r\n\r\n public Float getFloat(int index) {\r\n return getInternal(index, Float.class);\r\n }\r\n\r\n public Double getDouble(int index) {\r\n return getInternal(index, Double.class);\r\n }\r\n\r\n public BigInteger getBigInt(int index) {\r\n return getInternal(index, BigInteger.class);\r\n }\r\n\r\n public BigDecimal getBigDecimal(int index) {\r\n return getInternal(index, BigDecimal.class);\r\n }\r\n\r\n public Boolean getBoolean(int index) {\r\n return getInternal(index, Boolean.class);\r\n }\r\n\r\n private boolean outOfRange(int index){\r\n return index < 0 || index > data.size()-1;\r\n }\r\n\r\n public JsonObject getObj(int index, JsonObject ifNotExists) {\r\n if (outOfRange(index)) return ifNotExists;\r\n return getInternal(index, JsonObject.class);\r\n }\r\n\r\n public JsonArray getArr(int index, JsonArray ifNotExists) {\r\n if (outOfRange(index)) return ifNotExists;\r\n return getInternal(index, JsonArray.class);\r\n }\r\n\r\n public String getString(int index, String ifNotExists) {\r\n if (outOfRange(index)) return ifNotExists;\r\n return getInternal(index, String.class);\r\n }\r\n\r\n public Integer getInt(int index, Integer ifNotExists) {\r\n if (outOfRange(index)) return ifNotExists;\r\n return getInternal(index, Integer.class);\r\n }\r\n\r\n public Long getLong(int index, Long ifNotExists) {\r\n if (outOfRange(index)) return ifNotExists;\r\n return getInternal(index, Long.class);\r\n }\r\n\r\n public Float getFloat(int index, Float ifNotExists) {\r\n if (outOfRange(index)) return ifNotExists;\r\n return getInternal(index, Float.class);\r\n }\r\n\r\n public Double getDouble(int index, Double ifNotExists) {\r\n if (outOfRange(index)) return ifNotExists;\r\n return getInternal(index, Double.class);\r\n }\r\n\r\n public BigInteger getBigInt(int index, BigInteger ifNotExists) {\r\n if (outOfRange(index)) return ifNotExists;\r\n return getInternal(index, BigInteger.class);\r\n }\r\n\r\n public BigDecimal getBigDecimal(int index, BigDecimal ifNotExists) {\r\n if (outOfRange(index)) return ifNotExists;\r\n return getInternal(index, BigDecimal.class);\r\n }\r\n\r\n public Boolean getBoolean(int index, Boolean ifNotExists) {\r\n if (outOfRange(index)) return ifNotExists;\r\n return getInternal(index, Boolean.class);\r\n }\r\n\r\n public JsonArray add(Object value) {\r\n data.add(value);\r\n return this;\r\n }\r\n\r\n public JsonArray add(int index, Object value) {\r\n try {\r\n data.add(index, value);\r\n } catch (Throwable t) {\r\n throw new JsonException(t);\r\n }\r\n return this;\r\n }\r\n\r\n public JsonArray set(int index, Object value) {\r\n try {\r\n data.set(index, value);\r\n } catch (Throwable t) {\r\n throw new JsonException(t);\r\n }\r\n return this;\r\n }\r\n\r\n public JsonArray remove(int index) {\r\n try {\r\n data.remove(index);\r\n } catch (Throwable t) {\r\n throw new JsonException(t);\r\n }\r\n return this;\r\n }\r\n\r\n public JsonArray remove(Object value) {\r\n data.remove(value);\r\n return this;\r\n }\r\n\r\n public int indexOf(Object value) {\r\n return data.indexOf(value);\r\n }\r\n\r\n public boolean isNotNull(int index) {\r\n return get(index) != null;\r\n }\r\n\r\n public boolean contains(Object value) {\r\n return data.contains(value);\r\n }\r\n\r\n public int size() {\r\n return data.size();\r\n }\r\n\r\n public List<Object> list() {\r\n return data;\r\n }\r\n\r\n public <E> List<E> listOf(Class<E> type) {\r\n return streamOf(type).collect(Collectors.toList());\r\n }\r\n\r\n public Iterable<Object> iterable() {\r\n return list();\r\n }\r\n\r\n public <E> Iterable<E> iterableOf(Class<E> type) {\r\n return listOf(type);\r\n }\r\n\r\n public Stream<Object> stream() {\r\n return data.stream();\r\n }\r\n\r\n @SuppressWarnings(\"unchecked\")\r\n public <E> Stream<E> streamOf(Class<E> type) {\r\n return (Stream<E>) data.stream()\r\n .filter(value -> value != null && type.isAssignableFrom(value.getClass()));\r\n }\r\n\r\n @Override\r\n public void toOutput(JsonFormatter formatter, JsonOutput<?> output) {\r\n if (formatter.writeArrayStart(this, output)) {\r\n for (int i = 0, len = data.size(); i < len; i++) {\r\n if (i != 0) {\r\n formatter.writeArrayComma(this, output);\r\n }\r\n formatter.writeArrayValue(data.get(i),this, output);\r\n }\r\n formatter.writeArrayEnd(this, output);\r\n }\r\n }\r\n\r\n private <E> E getInternal(int index, Class<E> type) {\r\n try {\r\n Object value = data.get(index);\r\n return getValueAsType(value, type);\r\n } catch (Throwable t) {\r\n throw new JsonException(t);\r\n }\r\n }\r\n}\r", "public final class JsonNumber implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n @SuppressWarnings(\"RedundantIfStatement\")\n public static final Function<JsonNumber, Object> CONVERTER_DYNAMIC = jsonNumber -> {\n if (jsonNumber.isFloatingNumber()) {\n double doubleValue = jsonNumber.asDouble();\n if (doubleValue == (double) (float) doubleValue) {\n return (float) doubleValue;\n }\n return doubleValue;\n }\n long longValue = jsonNumber.asLong();\n int intValue = (int) longValue;\n if (intValue == longValue) {\n return intValue;\n }\n return longValue;\n };\n\n public static final Function<JsonNumber, Object> CONVERTER_INT_FLOAT = jsonNumber -> {\n if (jsonNumber.isFloatingNumber()) {\n return jsonNumber.asFloat();\n }\n return jsonNumber.asInt();\n };\n\n public static final Function<JsonNumber, Object> CONVERTER_LONG_DOUBLE = jsonNumber -> {\n if (jsonNumber.isFloatingNumber()) {\n return jsonNumber.asDouble();\n }\n return jsonNumber.asLong();\n };\n\n private final char[] charNumber;\n private final boolean floatingNumber;\n private transient String strNumber;\n\n public JsonNumber(char[] charNumber, int count, boolean floatingNumber) {\n this.charNumber = new char[count];\n System.arraycopy(charNumber, 0, this.charNumber, 0, count);\n this.floatingNumber = floatingNumber;\n }\n\n public boolean isFloatingNumber() {\n return floatingNumber;\n }\n\n public Number asNumber(Class<? extends Number> type) {\n if (Integer.class.equals(type)) {\n return asInt();\n } else if (Long.class.equals(type)) {\n return asLong();\n } else if (Float.class.equals(type)) {\n return asFloat();\n } else if (Double.class.equals(type)) {\n return asDouble();\n } else if (BigInteger.class.equals(type)) {\n return asBigInt();\n } else if (BigDecimal.class.equals(type)) {\n return asBigDecimal();\n }\n throw new JsonException(\"Unknown number type \" + type);\n }\n\n public int asInt() {\n int result = 0;\n int sign = 1;\n char c = charNumber[0];\n if (c == '-') {\n sign = -1;\n } else if (c == '.') {\n return 0;\n } else {\n result = toInt(c);\n }\n for (int i = 1; i < charNumber.length; i++) {\n if (charNumber[i] == '.') break;\n result = result * 10 + toInt(charNumber[i]);\n }\n return sign * result;\n }\n\n public long asLong() {\n long result = 0L;\n long sign = 1L;\n char c = charNumber[0];\n if (c == '-') {\n sign = -1L;\n } else if (c == '.') {\n return 0;\n } else {\n result = toLong(c);\n }\n for (int i = 1; i < charNumber.length; i++) {\n if (charNumber[i] == '.') break;\n result = result * 10L + toLong(charNumber[i]);\n }\n return sign * result;\n }\n\n public float asFloat() {\n return Float.parseFloat(toString());\n }\n\n public double asDouble() {\n return Double.parseDouble(toString());\n }\n\n public BigInteger asBigInt() {\n if (floatingNumber) {\n int indexOfDot = toString().indexOf(\".\");\n if (indexOfDot != -1) {\n String number = toString().substring(0, indexOfDot);\n return number.length() == 0 ? BigInteger.ZERO : new BigInteger(number);\n }\n }\n return new BigInteger(toString());\n }\n\n public BigDecimal asBigDecimal() {\n return new BigDecimal(toString());\n }\n\n public int length() {\n return charNumber.length;\n }\n\n public char charAt(int index) {\n return charNumber[index];\n }\n\n @Override\n public int hashCode() {\n return 31 * Boolean.hashCode(floatingNumber) + Arrays.hashCode(charNumber);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n JsonNumber that = (JsonNumber) o;\n return floatingNumber == that.floatingNumber && (charNumber != null ? Arrays.equals(charNumber, that.charNumber) : that.charNumber == null);\n }\n\n @Override\n public String toString() {\n if (strNumber == null) {\n strNumber = new String(charNumber);\n }\n return strNumber;\n }\n}", "public class JsonObject extends Json {\r\n\r\n @Serial\r\n private static final long serialVersionUID = 1L;\r\n\r\n private final Map<String, Object> data = new LinkedHashMap<>();\r\n\r\n @Override\r\n public JsonType type() {\r\n return JsonType.OBJECT;\r\n }\r\n\r\n public Object get(String attr) {\r\n return data.get(attr);\r\n }\r\n\r\n public JsonObject getObj(String attr) {\r\n return getInternal(attr, JsonObject.class);\r\n }\r\n\r\n public JsonArray getArr(String attr) {\r\n return getInternal(attr, JsonArray.class);\r\n }\r\n\r\n public String getString(String attr) {\r\n return getInternal(attr, String.class);\r\n }\r\n\r\n public Integer getInt(String attr) {\r\n return getInternal(attr, Integer.class);\r\n }\r\n\r\n public Long getLong(String attr) {\r\n return getInternal(attr, Long.class);\r\n }\r\n\r\n public Float getFloat(String attr) {\r\n return getInternal(attr, Float.class);\r\n }\r\n\r\n public Double getDouble(String attr) {\r\n return getInternal(attr, Double.class);\r\n }\r\n\r\n public BigInteger getBigInt(String attr) {\r\n return getInternal(attr, BigInteger.class);\r\n }\r\n\r\n public BigDecimal getBigDecimal(String attr) {\r\n return getInternal(attr, BigDecimal.class);\r\n }\r\n\r\n public Boolean getBoolean(String attr) {\r\n return getInternal(attr, Boolean.class);\r\n }\r\n\r\n public JsonObject getObj(String attr, JsonObject ifNotExists) {\r\n if (!data.containsKey(attr)) return ifNotExists;\r\n return getInternal(attr, JsonObject.class);\r\n }\r\n\r\n public JsonArray getArr(String attr, JsonArray ifNotExists) {\r\n if (!data.containsKey(attr)) return ifNotExists;\r\n return getInternal(attr, JsonArray.class);\r\n }\r\n\r\n public String getString(String attr, String ifNotExists) {\r\n if (!data.containsKey(attr)) return ifNotExists;\r\n return getInternal(attr, String.class);\r\n }\r\n\r\n public Integer getInt(String attr, Integer ifNotExists) {\r\n if (!data.containsKey(attr)) return ifNotExists;\r\n return getInternal(attr, Integer.class);\r\n }\r\n\r\n public Long getLong(String attr, Long ifNotExists) {\r\n if (!data.containsKey(attr)) return ifNotExists;\r\n return getInternal(attr, Long.class);\r\n }\r\n\r\n public Float getFloat(String attr, Float ifNotExists) {\r\n if (!data.containsKey(attr)) return ifNotExists;\r\n return getInternal(attr, Float.class);\r\n }\r\n\r\n public Double getDouble(String attr, Double ifNotExists) {\r\n if (!data.containsKey(attr)) return ifNotExists;\r\n return getInternal(attr, Double.class);\r\n }\r\n\r\n public BigInteger getBigInt(String attr, BigInteger ifNotExists) {\r\n if (!data.containsKey(attr)) return ifNotExists;\r\n return getInternal(attr, BigInteger.class);\r\n }\r\n\r\n public BigDecimal getBigDecimal(String attr, BigDecimal ifNotExists) {\r\n if (!data.containsKey(attr)) return ifNotExists;\r\n return getInternal(attr, BigDecimal.class);\r\n }\r\n\r\n public Boolean getBoolean(String attr, Boolean ifNotExists) {\r\n if (!data.containsKey(attr)) return ifNotExists;\r\n return getInternal(attr, Boolean.class);\r\n }\r\n \r\n public JsonObject add(String attr, Object value) {\r\n data.put(attr, value);\r\n return this;\r\n }\r\n\r\n public JsonObject remove(String attr) {\r\n data.remove(attr);\r\n return this;\r\n }\r\n\r\n public boolean isNotNull(String attr) {\r\n return data.get(attr) != null;\r\n }\r\n\r\n public boolean contains(String attr) {\r\n return data.containsKey(attr);\r\n }\r\n\r\n public int size() {\r\n return data.size();\r\n }\r\n\r\n public Map<String, Object> map() {\r\n return data;\r\n }\r\n\r\n public <E> Map<String, E> mapOf(Class<E> type) {\r\n return streamOf(type).collect(toMap(Entry::getKey, Entry::getValue));\r\n }\r\n\r\n public Iterable<Entry<String, Object>> iterable() {\r\n return data.entrySet();\r\n }\r\n\r\n public <E> Iterable<Entry<String, E>> iterableOf(Class<E> type) {\r\n return streamOf(type).collect(toList());\r\n }\r\n\r\n public Stream<Entry<String, Object>> stream() {\r\n return data.entrySet().stream();\r\n }\r\n\r\n @SuppressWarnings(\"unchecked\")\r\n public <E> Stream<Entry<String, E>> streamOf(Class<E> type) {\r\n return data.entrySet().stream()\r\n .filter(entry -> entry.getValue() != null && type.isAssignableFrom(entry.getValue().getClass()))\r\n .map(value -> (Entry<String, E>) value);\r\n }\r\n\r\n @Override\r\n public void toOutput(JsonFormatter formatter, JsonOutput<?> output) {\r\n if (formatter.writeObjectStart(this, output)) {\r\n boolean addComma = false;\r\n for (Entry<String, Object> entry : data.entrySet()) {\r\n if (addComma) {\r\n formatter.writeObjectComma(this,output);\r\n } else {\r\n addComma = true;\r\n }\r\n formatter.writeObjectAttr(entry.getKey(),this, output);\r\n formatter.writeObjectColon(this,output);\r\n formatter.writeObjectValue(entry.getValue(),this, output);\r\n }\r\n formatter.writeObjectEnd(this,output);\r\n }\r\n }\r\n\r\n private <E> E getInternal(String attr, Class<E> type) {\r\n Object value = data.get(attr);\r\n return getValueAsType(value, type);\r\n }\r\n}\r", "public class JsonBuilderDom extends JsonBuilderBase<JsonObject, JsonArray> {\r\n\r\n public static final JsonBuilderDom REF = new JsonBuilderDom();\r\n\r\n @Override\r\n public JsonObject createObject() {\r\n return new JsonObject();\r\n }\r\n\r\n @Override\r\n public JsonArray createArray() {\r\n return new JsonArray();\r\n }\r\n\r\n @Override\r\n protected void addToObject(JsonObject object, String attr, Object value) {\r\n object.add(attr, value);\r\n }\r\n\r\n @Override\r\n protected void addToArray(JsonArray array, Object value) {\r\n array.add(value);\r\n }\r\n}\r", "public interface JsonFormatter {\r\n\r\n static JsonFormatter PACKED() {\r\n return JsonFormatterPacked.REF;\r\n }\r\n\r\n static JsonFormatter PRETTY() {\r\n return new JsonFormatterPretty();\r\n }\r\n\r\n boolean writeObjectStart(JsonObject json, JsonOutput<?> output);\r\n\r\n void writeObjectAttr(CharSequence attr, JsonObject json, JsonOutput<?> output);\r\n\r\n void writeObjectColon(JsonObject json, JsonOutput<?> output);\r\n\r\n void writeObjectValue(Object value,JsonObject json, JsonOutput<?> output);\r\n\r\n void writeObjectComma(JsonObject json, JsonOutput<?> output);\r\n\r\n void writeObjectEnd(JsonObject json, JsonOutput<?> output);\r\n\r\n boolean writeArrayStart(JsonArray json, JsonOutput<?> output);\r\n\r\n void writeArrayValue(Object value, JsonArray json, JsonOutput<?> output);\r\n\r\n void writeArrayComma(JsonArray json, JsonOutput<?> output);\r\n\r\n void writeArrayEnd(JsonArray json, JsonOutput<?> output);\r\n}\r" ]
import org.cuberact.json.Json; import org.cuberact.json.JsonArray; import org.cuberact.json.JsonNumber; import org.cuberact.json.JsonObject; import org.cuberact.json.builder.JsonBuilderDom; import org.cuberact.json.formatter.JsonFormatter; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; import java.math.BigDecimal; import java.math.BigInteger;
/* * Copyright 2017 Michal Nikodim * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 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.cuberact.json.parser; /** * @author Michal Nikodim ([email protected]) */ public class JsonParserTest { @Test public void parseExample1() { String jsonAsString = "{\n" + " 'rect': [486,'\\u0048\\u0065\\u006c\\u006C\\u006FWorld',{'data' : '\\u011B\\u0161\\u010D\\u0159\\u017E\\u00FD\\u00E1\\u00ED\\u00E9'},-23.54],\n" + " 'perspectiveSelector': {\n" + " 'perspectives': [ true, false],\n" + " 'selected': null,\n" + " 'some': [1,2,3.2]\n" + " }\n" + "}"; jsonAsString = jsonAsString.replace('\'', '"'); String expected = "{'rect':[486,'HelloWorld',{'data':'ěščřžýáíé'},-23.54],'perspectiveSelector':{'perspectives':[true,false],'selected':null,'some':[1,2,3.2]}}" .replace('\'', '"'); Json json = new JsonParser().parse(jsonAsString); assertEquals(expected, json.toString(JsonFormatter.PACKED())); } @Test public void parseExample2() { String jsonAsString = "{\n" + "\t'id' : 'abcdef1234567890',\n" + "\t'apiKey' : 'abcdef-ghijkl',\n" + "\t'name' : 'Main_key',\n" + "\t'validFrom' : 1505858400000,\n" + "\t'softQuota' : 10000000,\n" + "\t'hardQuota' : 10.12345,\n" + "\t'useSignature' : null,\n" + "\t'state' : 'ENABLED',\n" + "\t'mocking' : true,\n" + "\t'clientIpUsed' : false,\n" + "\t'clientIpEnforced' : false\n" + "}"; jsonAsString = jsonAsString.replace('\'', '"'); String expected = "{'id':'abcdef1234567890','apiKey':'abcdef-ghijkl','name':'Main_key','validFrom':1505858400000,'softQuota':10000000,'hardQuota':10.12345,'useSignature':null,'state':'ENABLED','mocking':true,'clientIpUsed':false,'clientIpEnforced':false}" .replace('\'', '"'); Json json = new JsonParser().parse(jsonAsString); assertEquals(expected, json.toString(JsonFormatter.PACKED())); } @Test public void parseExample3() { String jsonAsString = "[1,\n" + "[2, \n" + "[3, \n" + "[4, \n" + "[5], \n" + "4.4], \n" + "3.3], \n" + "2.2], \n" + "1.1]"; String expected = "[1,[2,[3,[4,[5],4.4],3.3],2.2],1.1]"; Json json = new JsonParser().parse(jsonAsString); assertEquals(expected, json.toString(JsonFormatter.PACKED())); } @Test public void parseExample4() { String jsonAsString = "[[[[[[[[[[1]]]]]]]]]]"; Json json = new JsonParser().parse(jsonAsString); assertEquals(jsonAsString, json.toString(JsonFormatter.PACKED())); } @Test public void parseExample5() { String jsonAsString = "[1,-2,'text',true,false,null,1.1,-1.1,{},[]]" .replace('\'', '"'); Json json = new JsonParser().parse(jsonAsString); assertEquals(jsonAsString, json.toString(JsonFormatter.PACKED())); } @Test public void parseExample6() { String jsonAsString = "[1.1,-1.1,2.2e10,2.2e10,-2.2e10,-2.2e-10,2.2e-10,2.2e-10,-2.2e-10,-2.2e-10,12345.12345e8,12345.12345e-8,-12345.12345e8,-12345.12345e-8]"; Json json = new JsonParser().parse(jsonAsString); assertEquals(jsonAsString, json.toString(JsonFormatter.PACKED())); } @Test public void parseExample7() { String jsonAsString = "{'1':{'2':{'3':{'4':{'5':{'6':{'7':{'8':{'9':{'name':'jack'}}}}},'age':15}}}}}" .replace('\'', '"'); Json json = new JsonParser().parse(jsonAsString); assertEquals(jsonAsString, json.toString(JsonFormatter.PACKED())); } @Test public void parseExample8() { String jsonAsString = "{'\\t\\b\\r\\b\\f\\n':12}" .replace('\'', '"'); Json json = new JsonParser().parse(jsonAsString); assertEquals(jsonAsString, json.toString(JsonFormatter.PACKED())); } @Test public void parseExampleVeryLongStrings() { StringBuilder jsonAsString = new StringBuilder("{\""); for (int i = 0; i < 10000; i++) { jsonAsString.append((char) ((i & 15) + 65)); } jsonAsString.append("\":\""); for (int i = 0; i < 100000; i++) { jsonAsString.append((char) ((i & 15) + 65)); } jsonAsString.append("\"}"); Json json = new JsonParser().parse(jsonAsString); assertEquals(jsonAsString.toString(), json.toString(JsonFormatter.PACKED())); } @Test public void testArray() { String jsonAsString = "{'arr':[1,2,3,4,2147483647,-2147483648]}" .replace('\'', '"'); JsonObject json = new JsonParser().parse(jsonAsString);
assertEquals(JsonArray.class, json.getArr("arr").getClass());
1
nisovin/Shopkeepers
src/main/java/com/nisovin/shopkeepers/shoptypes/BookPlayerShopType.java
[ "public class Settings {\n\n\tpublic static String fileEncoding = \"UTF-8\";\n\tpublic static boolean debug = false;\n\n\tpublic static boolean disableOtherVillagers = false;\n\tpublic static boolean hireOtherVillagers = false;\n\tpublic static boolean blockVillagerSpawns = false;\n\tpublic static boolean enableSpawnVerifier = false;\n\tpublic static boolean bypassSpawnBlocking = true;\n\tpublic static boolean bypassShopInteractionBlocking = false;\n\tpublic static boolean enablePurchaseLogging = false;\n\tpublic static boolean saveInstantly = true;\n\tpublic static boolean skipCustomHeadSaving = true;\n\n\tpublic static boolean enableWorldGuardRestrictions = false;\n\tpublic static boolean requireWorldGuardAllowShopFlag = false;\n\tpublic static boolean enableTownyRestrictions = false;\n\n\tpublic static boolean createPlayerShopWithCommand = false;\n\tpublic static boolean simulateRightClickOnCommand = true;\n\tpublic static boolean requireChestRecentlyPlaced = true;\n\tpublic static boolean protectChests = true; // TODO does it make sense to not protected shop chests?\n\tpublic static boolean deleteShopkeeperOnBreakChest = false;\n\tpublic static int maxShopsPerPlayer = 0;\n\tpublic static String maxShopsPermOptions = \"10,15,25\";\n\tpublic static int maxChestDistance = 15;\n\tpublic static int playerShopkeeperInactiveDays = 0;\n\tpublic static boolean preventTradingWithOwnShop = true;\n\tpublic static boolean preventTradingWhileOwnerIsOnline = false;\n\tpublic static boolean useStrictItemComparison = false;\n\tpublic static boolean enableChestOptionOnPlayerShop = false;\n\n\tpublic static int taxRate = 0;\n\tpublic static boolean taxRoundUp = false;\n\n\tpublic static Material shopCreationItem = Material.MONSTER_EGG;\n\tpublic static int shopCreationItemData = 0;\n\tpublic static String shopCreationItemName = \"\";\n\tpublic static List<String> shopCreationItemLore = new ArrayList<String>(0);\n\tpublic static String shopCreationItemSpawnEggEntityType = \"VILLAGER\"; // only works above bukkit 1.11.1, ignored if\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// empty\n\tpublic static boolean preventShopCreationItemRegularUsage = false;\n\tpublic static boolean deletingPlayerShopReturnsCreationItem = false;\n\n\tpublic static List<String> enabledLivingShops = Arrays.asList(\n\t\t\tEntityType.VILLAGER.name(),\n\t\t\tEntityType.COW.name(),\n\t\t\tEntityType.MUSHROOM_COW.name(),\n\t\t\tEntityType.SHEEP.name(),\n\t\t\tEntityType.PIG.name(),\n\t\t\tEntityType.CHICKEN.name(),\n\t\t\tEntityType.OCELOT.name(),\n\t\t\tEntityType.RABBIT.name(),\n\t\t\tEntityType.WOLF.name(),\n\t\t\tEntityType.SNOWMAN.name(),\n\t\t\tEntityType.IRON_GOLEM.name(),\n\t\t\t\"POLAR_BEAR\", // MC 1.10\n\t\t\tEntityType.SKELETON.name(),\n\t\t\t\"STRAY\", // MC 1.11\n\t\t\t\"WITHER_SKELETON\", // MC 1.11\n\t\t\tEntityType.SPIDER.name(),\n\t\t\tEntityType.CAVE_SPIDER.name(),\n\t\t\tEntityType.CREEPER.name(),\n\t\t\tEntityType.WITCH.name(),\n\t\t\tEntityType.ENDERMAN.name(),\n\t\t\tEntityType.ZOMBIE.name(),\n\t\t\t\"ZOMBIE_VILLAGER\", // MC 1.11\n\t\t\tEntityType.PIG_ZOMBIE.name(),\n\t\t\t\"HUSK\", // MC 1.11\n\t\t\tEntityType.GIANT.name(),\n\t\t\tEntityType.GHAST.name(),\n\t\t\tEntityType.SLIME.name(),\n\t\t\tEntityType.MAGMA_CUBE.name(),\n\t\t\tEntityType.SQUID.name(),\n\t\t\t\"EVOKER\", // MC 1.11\n\t\t\t\"VEX\", // MC 1.11\n\t\t\t\"VINDICATOR\", // MC 1.11\n\t\t\t\"ILLUSIONER\", // MC 1.12\n\t\t\t\"PARROT\" // MC 1.12\n\t);\n\n\tpublic static boolean silenceLivingShopEntities = true;\n\n\tpublic static boolean enableSignShops = true;\n\tpublic static boolean enableCitizenShops = false;\n\n\tpublic static String signShopFirstLine = \"[SHOP]\";\n\tpublic static boolean showNameplates = true;\n\tpublic static boolean alwaysShowNameplates = false;\n\tpublic static String nameplatePrefix = \"&a\";\n\tpublic static String nameRegex = \"[A-Za-z0-9 ]{3,32}\";\n\tpublic static boolean namingOfPlayerShopsViaItem = false;\n\tpublic static boolean allowRenamingOfPlayerNpcShops = false;\n\n\tpublic static String editorTitle = \"Shopkeeper Editor\";\n\tpublic static Material nameItem = Material.NAME_TAG;\n\tpublic static int nameItemData = 0;\n\tpublic static String nameItemName = \"\";\n\tpublic static List<String> nameItemLore = new ArrayList<String>(0);\n\tpublic static Material chestItem = Material.CHEST;\n\tpublic static int chestItemData = 0;\n\tpublic static Material deleteItem = Material.BONE;\n\tpublic static int deleteItemData = 0;\n\n\tpublic static Material hireItem = Material.EMERALD;\n\tpublic static int hireItemData = 0;\n\tpublic static String hireItemName = \"\";\n\tpublic static List<String> hireItemLore = new ArrayList<String>(0);\n\tpublic static int hireOtherVillagersCosts = 1;\n\tpublic static String forHireTitle = \"For Hire\";\n\n\tpublic static Material currencyItem = Material.EMERALD;\n\tpublic static short currencyItemData = 0;\n\tpublic static String currencyItemName = \"\";\n\tpublic static List<String> currencyItemLore = new ArrayList<String>(0);\n\tpublic static Material zeroCurrencyItem = Material.BARRIER;\n\tpublic static short zeroCurrencyItemData = 0;\n\tpublic static String zeroCurrencyItemName = \"\";\n\tpublic static List<String> zeroCurrencyItemLore = new ArrayList<String>(0);\n\n\tpublic static Material highCurrencyItem = Material.EMERALD_BLOCK;\n\tpublic static short highCurrencyItemData = 0;\n\tpublic static String highCurrencyItemName = \"\";\n\tpublic static List<String> highCurrencyItemLore = new ArrayList<String>(0);\n\tpublic static int highCurrencyValue = 9;\n\tpublic static int highCurrencyMinCost = 20;\n\tpublic static Material highZeroCurrencyItem = Material.BARRIER;\n\tpublic static short highZeroCurrencyItemData = 0;\n\tpublic static String highZeroCurrencyItemName = \"\";\n\tpublic static List<String> highZeroCurrencyItemLore = new ArrayList<String>(0);\n\n\tpublic static String language = \"en\";\n\n\tpublic static String msgCreationItemSelected = \"&aRight-click to select the shop type.\\n\"\n\t\t\t+ \"&aSneak + right-click to select the object type.\\n\"\n\t\t\t+ \"&aRight-click a chest to select it.\\n\"\n\t\t\t+ \"&aThen right-click a block to place the shopkeeper.\";\n\n\tpublic static String msgButtonName = \"&aSet Shop Name\";\n\tpublic static List<String> msgButtonNameLore = Arrays.asList(\"Lets you rename\", \"your shopkeeper\");\n\tpublic static String msgButtonChest = \"&aView Chest Inventory\";\n\tpublic static List<String> msgButtonChestLore = Arrays.asList(\"Lets you view the inventory\", \" your shopkeeper is using\");\n\tpublic static String msgButtonType = \"&aChoose Appearance\";\n\tpublic static List<String> msgButtonTypeLore = Arrays.asList(\"Changes the look\", \"of your shopkeeper\");\n\tpublic static String msgButtonDelete = \"&4Delete\";\n\tpublic static List<String> msgButtonDeleteLore = Arrays.asList(\"Closes and removes\", \"this shopkeeper\");\n\tpublic static String msgButtonHire = \"&aHire\";\n\tpublic static List<String> msgButtonHireLore = Arrays.asList(\"Buy this shop\");\n\n\tpublic static String msgTradingTitlePrefix = \"&2\";\n\tpublic static String msgTradingTitleDefault = \"Shopkeeper\";\n\n\tpublic static String msgSelectedNormalShop = \"&aNormal shopkeeper selected (sells items to players).\";\n\tpublic static String msgSelectedBookShop = \"&aBook shopkeeper selected (sell books).\";\n\tpublic static String msgSelectedBuyShop = \"&aBuying shopkeeper selected (buys items from players).\";\n\tpublic static String msgSelectedTradeShop = \"&aTrading shopkeeper selected (trade items with players).\";\n\n\tpublic static String msgSelectedLivingShop = \"&aYou selected: &f{type}\";\n\tpublic static String msgSelectedSignShop = \"&aYou selected: &fsign shop\";\n\tpublic static String msgSelectedCitizenShop = \"&aYou selected: &fcitizen npc shop\";\n\n\tpublic static String msgSelectedChest = \"&aChest selected! Right click a block to place your shopkeeper.\";\n\tpublic static String msgMustSelectChest = \"&aYou must right-click a chest before placing your shopkeeper.\";\n\tpublic static String msgChestTooFar = \"&aThe shopkeeper's chest is too far away!\";\n\tpublic static String msgChestNotPlaced = \"&aYou must select a chest you have recently placed.\";\n\tpublic static String msgTooManyShops = \"&aYou have too many shops.\";\n\tpublic static String msgShopCreateFail = \"&aYou cannot create a shopkeeper there.\";\n\tpublic static String msgTypeNewName = \"&aPlease type the shop's name into the chat.\\n\"\n\t\t\t+ \" &aType a dash (-) to remove the name.\";\n\tpublic static String msgNameSet = \"&aThe shop's name has been set!\";\n\tpublic static String msgNameInvalid = \"&aThat name is not valid!\";\n\tpublic static String msgUnknownShopkeeper = \"&7No shopkeeper found with that name or id.\";\n\tpublic static String msgUnknownPlayer = \"&7No player found with that name.\";\n\tpublic static String msgUnknowShopType = \"&7Unknown shop type '{type}'.\";\n\tpublic static String msgShopTypeDisabled = \"&7The shop type '{type}' is disabled.\";\n\tpublic static String msgUnknowShopObjectType = \"&7Unknown shop object type '{type}'.\";\n\tpublic static String msgShopObjectTypeDisabled = \"&7The shop object type '{type}' is disabled.\";\n\tpublic static String msgMustTargetChest = \"&7You have to target a chest.\";\n\tpublic static String msgUnusedChest = \"&7No shopkeeper is using this chest.\";\n\tpublic static String msgNotOwner = \"&7You are not the owner of this shopkeeper.\";\n\t// placeholders: {owner} -> new owners name\n\tpublic static String msgOwnerSet = \"&aNew owner was set to &e{owner}\";\n\n\tpublic static String msgTradePermSet = \"&aThe shop's trading permission has been set!\";\n\tpublic static String msgTradePermRemoved = \"&aThe shop's trading permission has been removed!\";\n\tpublic static String msgTradePermView = \"&aThe shop's current trading permission is '&e{perm}&a'.\";\n\n\tpublic static String msgMustHoldHireItem = \"&7You have to hold the required hire item in your hand.\";\n\tpublic static String msgSetForHire = \"&aThe Shopkeeper was set for hire.\";\n\tpublic static String msgHired = \"&aYou have hired this shopkeeper!\";\n\tpublic static String msgCantHire = \"&aYou cannot afford to hire this shopkeeper.\";\n\t// placeholders: {costs}, {hire-item}\n\tpublic static String msgVillagerForHire = \"&aThe villager offered his services as a shopkeeper in exchange for &6{costs}x {hire-item}&a.\";\n\n\tpublic static String msgMissingTradePerm = \"&7You do not have the permission to trade with this shop.\";\n\tpublic static String msgMissingCustomTradePerm = \"&7You do not have the permission to trade with this shop.\";\n\tpublic static String msgCantTradeWhileOwnerOnline = \"&7You cannot trade while the owner of this shop ('{owner}') is online.\";\n\n\tpublic static String msgPlayerShopCreated = \"&aShopkeeper created!\\n\"\n\t\t\t+ \"&aAdd items you want to sell to your chest, then\\n\"\n\t\t\t+ \"&aright-click the shop while sneaking to modify costs.\";\n\tpublic static String msgBookShopCreated = \"&aShopkeeper created!\\n\"\n\t\t\t+ \"&aAdd written books and blank books to your chest, then\\n\"\n\t\t\t+ \"&aright-click the shop while sneaking to modify costs.\";\n\tpublic static String msgBuyShopCreated = \"&aShopkeeper created!\\n\"\n\t\t\t+ \"&aAdd one of each item you want to buy to your chest, then\\n\"\n\t\t\t+ \"&aright-click the shop while sneaking to modify costs.\";\n\tpublic static String msgTradeShopCreated = \"&aShopkeeper created!\\n\"\n\t\t\t+ \"&aAdd items you want to sell to your chest, then\\n\"\n\t\t\t+ \"&aright-click the shop while sneaking to modify costs.\";\n\tpublic static String msgAdminShopCreated = \"&aShopkeeper created!\\n\"\n\t\t\t+ \"&aRight-click the shop while sneaking to modify trades.\";\n\n\tpublic static String msgListAdminShopsHeader = \"&9There are &e{shopsCount} &9admin shops: &e(Page {page})\";\n\tpublic static String msgListPlayerShopsHeader = \"&9Player '&e{player}&9' has &e{shopsCount} &9shops: &e(Page {page})\";\n\tpublic static String msgListShopsEntry = \" &e{shopIndex}) &8{shopName}&r&7at &8({location})&7, type: &8{shopType}&7, object type: &8{objectType}\";\n\n\tpublic static String msgRemovedAdminShops = \"&e{shopsCount} &aadmin shops were removed.\";\n\tpublic static String msgRemovedPlayerShops = \"&e{shopsCount} &ashops of player '&e{player}&a' were removed.\";\n\tpublic static String msgRemovedAllPlayerShops = \"&aAll &e{shopsCount} &aplayer shops were removed.\";\n\n\tpublic static String msgConfirmRemoveAdminShops = \"&cYou are about to irrevocable remove all admin shops!\\n\"\n\t\t\t+ \"&7Please confirm this action by typing &6/shopkeepers confirm\";\n\tpublic static String msgConfirmRemoveOwnShops = \"&cYou are about to irrevocable remove all your shops!\\n\"\n\t\t\t+ \"&7Please confirm this action by typing &6/shopkeepers confirm\";\n\tpublic static String msgConfirmRemovePlayerShops = \"&cYou are about to irrevocable remove all shops of player &6{player}&c!\\n\"\n\t\t\t+ \"&7Please confirm this action by typing &6/shopkeepers confirm\";\n\tpublic static String msgConfirmRemoveAllPlayerShops = \"&cYou are about to irrevocable remove all player shops of all players!\\n\"\n\t\t\t+ \"&7Please confirm this action by typing &6/shopkeepers confirm\";\n\n\tpublic static String msgConfirmationExpired = \"&cConfirmation expired.\";\n\tpublic static String msgNothingToConfirm = \"&cThere is nothing to confirm currently.\";\n\n\tpublic static String msgNoPermission = \"&cYou don't have the permission to do that.\";\n\n\tpublic static String msgHelpHeader = \"&9***** &8[&6Shopkeepers Help&8] &9*****\";\n\tpublic static String msgCommandHelp = \"&a/shopkeepers help &8- &7Shows this help page.\";\n\tpublic static String msgCommandReload = \"&a/shopkeepers reload &8- &7Reloads this plugin.\";\n\tpublic static String msgCommandDebug = \"&a/shopkeepers debug &8- &7Toggles debug mode on and off.\";\n\tpublic static String msgCommandList = \"&a/shopkeepers list [player|admin] [page] &8- &7Lists all shops for the specified player, or all admin shops.\";\n\tpublic static String msgCommandRemove = \"&a/shopkeepers remove [player|all|admin] &8- &7Removes all shops for the specified player, all players, or all admin shops.\";\n\tpublic static String msgCommandRemote = \"&a/shopkeepers remote <shopName> &8- &7Remotely opens a shop.\";\n\tpublic static String msgCommandTransfer = \"&a/shopkeepers transfer <newOwner> &8- &7Transfers the ownership of a shop.\";\n\tpublic static String msgCommandSettradeperm = \"&a/shopkeepers setTradePerm <shopId> <tradePerm|-|?> &8- &7Sets, removes (-) or displays (?) the trading permission.\";\n\tpublic static String msgCommandSetforhire = \"&a/shopkeepers setForHire &8- &7Sets one of your shops for sale.\";\n\tpublic static String msgCommandShopkeeper = \"&a/shopkeepers [shop type] [object type] &8- &7Creates a shop.\";\n\n\tprivate static String toConfigKey(String fieldName) {\n\t\treturn fieldName.replaceAll(\"([A-Z][a-z]+)\", \"-$1\").toLowerCase();\n\t}\n\n\t// returns true, if the config misses values which need to be saved\n\tpublic static boolean loadConfiguration(Configuration config) {\n\t\tboolean misses = false;\n\t\ttry {\n\t\t\tField[] fields = Settings.class.getDeclaredFields();\n\t\t\tfor (Field field : fields) {\n\t\t\t\tClass<?> typeClass = field.getType();\n\t\t\t\tString configKey = toConfigKey(field.getName());\n\n\t\t\t\t// initialize the setting with the default value, if it is missing in the config\n\t\t\t\tif (!config.isSet(configKey)) {\n\t\t\t\t\tif (typeClass == Material.class) {\n\t\t\t\t\t\tconfig.set(configKey, ((Material) field.get(null)).name());\n\t\t\t\t\t} else if (typeClass == String.class) {\n\t\t\t\t\t\tconfig.set(configKey, Utils.decolorize((String) field.get(null)));\n\t\t\t\t\t} else if (typeClass == List.class && (Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0] == String.class) {\n\t\t\t\t\t\tconfig.set(configKey, Utils.decolorize((List<String>) field.get(null)));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconfig.set(configKey, field.get(null));\n\t\t\t\t\t}\n\t\t\t\t\tmisses = true;\n\t\t\t\t}\n\n\t\t\t\tif (typeClass == String.class) {\n\t\t\t\t\tfield.set(null, Utils.colorize(config.getString(configKey, (String) field.get(null))));\n\t\t\t\t} else if (typeClass == int.class) {\n\t\t\t\t\tfield.set(null, config.getInt(configKey, field.getInt(null)));\n\t\t\t\t} else if (typeClass == short.class) {\n\t\t\t\t\tfield.set(null, (short) config.getInt(configKey, field.getShort(null)));\n\t\t\t\t} else if (typeClass == boolean.class) {\n\t\t\t\t\tfield.set(null, config.getBoolean(configKey, field.getBoolean(null)));\n\t\t\t\t} else if (typeClass == Material.class) {\n\t\t\t\t\tif (config.contains(configKey)) {\n\t\t\t\t\t\tif (config.isInt(configKey)) {\n\t\t\t\t\t\t\t@SuppressWarnings(\"deprecation\")\n\t\t\t\t\t\t\tMaterial mat = Material.getMaterial(config.getInt(configKey));\n\t\t\t\t\t\t\tif (mat != null) {\n\t\t\t\t\t\t\t\tfield.set(null, mat);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (config.isString(configKey)) {\n\t\t\t\t\t\t\tMaterial mat = Material.matchMaterial(config.getString(configKey));\n\t\t\t\t\t\t\tif (mat != null) {\n\t\t\t\t\t\t\t\tfield.set(null, mat);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if (typeClass == List.class) {\n\t\t\t\t\tClass<?> genericType = (Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];\n\t\t\t\t\tif (genericType == String.class) {\n\t\t\t\t\t\tfield.set(null, Utils.colorize(config.getStringList(configKey)));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\t// validation:\n\n\t\tif (maxChestDistance > 50) maxChestDistance = 50;\n\t\tif (highCurrencyValue <= 0) highCurrencyItem = Material.AIR;\n\t\t// certain items cannot be of type AIR:\n\t\tif (shopCreationItem == Material.AIR) shopCreationItem = Material.MONSTER_EGG;\n\t\tif (hireItem == Material.AIR) hireItem = Material.EMERALD;\n\t\tif (currencyItem == Material.AIR) currencyItem = Material.EMERALD;\n\n\t\treturn misses;\n\t}\n\n\tpublic static void loadLanguageConfiguration(Configuration config) {\n\t\ttry {\n\t\t\tField[] fields = Settings.class.getDeclaredFields();\n\t\t\tfor (Field field : fields) {\n\t\t\t\tif (field.getType() == String.class && field.getName().startsWith(\"msg\")) {\n\t\t\t\t\tString configKey = toConfigKey(field.getName());\n\t\t\t\t\tfield.set(null, Utils.colorize(config.getString(configKey, (String) field.get(null))));\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t// item utilities:\n\n\t// creation item:\n\tpublic static ItemStack createShopCreationItem() {\n\t\tItemStack creationItem = Utils.createItemStack(shopCreationItem, 1, (short) shopCreationItemData, shopCreationItemName, shopCreationItemLore);\n\n\t\t// apply spawn egg entity type:\n\t\tif (shopCreationItem == Material.MONSTER_EGG && !Utils.isEmpty(shopCreationItemSpawnEggEntityType) && NMSManager.getProvider().supportsSpawnEggEntityType()) {\n\t\t\tEntityType spawnEggEntityType = null;\n\t\t\ttry {\n\t\t\t\tspawnEggEntityType = EntityType.valueOf(shopCreationItemSpawnEggEntityType);\n\t\t\t} catch (IllegalArgumentException e) {\n\t\t\t\t// unknown entity type, set 'empty' entity type\n\t\t\t}\n\t\t\tNMSManager.getProvider().setSpawnEggEntityType(creationItem, spawnEggEntityType);\n\t\t}\n\n\t\treturn creationItem;\n\t}\n\n\tpublic static boolean isShopCreationItem(ItemStack item) {\n\t\tif (!Utils.isSimilar(item, Settings.shopCreationItem, (short) Settings.shopCreationItemData, Settings.shopCreationItemName, Settings.shopCreationItemLore)) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// check spawn egg entity type:\n\t\tif (shopCreationItem == Material.MONSTER_EGG && !Utils.isEmpty(shopCreationItemSpawnEggEntityType) && NMSManager.getProvider().supportsSpawnEggEntityType()) {\n\t\t\tEntityType spawnEggEntityType = NMSManager.getProvider().getSpawnEggEntityType(item); // can be null\n\t\t\tEntityType requiredEntityType = null;\n\t\t\ttry {\n\t\t\t\trequiredEntityType = EntityType.valueOf(shopCreationItemSpawnEggEntityType);\n\t\t\t} catch (IllegalArgumentException e) {\n\t\t\t\t// unknown entity type, require 'empty' entity type\n\t\t\t}\n\t\t\tif (!Objects.equal(spawnEggEntityType, requiredEntityType)) return false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t// naming item:\n\tpublic static ItemStack createNameButtonItem() {\n\t\treturn Utils.createItemStack(nameItem, 1, (short) nameItemData, msgButtonName, msgButtonNameLore);\n\t}\n\n\tpublic static boolean isNamingItem(ItemStack item) {\n\t\treturn Utils.isSimilar(item, nameItem, (short) nameItemData, Settings.nameItemName, Settings.nameItemLore);\n\t}\n\n\t// chest button:\n\tpublic static ItemStack createChestButtonItem() {\n\t\treturn Utils.createItemStack(chestItem, 1, (short) chestItemData, msgButtonChest, msgButtonChestLore);\n\t}\n\n\t// delete button:\n\tpublic static ItemStack createDeleteButtonItem() {\n\t\treturn Utils.createItemStack(deleteItem, 1, (short) deleteItemData, msgButtonDelete, msgButtonDeleteLore);\n\t}\n\n\t// hire item:\n\tpublic static ItemStack createHireButtonItem() {\n\t\treturn Utils.createItemStack(hireItem, 1, (short) hireItemData, msgButtonHire, msgButtonHireLore);\n\t}\n\n\tpublic static boolean isHireItem(ItemStack item) {\n\t\treturn Utils.isSimilar(item, hireItem, (short) hireItemData, hireItemName, hireItemLore);\n\t}\n\n\t// currency item:\n\tpublic static ItemStack createCurrencyItem(int amount) {\n\t\treturn Utils.createItemStack(Settings.currencyItem, amount, Settings.currencyItemData,\n\t\t\t\tSettings.currencyItemName, Settings.currencyItemLore);\n\t}\n\n\tpublic static boolean isCurrencyItem(ItemStack item) {\n\t\treturn Utils.isSimilar(item, Settings.currencyItem, Settings.currencyItemData,\n\t\t\t\tSettings.currencyItemName, Settings.currencyItemLore);\n\t}\n\n\t// high currency item:\n\tpublic static ItemStack createHighCurrencyItem(int amount) {\n\t\tif (Settings.highCurrencyItem == Material.AIR) return null;\n\t\treturn Utils.createItemStack(Settings.highCurrencyItem, amount, Settings.highCurrencyItemData,\n\t\t\t\tSettings.highCurrencyItemName, Settings.highCurrencyItemLore);\n\t}\n\n\tpublic static boolean isHighCurrencyItem(ItemStack item) {\n\t\tif (Settings.highCurrencyItem == Material.AIR) {\n\t\t\treturn Utils.isEmpty(item);\n\t\t}\n\t\treturn Utils.isSimilar(item, Settings.highCurrencyItem, Settings.highCurrencyItemData,\n\t\t\t\tSettings.highCurrencyItemName, Settings.highCurrencyItemLore);\n\t}\n\n\t// zero currency item:\n\tpublic static ItemStack createZeroCurrencyItem() {\n\t\tif (Settings.zeroCurrencyItem == Material.AIR) return null;\n\t\treturn Utils.createItemStack(Settings.zeroCurrencyItem, 1, Settings.zeroCurrencyItemData,\n\t\t\t\tSettings.zeroCurrencyItemName, Settings.zeroCurrencyItemLore);\n\t}\n\n\tpublic static boolean isZeroCurrencyItem(ItemStack item) {\n\t\tif (Settings.zeroCurrencyItem == Material.AIR) {\n\t\t\treturn Utils.isEmpty(item);\n\t\t}\n\t\treturn Utils.isSimilar(item, Settings.zeroCurrencyItem, Settings.zeroCurrencyItemData,\n\t\t\t\tSettings.zeroCurrencyItemName, Settings.zeroCurrencyItemLore);\n\t}\n\n\t// high zero currency item:\n\tpublic static ItemStack createHighZeroCurrencyItem() {\n\t\tif (Settings.highZeroCurrencyItem == Material.AIR) return null;\n\t\treturn Utils.createItemStack(Settings.highZeroCurrencyItem, 1, Settings.highZeroCurrencyItemData,\n\t\t\t\tSettings.highZeroCurrencyItemName, Settings.highZeroCurrencyItemLore);\n\t}\n\n\tpublic static boolean isHighZeroCurrencyItem(ItemStack item) {\n\t\tif (Settings.highZeroCurrencyItem == Material.AIR) {\n\t\t\treturn Utils.isEmpty(item);\n\t\t}\n\t\treturn Utils.isSimilar(item, Settings.highZeroCurrencyItem, Settings.highZeroCurrencyItemData,\n\t\t\t\tSettings.highZeroCurrencyItemName, Settings.highZeroCurrencyItemLore);\n\t}\n}", "public abstract class ShopType<T extends Shopkeeper> extends SelectableType {\n\n\tprotected ShopType(String identifier, String permission) {\n\t\tsuper(identifier, permission);\n\t}\n\n\t/**\n\t * Whether or not this shop type is a player shop type.\n\t * \n\t * @return false if it is an admin shop type\n\t */\n\tpublic abstract boolean isPlayerShopType(); // TODO is this needed or could be hidden behind some abstraction?\n\n\tpublic abstract String getCreatedMessage();\n\n\tpublic final ShopType<?> selectNext(Player player) {\n\t\treturn ShopkeepersPlugin.getInstance().getShopTypeRegistry().selectNext(player);\n\t}\n\n\t/**\n\t * Creates a shopkeeper of this type.\n\t * This has to check that all data needed for the shop creation are given and valid.\n\t * For example: the owner and chest argument might be null for creating admin shopkeepers\n\t * while they are needed for player shops.\n\t * Returning null indicates that something is preventing the shopkeeper creation.\n\t * \n\t * @param data\n\t * a container holding the necessary arguments (spawn location, object type, owner, etc.) for creating\n\t * this shopkeeper\n\t * @return the created Shopkeeper\n\t * @throws ShopkeeperCreateException\n\t * if the shopkeeper could not be created\n\t */\n\tpublic abstract T createShopkeeper(ShopCreationData data) throws ShopkeeperCreateException;\n\n\t/**\n\t * Creates the shopkeeper of this type by loading the needed data from the given configuration section.\n\t * \n\t * @param config\n\t * the config section to load the shopkeeper data from\n\t * @return the created shopkeeper\n\t * @throws ShopkeeperCreateException\n\t * if the shopkeeper could not be loaded\n\t */\n\tprotected abstract T loadShopkeeper(ConfigurationSection config) throws ShopkeeperCreateException;\n\n\t/**\n\t * This needs to be called right after the creation or loading of a shopkeeper.\n\t * \n\t * @param shopkeeper\n\t * the freshly created shopkeeper\n\t */\n\tprotected void registerShopkeeper(T shopkeeper) {\n\t\tshopkeeper.shopObject.onInit();\n\t\tShopkeepersPlugin.getInstance().registerShopkeeper(shopkeeper);\n\t}\n\n\t// common checks, which might be useful for extending classes:\n\n\tprotected void commonPreChecks(ShopCreationData creationData) throws ShopkeeperCreateException {\n\t\t// common null checks:\n\t\tif (creationData == null || creationData.spawnLocation == null || creationData.objectType == null) {\n\t\t\tthrow new ShopkeeperCreateException(\"null\");\n\t\t}\n\t}\n\n\tprotected void commonPlayerPreChecks(ShopCreationData creationData) throws ShopkeeperCreateException {\n\t\tthis.commonPreChecks(creationData);\n\t\tif (creationData.creator == null || creationData.chest == null) {\n\t\t\tthrow new ShopkeeperCreateException(\"null\");\n\t\t}\n\t}\n\n\tprotected void commonPreChecks(ConfigurationSection section) throws ShopkeeperCreateException {\n\t\t// common null checks:\n\t\tif (section == null) {\n\t\t\tthrow new ShopkeeperCreateException(\"null\");\n\t\t}\n\t}\n}", "public class ShopkeeperCreateException extends Exception {\n\n\tprivate static final long serialVersionUID = -2026963951805397944L;\n\n\tpublic ShopkeeperCreateException(String message) {\n\t\tsuper(message);\n\t}\n}", "public interface ShopkeepersAPI {\n\n\tpublic static final String HELP_PERMISSION = \"shopkeeper.help\";\n\tpublic static final String TRADE_PERMISSION = \"shopkeeper.trade\";\n\tpublic static final String RELOAD_PERMISSION = \"shopkeeper.reload\";\n\tpublic static final String DEBUG_PERMISSION = \"shopkeeper.debug\";\n\tpublic static final String LIST_OWN_PERMISSION = \"shopkeeper.list.own\";\n\tpublic static final String LIST_OTHERS_PERMISSION = \"shopkeeper.list.others\";\n\tpublic static final String LIST_ADMIN_PERMISSION = \"shopkeeper.list.admin\";\n\tpublic static final String REMOVE_OWN_PERMISSION = \"shopkeeper.remove.own\";\n\tpublic static final String REMOVE_OTHERS_PERMISSION = \"shopkeeper.remove.others\";\n\tpublic static final String REMOVE_ALL_PERMISSION = \"shopkeeper.remove.all\";\n\tpublic static final String REMOVE_ADMIN_PERMISSION = \"shopkeeper.remove.admin\";\n\tpublic static final String REMOTE_PERMISSION = \"shopkeeper.remote\";\n\tpublic static final String TRANSFER_PERMISSION = \"shopkeeper.transfer\";\n\tpublic static final String SETTRADEPERM_PERMISSION = \"shopkeeper.settradeperm\";\n\tpublic static final String SETFORHIRE_PERMISSION = \"shopkeeper.setforhire\";\n\tpublic static final String HIRE_PERMISSION = \"shopkeeper.hire\";\n\tpublic static final String BYPASS_PERMISSION = \"shopkeeper.bypass\";\n\tpublic static final String ADMIN_PERMISSION = \"shopkeeper.admin\";\n\tpublic static final String PLAYER_NORMAL_PERMISSION = \"shopkeeper.player.normal\";\n\tpublic static final String PLAYER_BUY_PERMISSION = \"shopkeeper.player.buy\";\n\tpublic static final String PLAYER_TRADE_PERMISSION = \"shopkeeper.player.trade\";\n\tpublic static final String PLAYER_BOOK_PERMISSION = \"shopkeeper.player.book\";\n\n\t/**\n\t * Checks if the given player has the permission to create any shopkeeper.\n\t * \n\t * @param player\n\t * @return <code>false</code> if he cannot create shops at all, <code>true</code> otherwise\n\t */\n\tpublic boolean hasCreatePermission(Player player);\n\n\t/**\n\t * Creates a new admin shopkeeper and spawns it into the world.\n\t * \n\t * @param shopCreationData\n\t * a container holding the necessary arguments (spawn location, object type, etc.) for creating this\n\t * shopkeeper\n\t * @return the shopkeeper created, or <code>null</code> if creation wasn't successful for some reason\n\t */\n\tpublic Shopkeeper createNewAdminShopkeeper(ShopCreationData shopCreationData);\n\n\t/**\n\t * Creates a new player-based shopkeeper and spawns it into the world.\n\t * \n\t * @param shopCreationData\n\t * a container holding the necessary arguments (spawn location, object type, owner, etc.) for creating\n\t * this shopkeeper\n\t * @return the shopkeeper created, or <code>null</code> if creation wasn't successful for some reason\n\t */\n\tpublic Shopkeeper createNewPlayerShopkeeper(ShopCreationData shopCreationData);\n\n\t/**\n\t * Gets the shopkeeper by its unique id.\n\t * \n\t * <p>\n\t * Note: This is not the entity uuid, but the id from {@link Shopkeeper#getUniqueId()}.\n\t * </p>\n\t * \n\t * @param shopkeeperId\n\t * the shopkeeper's unique id\n\t * @return the shopkeeper for the given id, or <code>null</code>\n\t */\n\tpublic Shopkeeper getShopkeeper(UUID shopkeeperId);\n\n\t/**\n\t * Gets the shopkeeper by its current session id.\n\t * \n\t * <p>\n\t * This id is only guaranteed to be valid until the next server restart or reload of the shopkeepers. See\n\t * {@link Shopkeeper#getSessionId()} for details.\n\t * </p>\n\t * \n\t * @param shopkeeperSessionId\n\t * the shopkeeper's session id\n\t * @return the shopkeeper for the given session id, or <code>null</code>\n\t */\n\tpublic Shopkeeper getShopkeeper(int shopkeeperSessionId);\n\n\t/**\n\t * Tries to find a shopkeeper with the given name.\n\t * \n\t * <p>\n\t * This search ignores colors in the shop names.<br>\n\t * Note: Shop names are not unique!\n\t * </p>\n\t * \n\t * @param shopName\n\t * the shop name\n\t * @return the shopkeeper, or <code>null</code>\n\t */\n\tpublic Shopkeeper getShopkeeperByName(String shopName);\n\n\t/**\n\t * Gets the shopkeeper for a given entity.\n\t * \n\t * @param entity\n\t * the entity\n\t * @return the shopkeeper, or <code>null</code> if the given entity is not a shopkeeper\n\t */\n\tpublic Shopkeeper getShopkeeperByEntity(Entity entity);\n\n\t/**\n\t * Gets the shopkeeper for a given block (ex: sign shops).\n\t * \n\t * @param block\n\t * the block\n\t * @return the shopkeeper, or <code>null</code> if the given block is not a shopkeeper\n\t */\n\tpublic Shopkeeper getShopkeeperByBlock(Block block);\n\n\t/**\n\t * Gets all shopkeepers for a given chunk. Returns <code>null</code> if there are no shopkeepers in that chunk.\n\t * \n\t * @param worldName\n\t * the world name\n\t * @param x\n\t * chunk x-coordinate\n\t * @param z\n\t * chunk z-coordinate\n\t * @return an unmodifiable list of shopkeepers, or <code>null</code> if there are none\n\t */\n\tpublic List<Shopkeeper> getShopkeepersInChunk(String worldName, int x, int z);\n\n\t/**\n\t * Gets all shopkeepers for a given chunk. Returns <code>null</code> if there are no shopkeepers in that chunk.\n\t * Similar to {@link #getShopkeepersInChunk(String, int, int)}.\n\t * \n\t * @param chunkData\n\t * specifies the chunk\n\t * @return an unmodifiable list of the shopkeepers in the specified chunk, or <code>null</code> if there are none\n\t */\n\tpublic List<Shopkeeper> getShopkeepersInChunk(ChunkData chunkData);\n\n\t/**\n\t * Checks if a given entity is a Shopkeeper.\n\t * \n\t * @param entity\n\t * the entity to check\n\t * @return whether the entity is a Shopkeeper\n\t */\n\tpublic boolean isShopkeeper(Entity entity);\n\n\t/**\n\t * Gets all shopkeepers.\n\t * \n\t * @return an unmodifiable view on all shopkeepers\n\t */\n\tpublic Collection<Shopkeeper> getAllShopkeepers();\n\n\t/**\n\t * Gets all loaded shopkeepers grouped by the chunks they are in.\n\t * \n\t * @return all loaded shopkeepers\n\t * @deprecated Use {@link #getAllShopkeepers()} instead.\n\t */\n\t@Deprecated\n\tpublic Collection<List<Shopkeeper>> getAllShopkeepersByChunks();\n\n\t/**\n\t * Gets all active shopkeepers. Some shopkeeper types might be always active (like sign shops),\n\t * others are only active as long as their chunk they are in is loaded.\n\t * \n\t * @return an unmodifiable view on all active shopkeepers\n\t */\n\tpublic Collection<Shopkeeper> getActiveShopkeepers();\n\n\t/**\n\t * Requests a save of all the loaded shopkeepers data.\n\t * The actual saving might happen delayed depending on the 'save-instantly' setting from the config.\n\t */\n\tpublic void save();\n\n\t/**\n\t * Instantly saves the shopkeepers data of all loaded shopkeepers to file.\n\t * File IO is going to happen asynchronous.\n\t */\n\tpublic void saveReal();\n}", "public class Utils {\n\n\t/**\n\t * Creates a clone of the given {@link ItemStack} with amount <code>1</code>.\n\t * \n\t * @param item\n\t * the item to get a normalized version of\n\t * @return the normalized item\n\t */\n\tpublic static ItemStack getNormalizedItem(ItemStack item) {\n\t\tif (item == null) return null;\n\t\tItemStack normalizedClone = item.clone();\n\t\tnormalizedClone.setAmount(1);\n\t\treturn normalizedClone;\n\t}\n\n\t// private static final ItemStack EMPTY_ITEM = new ItemStack(Material.AIR, 0);\n\n\tpublic static boolean isEmpty(ItemStack item) {\n\t\treturn item == null || item.getType() == Material.AIR || item.getAmount() <= 0;\n\t}\n\n\tpublic static ItemStack getNullIfEmpty(ItemStack item) {\n\t\treturn isEmpty(item) ? null : item;\n\t}\n\n\t/*public static ItemStack getEmptyIfNull(ItemStack item) {\n\t\treturn item == null ? getEmptyItem() : item;\n\t}\n\t\n\tpublic static ItemStack normalizedIfEmpty(ItemStack item) {\n\t\treturn isEmpty(item) ? EMPTY_ITEM : item;\n\t}\n\n\tpublic static ItemStack getEmptyItem() {\n\t\treturn EMPTY_ITEM.clone();\n\t}*/\n\n\tpublic static boolean isChest(Material material) {\n\t\treturn material == Material.CHEST || material == Material.TRAPPED_CHEST;\n\t}\n\n\tpublic static boolean isSign(Material material) {\n\t\treturn material == Material.WALL_SIGN || material == Material.SIGN_POST || material == Material.SIGN;\n\t}\n\n\t// TODO temporary, due to a bukkit bug custom head item can currently not be saved\n\tpublic static boolean isCustomHeadItem(ItemStack item) {\n\t\tif (item == null) return false;\n\t\tif (item.getType() != Material.SKULL_ITEM) {\n\t\t\treturn false;\n\t\t}\n\t\tif (item.getDurability() != SkullType.PLAYER.ordinal()) {\n\t\t\treturn false;\n\t\t}\n\n\t\tItemMeta meta = item.getItemMeta();\n\t\tif (meta instanceof SkullMeta) {\n\t\t\tSkullMeta skullMeta = (SkullMeta) meta;\n\t\t\tif (skullMeta.hasOwner() && skullMeta.getOwner() == null) {\n\t\t\t\t// custom head items usually don't have a valid owner\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if the given {@link BlockFace} is valid to be used for a wall sign.\n\t * \n\t * @param blockFace\n\t * @return\n\t */\n\tpublic static boolean isWallSignFace(BlockFace blockFace) {\n\t\treturn blockFace == BlockFace.NORTH || blockFace == BlockFace.SOUTH || blockFace == BlockFace.EAST || blockFace == BlockFace.WEST;\n\t}\n\n\t/**\n\t * Determines the axis-aligned {@link BlockFace} for the given direction.\n\t * If modY is zero only {@link BlockFace}s facing horizontal will be returned.\n\t * This method takes into account that the values for EAST/WEST and NORTH/SOUTH\n\t * were switched in some past version of bukkit. So it should also properly work\n\t * with older bukkit versions.\n\t * \n\t * @param modX\n\t * @param modY\n\t * @param modZ\n\t * @return\n\t */\n\tpublic static BlockFace getAxisBlockFace(double modX, double modY, double modZ) {\n\t\tdouble xAbs = Math.abs(modX);\n\t\tdouble yAbs = Math.abs(modY);\n\t\tdouble zAbs = Math.abs(modZ);\n\n\t\tif (xAbs >= zAbs) {\n\t\t\tif (xAbs >= yAbs) {\n\t\t\t\tif (modX >= 0.0D) {\n\t\t\t\t\t// EAST/WEST and NORTH/SOUTH values were switched in some past bukkit version:\n\t\t\t\t\t// with this additional checks it should work across different versions\n\t\t\t\t\tif (BlockFace.EAST.getModX() == 1) {\n\t\t\t\t\t\treturn BlockFace.EAST;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn BlockFace.WEST;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (BlockFace.EAST.getModX() == 1) {\n\t\t\t\t\t\treturn BlockFace.WEST;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn BlockFace.EAST;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (modY >= 0.0D) {\n\t\t\t\t\treturn BlockFace.UP;\n\t\t\t\t} else {\n\t\t\t\t\treturn BlockFace.DOWN;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif (zAbs >= yAbs) {\n\t\t\t\tif (modZ >= 0.0D) {\n\t\t\t\t\tif (BlockFace.SOUTH.getModZ() == 1) {\n\t\t\t\t\t\treturn BlockFace.SOUTH;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn BlockFace.NORTH;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (BlockFace.SOUTH.getModZ() == 1) {\n\t\t\t\t\t\treturn BlockFace.NORTH;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn BlockFace.SOUTH;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (modY >= 0.0D) {\n\t\t\t\t\treturn BlockFace.UP;\n\t\t\t\t} else {\n\t\t\t\t\treturn BlockFace.DOWN;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Tries to find the nearest wall sign {@link BlockFace} facing towards the given direction.\n\t * \n\t * @param direction\n\t * @return a valid wall sign face\n\t */\n\tpublic static BlockFace toWallSignFace(Vector direction) {\n\t\tassert direction != null;\n\t\treturn getAxisBlockFace(direction.getX(), 0.0D, direction.getZ());\n\t}\n\n\t/**\n\t * Gets the block face a player is looking at.\n\t * \n\t * @param player\n\t * the player\n\t * @param targetBlock\n\t * the block the player is looking at\n\t * @return the block face, or null if none was found\n\t */\n\tpublic static BlockFace getTargetBlockFace(Player player, Block targetBlock) {\n\t\tLocation intersection = getBlockIntersection(player, targetBlock);\n\t\tif (intersection == null) return null;\n\t\tLocation blockCenter = targetBlock.getLocation().add(0.5D, 0.5D, 0.5D);\n\t\tVector centerToIntersection = intersection.subtract(blockCenter).toVector();\n\t\tdouble x = centerToIntersection.getX();\n\t\tdouble y = centerToIntersection.getY();\n\t\tdouble z = centerToIntersection.getZ();\n\t\treturn getAxisBlockFace(x, y, z);\n\t}\n\n\t/**\n\t * Determines the exact intersection point of a players view and a targeted block.\n\t * \n\t * @param player\n\t * the player\n\t * @param targetBlock\n\t * the block the player is looking at\n\t * @return the intersection point of the players view and the target block,\n\t * or null if no intersection was found\n\t */\n\tpublic static Location getBlockIntersection(Player player, Block targetBlock) {\n\t\tif (player == null || targetBlock == null) return null;\n\n\t\t// block bounds:\n\t\tdouble minX = targetBlock.getX();\n\t\tdouble minY = targetBlock.getY();\n\t\tdouble minZ = targetBlock.getZ();\n\n\t\tdouble maxX = minX + 1.0D;\n\t\tdouble maxY = minY + 1.0D;\n\t\tdouble maxZ = minZ + 1.0D;\n\n\t\t// ray origin:\n\t\tLocation origin = player.getEyeLocation();\n\t\tdouble originX = origin.getX();\n\t\tdouble originY = origin.getY();\n\t\tdouble originZ = origin.getZ();\n\n\t\t// ray direction\n\t\tVector dir = origin.getDirection();\n\t\tdouble dirX = dir.getX();\n\t\tdouble dirY = dir.getY();\n\t\tdouble dirZ = dir.getZ();\n\n\t\t// tiny improvement to save a few divisions below:\n\t\tdouble divX = 1.0D / dirX;\n\t\tdouble divY = 1.0D / dirY;\n\t\tdouble divZ = 1.0D / dirZ;\n\n\t\t// intersection interval:\n\t\tdouble t0 = 0.0D;\n\t\tdouble t1 = Double.MAX_VALUE;\n\n\t\tdouble tmin;\n\t\tdouble tmax;\n\n\t\tdouble tymin;\n\t\tdouble tymax;\n\n\t\tdouble tzmin;\n\t\tdouble tzmax;\n\n\t\tif (dirX >= 0.0D) {\n\t\t\ttmin = (minX - originX) * divX;\n\t\t\ttmax = (maxX - originX) * divX;\n\t\t} else {\n\t\t\ttmin = (maxX - originX) * divX;\n\t\t\ttmax = (minX - originX) * divX;\n\t\t}\n\n\t\tif (dirY >= 0.0D) {\n\t\t\ttymin = (minY - originY) * divY;\n\t\t\ttymax = (maxY - originY) * divY;\n\t\t} else {\n\t\t\ttymin = (maxY - originY) * divY;\n\t\t\ttymax = (minY - originY) * divY;\n\t\t}\n\n\t\tif ((tmin > tymax) || (tymin > tmax)) {\n\t\t\treturn null;\n\t\t}\n\n\t\tif (tymin > tmin) tmin = tymin;\n\t\tif (tymax < tmax) tmax = tymax;\n\n\t\tif (dirZ >= 0.0D) {\n\t\t\ttzmin = (minZ - originZ) * divZ;\n\t\t\ttzmax = (maxZ - originZ) * divZ;\n\t\t} else {\n\t\t\ttzmin = (maxZ - originZ) * divZ;\n\t\t\ttzmax = (minZ - originZ) * divZ;\n\t\t}\n\n\t\tif ((tmin > tzmax) || (tzmin > tmax)) {\n\t\t\treturn null;\n\t\t}\n\n\t\tif (tzmin > tmin) tmin = tzmin;\n\t\tif (tzmax < tmax) tmax = tzmax;\n\n\t\tif ((tmin >= t1) || (tmax <= t0)) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// intersection:\n\t\tLocation intersection = origin.add(dir.multiply(tmin));\n\t\treturn intersection;\n\t}\n\n\t// messages:\n\n\tpublic static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat(\"0.##\", new DecimalFormatSymbols(Locale.US));\n\tstatic {\n\t\tDECIMAL_FORMAT.setGroupingUsed(false);\n\t}\n\n\tpublic static String getLocationString(Location location) {\n\t\treturn getLocationString(location.getWorld().getName(), location.getX(), location.getY(), location.getZ());\n\t}\n\n\tpublic static String getLocationString(Block block) {\n\t\treturn getLocationString(block.getWorld().getName(), block.getX(), block.getY(), block.getZ());\n\t}\n\n\tpublic static String getLocationString(String worldName, double x, double y, double z) {\n\t\treturn worldName + \",\" + DECIMAL_FORMAT.format(x) + \",\" + DECIMAL_FORMAT.format(y) + \",\" + DECIMAL_FORMAT.format(z);\n\t}\n\n\tpublic static String translateColorCodesToAlternative(char altColorChar, String textToTranslate) {\n\t\tchar[] b = textToTranslate.toCharArray();\n\t\tfor (int i = 0; i < b.length - 1; i++) {\n\t\t\tif (b[i] == ChatColor.COLOR_CHAR && \"0123456789AaBbCcDdEeFfKkLlMmNnOoRr\".indexOf(b[i + 1]) > -1) {\n\t\t\t\tb[i] = altColorChar;\n\t\t\t\tb[i + 1] = Character.toLowerCase(b[i + 1]);\n\t\t\t}\n\t\t}\n\t\treturn new String(b);\n\t}\n\n\tpublic static String decolorize(String colored) {\n\t\tif (colored == null) return null;\n\t\treturn Utils.translateColorCodesToAlternative('&', colored);\n\t}\n\n\tpublic static List<String> decolorize(List<String> colored) {\n\t\tif (colored == null) return null;\n\t\tList<String> decolored = new ArrayList<String>(colored.size());\n\t\tfor (String string : colored) {\n\t\t\tdecolored.add(Utils.translateColorCodesToAlternative('&', string));\n\t\t}\n\t\treturn decolored;\n\t}\n\n\tpublic static String colorize(String message) {\n\t\tif (message == null || message.isEmpty()) return message;\n\t\treturn ChatColor.translateAlternateColorCodes('&', message);\n\t}\n\n\tpublic static List<String> colorize(List<String> messages) {\n\t\tif (messages == null) return messages;\n\t\tList<String> colored = new ArrayList<String>(messages.size());\n\t\tfor (String message : messages) {\n\t\t\tcolored.add(Utils.colorize(message));\n\t\t}\n\t\treturn colored;\n\t}\n\n\tpublic static void sendMessage(CommandSender sender, String message, String... args) {\n\t\t// skip if sender is null or message is \"empty\":\n\t\tif (sender == null || message == null || message.isEmpty()) return;\n\t\tif (args != null && args.length >= 2) {\n\t\t\t// replace arguments (key-value replacement):\n\t\t\tString key;\n\t\t\tString value;\n\t\t\tfor (int i = 1; i < args.length; i += 2) {\n\t\t\t\tkey = args[i - 1];\n\t\t\t\tvalue = args[i];\n\t\t\t\tif (key == null || value == null) continue; // skip invalid arguments\n\t\t\t\tmessage = message.replace(key, value);\n\t\t\t}\n\t\t}\n\n\t\tString[] msgs = message.split(\"\\n\");\n\t\tfor (String msg : msgs) {\n\t\t\tsender.sendMessage(msg);\n\t\t}\n\t}\n\n\tpublic static boolean isEmpty(String string) {\n\t\treturn string == null || string.isEmpty();\n\t}\n\n\tpublic static String normalize(String identifier) {\n\t\tif (identifier == null) return null;\n\t\treturn identifier.trim().replace('_', '-').replace(' ', '-').toLowerCase(Locale.ROOT);\n\t}\n\n\tpublic static List<String> normalize(List<String> identifiers) {\n\t\tif (identifiers == null) return null;\n\t\tList<String> normalized = new ArrayList<String>(identifiers.size());\n\t\tfor (String identifier : identifiers) {\n\t\t\tnormalized.add(normalize(identifier));\n\t\t}\n\t\treturn normalized;\n\t}\n\n\t/**\n\t * Performs a permissions check and logs debug information about it.\n\t * \n\t * @param permissible\n\t * @param permission\n\t * @return\n\t */\n\tpublic static boolean hasPermission(Permissible permissible, String permission) {\n\t\tassert permissible != null;\n\t\tboolean hasPerm = permissible.hasPermission(permission);\n\t\tif (!hasPerm && (permissible instanceof Player)) {\n\t\t\tLog.debug(\"Player '\" + ((Player) permissible).getName() + \"' does not have permission '\" + permission + \"'.\");\n\t\t}\n\t\treturn hasPerm;\n\t}\n\n\t// entity utilities:\n\n\tpublic static boolean isNPC(Entity entity) {\n\t\treturn entity.hasMetadata(\"NPC\");\n\t}\n\n\tpublic static List<Entity> getNearbyEntities(Location location, double radius, EntityType... types) {\n\t\tList<Entity> entities = new ArrayList<Entity>();\n\t\tif (location == null) return entities;\n\t\tif (radius <= 0.0D) return entities;\n\n\t\tdouble radius2 = radius * radius;\n\t\tint chunkRadius = ((int) (radius / 16)) + 1;\n\t\tChunk center = location.getChunk();\n\t\tint startX = center.getX() - chunkRadius;\n\t\tint endX = center.getX() + chunkRadius;\n\t\tint startZ = center.getZ() - chunkRadius;\n\t\tint endZ = center.getZ() + chunkRadius;\n\t\tWorld world = location.getWorld();\n\t\tfor (int chunkX = startX; chunkX <= endX; chunkX++) {\n\t\t\tfor (int chunkZ = startZ; chunkZ <= endZ; chunkZ++) {\n\t\t\t\tif (!world.isChunkLoaded(chunkX, chunkZ)) continue;\n\t\t\t\tChunk chunk = world.getChunkAt(chunkX, chunkZ);\n\t\t\t\tfor (Entity entity : chunk.getEntities()) {\n\t\t\t\t\tLocation entityLoc = entity.getLocation();\n\t\t\t\t\t// TODO: this is a workaround: for some yet unknown reason entities sometimes report to be in a\n\t\t\t\t\t// different world..\n\t\t\t\t\tif (!entityLoc.getWorld().equals(world)) {\n\t\t\t\t\t\tLog.debug(\"Found an entity which reports to be in a different world than the chunk we got it from:\");\n\t\t\t\t\t\tLog.debug(\"Location=\" + location + \", Chunk=\" + chunk + \", ChunkWorld=\" + chunk.getWorld()\n\t\t\t\t\t\t\t\t+ \", entityType=\" + entity.getType() + \", entityLocation=\" + entityLoc);\n\t\t\t\t\t\tcontinue; // skip this entity\n\t\t\t\t\t}\n\n\t\t\t\t\tif (entityLoc.distanceSquared(location) <= radius2) {\n\t\t\t\t\t\tif (types == null) {\n\t\t\t\t\t\t\tentities.add(entity);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tEntityType type = entity.getType();\n\t\t\t\t\t\t\tfor (EntityType t : types) {\n\t\t\t\t\t\t\t\tif (type.equals(t)) {\n\t\t\t\t\t\t\t\t\tentities.add(entity);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn entities;\n\t}\n\n\t// itemstack utilities:\n\n\tpublic static ItemStack createItemStack(Material type, int amount, short data, String displayName, List<String> lore) {\n\t\t// TODO return null in case of type AIR?\n\t\tItemStack item = new ItemStack(type, amount, data);\n\t\treturn setItemStackNameAndLore(item, displayName, lore);\n\t}\n\n\tpublic static ItemStack setItemStackNameAndLore(ItemStack item, String displayName, List<String> lore) {\n\t\tif (item == null) return null;\n\t\tItemMeta meta = item.getItemMeta();\n\t\tif (meta != null) {\n\t\t\tmeta.setDisplayName(displayName);\n\t\t\tmeta.setLore(lore);\n\t\t\titem.setItemMeta(meta);\n\t\t}\n\t\treturn item;\n\t}\n\n\tpublic static String getSimpleItemInfo(ItemStack item) {\n\t\tif (item == null) return \"none\";\n\t\tStringBuilder sb = new StringBuilder();\n\t\tsb.append(item.getType()).append('~').append(item.getDurability());\n\t\treturn sb.toString();\n\t}\n\n\tpublic static String getSimpleRecipeInfo(ItemStack[] recipe) {\n\t\tif (recipe == null) return \"none\";\n\t\tStringBuilder sb = new StringBuilder();\n\t\tsb.append(\"[0=\").append(getSimpleItemInfo(recipe[0]))\n\t\t\t\t.append(\",1=\").append(getSimpleItemInfo(recipe[1]))\n\t\t\t\t.append(\",2=\").append(getSimpleItemInfo(recipe[2])).append(\"]\");\n\t\treturn sb.toString();\n\t}\n\n\t/**\n\t * Same as {@link ItemStack#isSimilar(ItemStack)}, but taking into account that both given ItemStacks might be\n\t * <code>null</code>.\n\t * \n\t * @param item1\n\t * an itemstack\n\t * @param item2\n\t * another itemstack\n\t * @return <code>true</code> if the given item stacks are both <code>null</code> or similar\n\t */\n\tpublic static boolean isSimilar(ItemStack item1, ItemStack item2) {\n\t\tif (item1 == null) return (item2 == null);\n\t\treturn item1.isSimilar(item2);\n\t}\n\n\t/**\n\t * Checks if the given item matches the specified attributes.\n\t * \n\t * @param item\n\t * the item\n\t * @param type\n\t * The item type.\n\t * @param data\n\t * The data value/durability. If -1 is is ignored.\n\t * @param displayName\n\t * The displayName. If null or empty it is ignored.\n\t * @param lore\n\t * The item lore. If null or empty it is ignored.\n\t * @return <code>true</code> if the item has similar attributes\n\t */\n\tpublic static boolean isSimilar(ItemStack item, Material type, short data, String displayName, List<String> lore) {\n\t\tif (item == null) return false;\n\t\tif (item.getType() != type) return false;\n\t\tif (data != -1 && item.getDurability() != data) return false;\n\n\t\tItemMeta itemMeta = null;\n\t\t// compare display name:\n\t\tif (displayName != null && !displayName.isEmpty()) {\n\t\t\tif (!item.hasItemMeta()) return false;\n\t\t\titemMeta = item.getItemMeta();\n\t\t\tif (itemMeta == null) return false;\n\n\t\t\tif (!itemMeta.hasDisplayName() || !displayName.equals(itemMeta.getDisplayName())) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\t// compare lore:\n\t\tif (lore != null && !lore.isEmpty()) {\n\t\t\tif (itemMeta == null) {\n\t\t\t\tif (!item.hasItemMeta()) return false;\n\t\t\t\titemMeta = item.getItemMeta();\n\t\t\t\tif (itemMeta == null) return false;\n\t\t\t}\n\n\t\t\tif (!itemMeta.hasLore() || !lore.equals(itemMeta.getLore())) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t// save and load itemstacks from config, including attributes:\n\n\t/**\n\t * Saves the given {@link ItemStack} to the given configuration section.\n\t * Also saves the item's attributes in the same section at '{node}_attributes'.\n\t * \n\t * @param section\n\t * a configuration section\n\t * @param node\n\t * where to save the item stack inside the section\n\t * @param item\n\t * the item stack to save, can be null\n\t */\n\tpublic static void saveItem(ConfigurationSection section, String node, ItemStack item) {\n\t\tassert section != null && node != null;\n\t\tsection.set(node, item);\n\t\t// saving attributes manually, as they weren't saved by bukkit in the past:\n\t\tString attributes = NMSManager.getProvider().saveItemAttributesToString(item);\n\t\tif (attributes != null && !attributes.isEmpty()) {\n\t\t\tString attributesNode = node + \"_attributes\";\n\t\t\tsection.set(attributesNode, attributes);\n\t\t}\n\t}\n\n\t/**\n\t * Loads an {@link ItemStack} from the given configuration section.\n\t * Also attempts to load attributes saved at '{node}_attributes'.\n\t * \n\t * @param section\n\t * a configuration section\n\t * @param node\n\t * where to load the item stack from inside the section\n\t * @return the loaded item stack, possibly null\n\t */\n\tpublic static ItemStack loadItem(ConfigurationSection section, String node) {\n\t\tassert section != null && node != null;\n\t\tItemStack item = section.getItemStack(node);\n\t\t// loading separately stored attributes:\n\t\tString attributesNode = node + \"_attributes\";\n\t\tif (item != null && section.contains(attributesNode)) {\n\t\t\tString attributes = section.getString(attributesNode);\n\t\t\tif (attributes != null && !attributes.isEmpty()) {\n\t\t\t\titem = NMSManager.getProvider().loadItemAttributesFromString(item, attributes);\n\t\t\t}\n\t\t}\n\t\treturn item;\n\t}\n\n\t// inventory utilities:\n\n\tpublic static List<ItemCount> getItemCountsFromInventory(Inventory inventory, Filter<ItemStack> filter) {\n\t\tList<ItemCount> itemCounts = new ArrayList<ItemCount>();\n\t\tif (inventory != null) {\n\t\t\tItemStack[] contents = inventory.getContents();\n\t\t\tfor (ItemStack item : contents) {\n\t\t\t\tif (isEmpty(item)) continue;\n\t\t\t\tif (filter != null && !filter.accept(item)) continue;\n\n\t\t\t\t// check if we already have a counter for this type of item:\n\t\t\t\tItemCount itemCount = ItemCount.findSimilar(itemCounts, item);\n\t\t\t\tif (itemCount != null) {\n\t\t\t\t\t// increase item count:\n\t\t\t\t\titemCount.addAmount(item.getAmount());\n\t\t\t\t} else {\n\t\t\t\t\t// add new item entry:\n\t\t\t\t\titemCounts.add(new ItemCount(item, item.getAmount()));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn itemCounts;\n\t}\n\n\t/**\n\t * Checks if the given inventory contains at least a certain amount of items which match the specified attributes.\n\t * \n\t * @param inv\n\t * @param type\n\t * The item type.\n\t * @param data\n\t * The data value/durability. If -1 is is ignored.\n\t * @param displayName\n\t * The displayName. If null it is ignored.\n\t * @param lore\n\t * The item lore. If null or empty it is ignored.\n\t * @param ignoreNameAndLore\n\t * @param amount\n\t * @return\n\t */\n\tpublic static boolean hasInventoryItemsAtLeast(Inventory inv, Material type, short data, String displayName, List<String> lore, int amount) {\n\t\tfor (ItemStack is : inv.getContents()) {\n\t\t\tif (!Utils.isSimilar(is, type, data, displayName, lore)) continue;\n\t\t\tint currentAmount = is.getAmount() - amount;\n\t\t\tif (currentAmount >= 0) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\tamount = -currentAmount;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Adds the given {@link ItemStack} to the given contents.\n\t * \n\t * <p>\n\t * This will first try to fill similar partial {@link ItemStack}s in the contents up to the item's max stack size.\n\t * Afterwards it will insert the remaining amount into empty slots, splitting at the item's max stack size.<br>\n\t * This does not modify the original item stacks. If it has to modify the amount of an item stack, it first replaces\n\t * it with a copy. So in case those item stacks are mirroring changes to their minecraft counterpart, those don't\n\t * get affected directly.\n\t * </p>\n\t * \n\t * @param contents\n\t * The contents to add the given {@link ItemStack} to.\n\t * @param item\n\t * The {@link ItemStack} to add to the given contents.\n\t * @return The amount of items which couldn't be added (0 on full success).\n\t */\n\tpublic static int addItems(ItemStack[] contents, ItemStack item) {\n\t\tValidate.notNull(contents);\n\t\tValidate.notNull(item);\n\t\tint amount = item.getAmount();\n\t\tValidate.isTrue(amount >= 0);\n\t\tif (amount == 0) return 0;\n\n\t\t// search for partially fitting item stacks:\n\t\tint maxStackSize = item.getMaxStackSize();\n\t\tint size = contents.length;\n\t\tfor (int slot = 0; slot < size; slot++) {\n\t\t\tItemStack slotItem = contents[slot];\n\n\t\t\t// slot empty? - skip, because we are currently filling existing item stacks up\n\t\t\tif (isEmpty(slotItem)) continue;\n\n\t\t\t// slot already full?\n\t\t\tint slotAmount = slotItem.getAmount();\n\t\t\tif (slotAmount >= maxStackSize) continue;\n\n\t\t\tif (slotItem.isSimilar(item)) {\n\t\t\t\t// copy itemstack, so we don't modify the original itemstack:\n\t\t\t\tslotItem = slotItem.clone();\n\t\t\t\tcontents[slot] = slotItem;\n\n\t\t\t\tint newAmount = slotAmount + amount;\n\t\t\t\tif (newAmount <= maxStackSize) {\n\t\t\t\t\t// remaining amount did fully fit into this stack:\n\t\t\t\t\tslotItem.setAmount(newAmount);\n\t\t\t\t\treturn 0;\n\t\t\t\t} else {\n\t\t\t\t\t// did not fully fit:\n\t\t\t\t\tslotItem.setAmount(maxStackSize);\n\t\t\t\t\tamount -= (maxStackSize - slotAmount);\n\t\t\t\t\tassert amount != 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// we have items remaining:\n\t\tassert amount > 0;\n\n\t\t// search for free slots:\n\t\tfor (int slot = 0; slot < size; slot++) {\n\t\t\tItemStack slotItem = contents[slot];\n\t\t\tif (isEmpty(slotItem)) {\n\t\t\t\t// found free slot:\n\t\t\t\tif (amount > maxStackSize) {\n\t\t\t\t\t// add full stack:\n\t\t\t\t\tItemStack stack = item.clone();\n\t\t\t\t\tstack.setAmount(maxStackSize);\n\t\t\t\t\tcontents[slot] = stack;\n\t\t\t\t\tamount -= maxStackSize;\n\t\t\t\t} else {\n\t\t\t\t\t// completely fits:\n\t\t\t\t\tItemStack stack = item.clone(); // create a copy, just in case\n\t\t\t\t\tstack.setAmount(amount); // stack of remaining amount\n\t\t\t\t\tcontents[slot] = stack;\n\t\t\t\t\treturn 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// not all items did fit into the inventory:\n\t\treturn amount;\n\t}\n\n\t/**\n\t * Removes the given {@link ItemStack} from the given contents.\n\t * \n\t * <p>\n\t * If the amount of the given {@link ItemStack} is {@link Integer#MAX_VALUE}, then all similar items are being\n\t * removed from the contents.<br>\n\t * This does not modify the original item stacks. If it has to modify the amount of an item stack, it first replaces\n\t * it with a copy. So in case those item stacks are mirroring changes to their minecraft counterpart, those don't\n\t * get affected directly.\n\t * </p>\n\t * \n\t * @param contents\n\t * The contents to remove the given {@link ItemStack} from.\n\t * @param item\n\t * The {@link ItemStack} to remove from the given contents.\n\t * @return The amount of items which couldn't be removed (0 on full success).\n\t */\n\tpublic static int removeItems(ItemStack[] contents, ItemStack item) {\n\t\tValidate.notNull(contents);\n\t\tValidate.notNull(item);\n\t\tint amount = item.getAmount();\n\t\tValidate.isTrue(amount >= 0);\n\t\tif (amount == 0) return 0;\n\n\t\tboolean removeAll = (amount == Integer.MAX_VALUE);\n\t\tint size = contents.length;\n\t\tfor (int slot = 0; slot < size; slot++) {\n\t\t\tItemStack slotItem = contents[slot];\n\t\t\tif (slotItem == null) continue;\n\t\t\tif (item.isSimilar(slotItem)) {\n\t\t\t\tif (removeAll) {\n\t\t\t\t\tcontents[slot] = null;\n\t\t\t\t} else {\n\t\t\t\t\tint newAmount = slotItem.getAmount() - amount;\n\t\t\t\t\tif (newAmount > 0) {\n\t\t\t\t\t\t// copy itemstack, so we don't modify the original itemstack:\n\t\t\t\t\t\tslotItem = slotItem.clone();\n\t\t\t\t\t\tcontents[slot] = slotItem;\n\t\t\t\t\t\tslotItem.setAmount(newAmount);\n\t\t\t\t\t\t// all items were removed:\n\t\t\t\t\t\treturn 0;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcontents[slot] = null;\n\t\t\t\t\t\tamount = -newAmount;\n\t\t\t\t\t\tif (amount == 0) {\n\t\t\t\t\t\t\t// all items were removed:\n\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (removeAll) return 0;\n\t\treturn amount;\n\t}\n\n\t/**\n\t * Removes the specified amount of items which match the specified attributes from the given inventory.\n\t * \n\t * @param inv\n\t * @param type\n\t * The item type.\n\t * @param data\n\t * The data value/durability. If -1 is is ignored.\n\t * @param displayName\n\t * The displayName. If null it is ignored.\n\t * @param lore\n\t * The item lore. If null or empty it is ignored.\n\t * @param ignoreNameAndLore\n\t * @param amount\n\t */\n\tpublic static void removeItemsFromInventory(Inventory inv, Material type, short data, String displayName, List<String> lore, int amount) {\n\t\tfor (ItemStack is : inv.getContents()) {\n\t\t\tif (!Utils.isSimilar(is, type, data, displayName, lore)) continue;\n\t\t\tint newamount = is.getAmount() - amount;\n\t\t\tif (newamount > 0) {\n\t\t\t\tis.setAmount(newamount);\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\tinv.remove(is);\n\t\t\t\tamount = -newamount;\n\t\t\t\tif (amount == 0) break;\n\t\t\t}\n\t\t}\n\t}\n\n\t@SuppressWarnings(\"deprecation\")\n\tpublic static void updateInventoryLater(final Player player) {\n\t\tBukkit.getScheduler().runTaskLater(ShopkeepersPlugin.getInstance(), new Runnable() {\n\n\t\t\t@Override\n\t\t\tpublic void run() {\n\t\t\t\tplayer.updateInventory();\n\t\t\t}\n\t\t}, 3L);\n\t}\n\n\tpublic static Integer parseInt(String intString) {\n\t\ttry {\n\t\t\treturn Integer.parseInt(intString);\n\t\t} catch (NumberFormatException e) {\n\t\t\treturn null;\n\t\t}\n\t}\n}" ]
import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import com.nisovin.shopkeepers.Settings; import com.nisovin.shopkeepers.ShopCreationData; import com.nisovin.shopkeepers.ShopType; import com.nisovin.shopkeepers.ShopkeeperCreateException; import com.nisovin.shopkeepers.ShopkeepersAPI; import com.nisovin.shopkeepers.Utils;
package com.nisovin.shopkeepers.shoptypes; public class BookPlayerShopType extends ShopType<BookPlayerShopkeeper> { BookPlayerShopType() { super("book", ShopkeepersAPI.PLAYER_BOOK_PERMISSION); } @Override
public BookPlayerShopkeeper loadShopkeeper(ConfigurationSection config) throws ShopkeeperCreateException {
2
stefanhaustein/nativehtml
shared/src/main/java/org/kobjects/nativehtml/io/HtmlParser.java
[ "public class CssStyleSheet {\n private static final char SELECT_ATTRIBUTE_NAME = 7;\n private static final char SELECT_ATTRIBUTE_VALUE = 8;\n private static final char SELECT_ATTRIBUTE_INCLUDES = 9;\n private static final char SELECT_ATTRIBUTE_DASHMATCH = 10;\n\n private static final float[] HEADING_SIZES = {2, 1.5f, 1.17f, 1.12f, .83f, .67f};\n\n /**\n * A table mapping element names to sub-style sheets for the corresponding\n * selection path.\n */\n public HashMap<String, CssStyleSheet> selectElementName;\n\n /**\n * A table mapping pseudoclass names to sub-style sheets for the corresponding\n * selection path.\n */\n private HashMap<String, CssStyleSheet> selectPseudoclass;\n\n /**\n * A list of attribute names for selectors. Forms attribute selectors together\n * with selectAttributeOperation and selectAttributeValue.\n */\n private ArrayList<String> selectAttributeName;\n\n /**\n * A list of attribute operations for selectors (one of the\n * SELECT_ATTRIBUTE_XX constants). Forms attribute selectors together with\n * selectAttributeName and selectAttributeValue.\n */\n private StringBuilder selectAttributeOperation;\n\n /**\n * A list of Hashtables, mapping attribute values to sub-style sheets for the\n * corresponding selection path. Forms attribute selectors together with\n * selectAttributeName and selectAttributeOperation.\n */\n private ArrayList<HashMap<String, CssStyleSheet>> selectAttributeValue;\n\n /**\n * Reference to child selector selector sub-style sheet.\n */\n private CssStyleSheet selectChild;\n\n /**\n * Reference to descendant selector sub-style sheet.\n */\n private CssStyleSheet selectDescendants;\n\n /**\n * Properties for * rules \n */\n private ArrayList<CssStyleDeclaration> properties;\n\n /**\n * Creates a new style sheet with default rules for HTML.\n */\n public static CssStyleSheet createDefault(int defaultFontSizePx) {\n CssStyleSheet s = new CssStyleSheet();\n // Set default indent with to sufficient space for ordered lists with\n // two digits and the default paragraph spacing to 50% of the font height\n // (so top and bottom spacing adds up to a full line)\n int defaultFontSizePt = defaultFontSizePx * 3 / 4;\n int defaultIndent = defaultFontSizePx * 4 / 2;\n int defaultParagraphSpace = defaultFontSizePx / 2;\n\n if (defaultFontSizePt != 12) {\n s.get(\"*\").set(CssProperty.FONT_SIZE, defaultFontSizePt, CssUnit.PT);\n }\n\n s.get(\":link\")\n .set(CssProperty.COLOR, 0x0ff0000ff, CssUnit.ARGB)\n .setEnum(CssProperty.TEXT_DECORATION, CssEnum.UNDERLINE);\n s.get(\"address\")\n .setEnum(CssProperty.DISPLAY, CssEnum.BLOCK);\n s.get(\"b\").set(CssProperty.FONT_WEIGHT, 700, CssUnit.NUMBER);\n s.get(\"tt\").fontFamily = \"monospace\";\n s.get(\"big\").set(CssProperty.FONT_SIZE, defaultFontSizePt * 4 / 3, CssUnit.PT);\n s.get(\"blockquote\")\n .setEnum(CssProperty.DISPLAY, CssEnum.BLOCK)\n .set(CssProperty.MARGIN_TOP, defaultParagraphSpace, CssUnit.PX)\n .set(CssProperty.MARGIN_RIGHT, defaultIndent, CssUnit.PX)\n .set(CssProperty.MARGIN_BOTTOM, defaultParagraphSpace, CssUnit.PX)\n .set(CssProperty.MARGIN_LEFT, defaultIndent, CssUnit.PX);\n s.get(\"body\")\n .setEnum(CssProperty.DISPLAY, CssEnum.BLOCK)\n .set(CssProperty.PADDING, defaultParagraphSpace / 2, CssUnit.PX, 0);\n s.get(\"button\").\n setEnum(CssProperty.DISPLAY, CssEnum.INLINE_BLOCK).\n set(CssProperty.PADDING, 30, CssUnit.PX);\n s.get(\"center\")\n .setEnum(CssProperty.DISPLAY, CssEnum.BLOCK)\n .set(CssProperty.MARGIN_TOP, defaultParagraphSpace, CssUnit.PX)\n .set(CssProperty.MARGIN_BOTTOM, defaultParagraphSpace, CssUnit.PX)\n .setEnum(CssProperty.TEXT_ALIGN, CssEnum.CENTER);\n s.get(\"dd\")\n .setEnum(CssProperty.DISPLAY, CssEnum.BLOCK)\n .set(CssProperty.MARGIN_LEFT, defaultIndent, CssUnit.PX);\n s.get(\"del\").setEnum(CssProperty.TEXT_DECORATION, CssEnum.LINE_THROUGH);\n s.get(\"dir\")\n .setEnum(CssProperty.DISPLAY, CssEnum.BLOCK)\n .set(CssProperty.MARGIN_TOP, defaultParagraphSpace, CssUnit.PX)\n .set(CssProperty.MARGIN_BOTTOM, defaultParagraphSpace, CssUnit.PX)\n .set(CssProperty.MARGIN_LEFT, defaultIndent, CssUnit.PX)\n .setEnum(CssProperty.LIST_STYLE_TYPE, CssEnum.SQUARE);\n s.get(\"div\").setEnum(CssProperty.DISPLAY, CssEnum.BLOCK);\n s.get(\"dl\").setEnum(CssProperty.DISPLAY, CssEnum.BLOCK);\n s.get(\"dt\").setEnum(CssProperty.DISPLAY, CssEnum.BLOCK);\n s.get(\"form\").setEnum(CssProperty.DISPLAY, CssEnum.BLOCK);\n for (int i = 1; i <= 6; i++) {\n // TODO: Change to em, see http://stackoverflow.com/questions/6140430/what-are-the-most-common-font-sizes-for-h1-h6-tags\n s.get(\"h\" + i)\n .setEnum(CssProperty.DISPLAY, CssEnum.BLOCK)\n .set(CssProperty.FONT_WEIGHT, 700, CssUnit.NUMBER)\n .set(CssProperty.MARGIN_TOP, defaultParagraphSpace, CssUnit.PX)\n .set(CssProperty.MARGIN_BOTTOM, defaultParagraphSpace, CssUnit.PX)\n .set(CssProperty.FONT_SIZE, Math.round(HEADING_SIZES[i - 1] * defaultFontSizePt), CssUnit.PT);\n }\n s.get(\"hr\")\n .setEnum(CssProperty.DISPLAY, CssEnum.BLOCK)\n .setEnum(CssProperty.BORDER_TOP_STYLE, CssEnum.SOLID)\n .set(CssProperty.BORDER_TOP_COLOR, 0x0ff888888, CssUnit.ARGB)\n .set(CssProperty.MARGIN_TOP, defaultParagraphSpace, CssUnit.PX)\n .set(CssProperty.MARGIN_BOTTOM, defaultParagraphSpace, CssUnit.PX);\n CssStyleDeclaration italic = new CssStyleDeclaration().setEnum(CssProperty.FONT_STYLE, CssEnum.ITALIC);\n s.get(\"i\").setEnum(CssProperty.FONT_STYLE, CssEnum.ITALIC);\n s.get(\"em\").setEnum(CssProperty.FONT_STYLE, CssEnum.ITALIC);\n s.get(\"img\").setEnum(CssProperty.DISPLAY, CssEnum.INLINE_BLOCK);\n s.get(\"input\")\n .setEnum(CssProperty.DISPLAY, CssEnum.INLINE_BLOCK);\n s.get(\"ins\").setEnum(CssProperty.TEXT_DECORATION, CssEnum.UNDERLINE);\n s.get(\"li\")\n .setEnum(CssProperty.DISPLAY, CssEnum.LIST_ITEM)\n .set(CssProperty.MARGIN_TOP, defaultParagraphSpace, CssUnit.PX)\n .set(CssProperty.MARGIN_BOTTOM, defaultParagraphSpace, CssUnit.PX);\n s.get(\"marquee\").setEnum(CssProperty.DISPLAY, CssEnum.BLOCK);\n s.get(\"menu\")\n .setEnum(CssProperty.DISPLAY, CssEnum.BLOCK).\n set(CssProperty.MARGIN_TOP, defaultParagraphSpace, CssUnit.PX).\n set(CssProperty.MARGIN_BOTTOM, defaultParagraphSpace, CssUnit.PX).\n set(CssProperty.MARGIN_LEFT, defaultIndent, CssUnit.PX).\n setEnum(CssProperty.LIST_STYLE_TYPE, CssEnum.SQUARE);\n s.get(\"ol\")\n .setEnum(CssProperty.DISPLAY, CssEnum.BLOCK)\n .set(CssProperty.MARGIN_LEFT, defaultIndent, CssUnit.PX)\n .setEnum(CssProperty.LIST_STYLE_TYPE, CssEnum.DECIMAL);\n s.get(\"p\")\n .setEnum(CssProperty.DISPLAY, CssEnum.BLOCK)\n .set(CssProperty.MARGIN_TOP, defaultParagraphSpace, CssUnit.PX)\n .set(CssProperty.MARGIN_BOTTOM, defaultParagraphSpace, CssUnit.PX);\n CssStyleDeclaration pre = new CssStyleDeclaration()\n .setEnum(CssProperty.DISPLAY, CssEnum.BLOCK)\n .setEnum(CssProperty.WHITE_SPACE, CssEnum.PRE)\n .set(CssProperty.MARGIN_TOP, defaultParagraphSpace, CssUnit.PX)\n .set(CssProperty.MARGIN_BOTTOM, defaultParagraphSpace, CssUnit.PX);\n s.get(\"pre\").fontFamily = \"monospace\";\n s.get(\"script\").setEnum(CssProperty.DISPLAY, CssEnum.NONE);\n s.get(\"small\").set(CssProperty.FONT_SIZE, defaultFontSizePt * 3 / 4, CssUnit.PT);\n s.get(\"strike\").setEnum(CssProperty.TEXT_DECORATION, CssEnum.LINE_THROUGH);\n s.get(\"strong\")\n .set(CssProperty.FONT_WEIGHT, CssStyleDeclaration.FONT_WEIGHT_BOLD, CssUnit.NUMBER);\n s.get(\"style\").setEnum(CssProperty.DISPLAY, CssEnum.NONE);\n\n s.get(\"sup\")\n .set(CssProperty.FONT_SIZE, defaultFontSizePt * 3 / 4, CssUnit.PT)\n .setEnum(CssProperty.VERTICAL_ALIGN, CssEnum.SUPER);\n s.get(\"sub\")\n .set(CssProperty.FONT_SIZE, defaultFontSizePt * 3 / 4, CssUnit.PT)\n .setEnum(CssProperty.VERTICAL_ALIGN, CssEnum.SUB);\n\n s.get(\"table\")\n .set(CssProperty.BORDER_SPACING, 2, CssUnit.PX)\n .setEnum(CssProperty.DISPLAY, CssEnum.TABLE)\n .setEnum(CssProperty.CLEAR, CssEnum.BOTH);\n s.get(\"td\")\n .setEnum(CssProperty.DISPLAY, CssEnum.TABLE_CELL)\n .set(CssProperty.PADDING, 10, CssUnit.PX)\n .setEnum(CssProperty.BORDER_STYLE, CssEnum.SOLID)\n .setEnum(CssProperty.TEXT_ALIGN, CssEnum.LEFT);\n s.get(\"th\")\n .setEnum(CssProperty.DISPLAY, CssEnum.TABLE_CELL)\n .set(CssProperty.FONT_WEIGHT, 700, CssUnit.NUMBER)\n .set(CssProperty.PADDING, 10, CssUnit.PX)\n .setEnum(CssProperty.BORDER_STYLE, CssEnum.SOLID)\n .setEnum(CssProperty.TEXT_ALIGN, CssEnum.CENTER);\n s.get(\"tr\").setEnum(CssProperty.DISPLAY, CssEnum.TABLE_ROW);\n s.get(\"u\").setEnum(CssProperty.TEXT_DECORATION, CssEnum.UNDERLINE);\n s.get(\"ul\")\n .setEnum(CssProperty.DISPLAY, CssEnum.BLOCK)\n .set(CssProperty.MARGIN_LEFT, defaultIndent, CssUnit.PX)\n .setEnum(CssProperty.LIST_STYLE_TYPE, CssEnum.SQUARE);\n s.get(\"ul ul\").setEnum(CssProperty.LIST_STYLE_TYPE, CssEnum.CIRCLE);\n s.get(\"ul ul ul\").setEnum(CssProperty.LIST_STYLE_TYPE, CssEnum.DISC);\n return s;\n }\n\n /**\n * Returns true if s matches any type in the given media type array. null, the empty string\n * and all are always matched. s is converted to lower case for the match.\n */\n public static boolean matchesMediaType(String s, String[] mediaTypes) {\n if (s == null) {\n return true;\n }\n s = s.trim().toLowerCase(Locale.US);\n return s.length() == 0 || s.equals(\"all\") || Css.indexOfIgnoreCase(mediaTypes, s) != -1;\n }\n \n \n /**\n * Reads a style sheet from the given css string and merges it into this style sheet.\n * @param css the CSS string to load the style sheet from\n * @param url URL of this style sheet (or the containing document)\n * @param nesting The nesting of this style sheet in other style sheets.\n * \n * @return this\n */\n public CssStyleSheet read(String css, URI url, int[] nesting, String[] mediaTypes, List<Dependency> dependencies) {\n CssTokenizer ct = new CssTokenizer(url, css);\n int position = 0;\n boolean inMedia = false;\n while (ct.ttype != CssTokenizer.TT_EOF) {\n if (ct.ttype == CssTokenizer.TT_ATKEYWORD) {\n if (\"media\".equals(ct.sval)) {\n ct.nextToken(false);\n inMedia = false;\n do {\n if(ct.ttype != ',') {\n inMedia |= matchesMediaType(ct.sval, mediaTypes);\n }\n ct.nextToken(false);\n } while (ct.ttype != '{' && ct.ttype != CssTokenizer.TT_EOF);\n ct.nextToken(false);\n if (!inMedia) {\n int level = 1;\n do {\n switch (ct.ttype) {\n case '}': \n level--;\n break;\n case '{':\n level++;\n break;\n case CssTokenizer.TT_EOF:\n return this;\n }\n ct.nextToken(false);\n } while (level > 0);\n }\n } else if (\"import\".equals(ct.sval)){\n ct.nextToken(false);\n String importUrl = ct.sval;\n ct.nextToken(false);\n StringBuilder media = new StringBuilder();\n while (ct.ttype != ';' && ct.ttype != CssTokenizer.TT_EOF) {\n media.append(ct.sval);\n ct.nextToken(false);\n }\n if (dependencies != null && matchesMediaType(media.toString(), mediaTypes)) {\n int [] dependencyNesting = new int[nesting.length + 1];\n System.arraycopy(nesting, 0, dependencyNesting, 0, nesting.length);\n dependencyNesting[nesting.length] = position;\n dependencies.add(new Dependency(url.resolve(importUrl), dependencyNesting));\n }\n ct.nextToken(false);\n position++;\n } else {\n ct.debug(\"unsupported @\" + ct.sval);\n ct.nextToken(false);\n }\n } else if (ct.ttype == '}') {\n if (!inMedia) {\n ct.debug(\"unexpected }\");\n }\n inMedia = false;\n ct.nextToken(false);\n } else {\n // no @keyword or } -> regular selector\n ArrayList<CssStyleDeclaration> targets = new ArrayList<CssStyleDeclaration>();\n targets.add(parseSelector(ct));\n while (ct.ttype == ',') {\n ct.nextToken(false);\n targets.add(parseSelector(ct));\n }\n\n CssStyleDeclaration style = new CssStyleDeclaration();\n if (ct.ttype == '{') {\n ct.nextToken(false);\n style.read(ct);\n ct.assertTokenType('}');\n } else {\n ct.debug(\"{ expected\");\n }\n\n for (int i = 0; i < targets.size(); i++) {\n CssStyleDeclaration target = targets.get(i);\n if (target == null) {\n continue;\n }\n target.position = position;\n target.nesting = nesting;\n target.setFrom(style);\n }\n ct.nextToken(false);\n position++;\n }\n }\n return this;\n }\n\n /**\n * Parse a selector. The tokenizer must be at the first token of the selector.\n * When returning, the current token will be ',' or '{'.\n * <p>\n * This method brings selector paths into the tree form described in the class\n * documentation.\n * \n * @param ct the css tokenizer\n * @return the node at the end of the tree path denoted by this selector,\n * where the corresponding CSS properties will be stored\n */\n private CssStyleDeclaration parseSelector(CssTokenizer ct) {\n\n boolean error = false;\n \n int specificity = 0;\n CssStyleSheet result = this;\n\n loop : while (true) {\n switch (ct.ttype) {\n case CssTokenizer.TT_IDENT: {\n if (result.selectElementName == null) {\n result.selectElementName = new HashMap<String, CssStyleSheet>();\n }\n result = descend(result.selectElementName, \n Css.identifierToLowerCase(ct.sval));\n specificity += Css.SPECIFICITY_D;\n ct.nextToken(true);\n break;\n }\n case '*': {\n // no need to dom anything...\n ct.nextToken(true);\n continue;\n }\n case '[': {\n ct.nextToken(false);\n String name = Css.identifierToLowerCase(ct.sval);\n ct.nextToken(false);\n char type;\n String value = \"\";\n \n if (ct.ttype == ']') {\n type = SELECT_ATTRIBUTE_NAME;\n } else {\n switch (ct.ttype) {\n case CssTokenizer.TT_INCLUDES:\n type = SELECT_ATTRIBUTE_INCLUDES;\n break;\n case '=':\n type = SELECT_ATTRIBUTE_VALUE;\n break;\n case CssTokenizer.TT_DASHMATCH:\n type = SELECT_ATTRIBUTE_DASHMATCH;\n break;\n default:\n error = true;\n break loop;\n }\n ct.nextToken(false);\n if (ct.ttype != CssTokenizer.TT_STRING) {\n error = true;\n break loop;\n }\n value = ct.sval;\n ct.nextToken(false);\n ct.assertTokenType(']');\n specificity += Css.SPECIFICITY_C;\n }\n result = result.createAttributeSelector(type, name, value);\n ct.nextToken(true);\n break;\n }\n case '.':\n ct.nextToken(false);\n error = ct.ttype != CssTokenizer.TT_IDENT;\n result = result.createAttributeSelector(SELECT_ATTRIBUTE_INCLUDES, \"class\", ct.sval);\n specificity += Css.SPECIFICITY_C;\n ct.nextToken(true);\n break;\n\n case CssTokenizer.TT_HASH:\n result = result.createAttributeSelector(SELECT_ATTRIBUTE_VALUE, \"id\", ct.sval);\n specificity += Css.SPECIFICITY_B;\n ct.nextToken(true);\n break;\n\n case ':': \n ct.nextToken(false);\n error = ct.ttype != CssTokenizer.TT_IDENT;\n if (result.selectPseudoclass == null) {\n result.selectPseudoclass = new HashMap<String, CssStyleSheet>();\n }\n result = descend(result.selectPseudoclass, ct.sval);\n specificity += Css.SPECIFICITY_C;\n ct.nextToken(true);\n break;\n\n case CssTokenizer.TT_S:\n ct.nextToken(false);\n if (ct.ttype == '{' || ct.ttype == ',' || ct.ttype == -1) {\n break loop;\n }\n if (ct.ttype == '>') {\n if (result.selectChild == null) {\n result.selectChild = new CssStyleSheet();\n }\n result = result.selectChild;\n ct.nextToken(false);\n } else {\n if (result.selectDescendants == null) {\n result.selectDescendants = new CssStyleSheet();\n }\n result = result.selectDescendants;\n }\n break;\n\n case '>':\n if (result.selectChild == null) {\n result.selectChild = new CssStyleSheet();\n }\n result = result.selectChild;\n ct.nextToken(false);\n break;\n\n default: // unknown\n break loop;\n }\n }\n\n // state: behind all recognized tokens -- check for unexpected stuff\n if (error || (ct.ttype != ',' && ct.ttype != '{')) {\n ct.debug(\"Unrecognized selector\");\n // parse to '{', ',' or TT_EOF to get to a well-defined state\n while (ct.ttype != ',' && ct.ttype != CssTokenizer.TT_EOF\n && ct.ttype != '{') {\n ct.nextToken(false);\n }\n return null;\n }\n\n CssStyleDeclaration style = new CssStyleDeclaration();\n style.specificity = specificity;\n if (result.properties == null) {\n result.properties = new ArrayList<CssStyleDeclaration>();\n }\n result.properties.add(style);\n \n return style;\n }\n\n private CssStyleSheet createAttributeSelector(char type, String name, String value) {\n int index = -1;\n if (selectAttributeOperation == null) {\n selectAttributeOperation = new StringBuilder();\n selectAttributeName = new ArrayList<String>();\n selectAttributeValue = new ArrayList<HashMap<String, CssStyleSheet>>();\n } else {\n for (int j = 0; j < selectAttributeOperation.length(); j++) {\n if (selectAttributeOperation.charAt(j) == type\n && selectAttributeName.get(j).equals(name)) {\n index = j;\n }\n }\n }\n\n if (index == -1) {\n index = selectAttributeOperation.length();\n selectAttributeOperation.append(type);\n selectAttributeName.add(name);\n selectAttributeValue.add(new HashMap<String, CssStyleSheet>());\n }\n return descend(selectAttributeValue.get(index), value);\n }\n\n /**\n * Returns the style sheet denoted by the given key from the hashtable. If not\n * yet existing, a corresponding entry is created.\n */\n private static CssStyleSheet descend(Map<String, CssStyleSheet> h, String key) {\n CssStyleSheet s = h.get(key);\n if (s == null) {\n s = new CssStyleSheet();\n h.put(key, s);\n }\n return s;\n }\n\n /**\n * Helper method for collectStyles(). Determines whether the given key is \n * in the given map. If so, the style search continues in the corresponding \n * style sheet.\n * \n * @param element the element under consideration (may be the target element\n * or any parent)\n * @param map corresponding sub style sheet map\n * @param key element name or attribute value\n * @param queue queue of matching rules to be processed further\n */\n private static void collectStyles(Element element, Map<String, CssStyleSheet> map, String key,\n List<CssStyleDeclaration> queue, List<CssStyleSheet> children, List<CssStyleSheet> descendants) {\n if (key == null || map == null) {\n return;\n }\n CssStyleSheet sh = map.get(key);\n if (sh != null) {\n sh.collectStyles(element, queue, children, descendants);\n }\n }\n\n /**\n * Performs a depth first search of all matching selectors and enqueues the\n * corresponding style information.\n */\n public void collectStyles(Element element, List<CssStyleDeclaration> queue,\n List<CssStyleSheet> children, List<CssStyleSheet> descendants) {\n \n if (properties != null) {\n // enqueue the style at the current node according to its specificity\n\n for (int i = 0; i < properties.size(); i++) {\n CssStyleDeclaration p = properties.get(i);\n int index = queue.size();\n while (index > 0) {\n CssStyleDeclaration s = queue.get(index - 1);\n if (s.compareSpecificity(p) < 0) {\n break;\n }\n if (s == p) {\n index = -1;\n break;\n }\n index--;\n }\n if (index != -1) {\n queue.add(index, p);\n }\n }\n }\n \n if (selectAttributeOperation != null) {\n for (int i = 0; i < selectAttributeOperation.length(); i++) {\n int type = selectAttributeOperation.charAt(i);\n String name = selectAttributeName.get(i);\n String value = element.getAttribute(name);\n if (value == null) {\n continue;\n }\n HashMap<String, CssStyleSheet> valueMap = selectAttributeValue.get(i);\n if (type == SELECT_ATTRIBUTE_NAME) {\n collectStyles(element, valueMap, \"\", queue, children, descendants);\n } else if (type == SELECT_ATTRIBUTE_VALUE) {\n collectStyles(element, valueMap, value, queue, children, descendants);\n } else {\n String[] values = Css.split(value,\n type == SELECT_ATTRIBUTE_INCLUDES ? ' ' : ',');\n for (int j = 0; j < values.length; j++) {\n collectStyles(element, valueMap, values[j], queue, children, descendants);\n }\n }\n }\n }\n\n if (selectElementName != null) {\n collectStyles(element, selectElementName, element.getLocalName(), queue, children, descendants);\n }\n\n if (selectChild != null) {\n children.add(selectChild);\n }\n\n/* if (selectPseudoclass != null && element.isLink()) {\n collectStyles(element, selectPseudoclass, \"link\", queue, children, descendants);\n }*/\n \n if (selectDescendants != null) {\n descendants.add(selectDescendants);\n }\n }\n\n /**\n * Returns the style declaration for the given selector for programmatic modification.\n * If the specificity is >= 0, Css.SPECIFICITY_IMPORTANT is subtracted to make sure system\n * styles don't override user styles.\n */\n public CssStyleDeclaration get(String selector) {\n CssTokenizer ct = new CssTokenizer(null, selector + \"{\");\n CssStyleDeclaration result = parseSelector(ct);\n if (result.specificity >= 0) {\n result.specificity -= Css.SPECIFICITY_IMPORTANT;\n }\n return result;\n }\n\n public String toString() {\n StringBuilder sb = new StringBuilder();\n toString(\"\", sb);\n return sb.toString();\n }\n\n public void toString(String current, StringBuilder sb) {\n if (properties != null) {\n sb.append(current.length() == 0 ? \"*\" : current);\n sb.append(\" {\");\n for (int i = 0; i < properties.size(); i++) {\n properties.get(i).toString(\"\", sb);\n }\n sb.append(\"}\\n\");\n }\n\n if (selectElementName != null) {\n for (Map.Entry<String, CssStyleSheet> entry: selectElementName.entrySet()) {\n entry.getValue().toString(entry.getKey() + current, sb);\n }\n }\n\n if (selectAttributeOperation != null) {\n for (int i = 0; i < selectAttributeOperation.length(); i++) {\n int type = selectAttributeOperation.charAt(i);\n StringBuilder p = new StringBuilder(current);\n p.append('[');\n p.append(selectAttributeName.get(i));\n\n if (type == SELECT_ATTRIBUTE_NAME) {\n p.append(']');\n selectAttributeValue.get(i).get(\"\").toString(p.toString(), sb);\n } else {\n switch (type) {\n case SELECT_ATTRIBUTE_VALUE:\n p.append('=');\n break;\n case SELECT_ATTRIBUTE_INCLUDES:\n p.append(\"~=\");\n break;\n case SELECT_ATTRIBUTE_DASHMATCH:\n p.append(\"|=\");\n break;\n }\n HashMap<String, CssStyleSheet> valueMap = selectAttributeValue.get(i);\n for (Map.Entry<String, CssStyleSheet> e : valueMap.entrySet()) {\n e.getValue().toString(p.toString() + '\"' + e.getKey() + \"\\\"]\", sb);\n }\n }\n }\n }\n\n if (selectDescendants != null) {\n selectDescendants.toString(current + \" \", sb);\n }\n\n if (selectChild != null) {\n selectChild.toString(current + \" > \", sb);\n }\n }\n\n public void apply(Element element, URI baseUri) {\n ArrayList<CssStyleSheet> applyAnywhere = new ArrayList<>();\n applyAnywhere.add(this);\n CssStyleSheet.apply(element, baseUri, null, new ArrayList<CssStyleSheet>(), applyAnywhere);\n \n }\n\n /**\n * Applies the given style sheet to this element and recursively to all child\n * elements, setting the computedStyle field to the computed CSS values.\n * <p>\n * Technically, it builds a queue of applicable styles and then applies them \n * in the order of ascending specificity. After the style sheet has been \n * applied, the inheritance rules and finally the style attribute are taken \n * into account.\n */\n private static void apply(Element element, URI baseUri, CssStyleDeclaration inherit,\n List<CssStyleSheet> applyHere, List<CssStyleSheet> applyAnywhere) {\n CssStyleDeclaration style = new CssStyleDeclaration();\n if (inherit != null) {\n style.inherit(inherit);\n }\n\n ArrayList<CssStyleDeclaration> queue = new ArrayList<>();\n ArrayList<CssStyleSheet> childStyles = new ArrayList<>();\n ArrayList<CssStyleSheet> descendantStyles = new ArrayList<>();\n \n int size = applyHere.size();\n for (int i = 0; i < size; i++) {\n CssStyleSheet styleSheet = applyHere.get(i);\n styleSheet.collectStyles(element, queue, childStyles, descendantStyles);\n }\n size = applyAnywhere.size();\n for (int i = 0; i < size; i++) {\n CssStyleSheet styleSheet = applyAnywhere.get(i);\n descendantStyles.add(styleSheet);\n styleSheet.collectStyles(element, queue, childStyles, descendantStyles);\n }\n \n for (int i = 0; i < queue.size(); i++) {\n style.setFrom((queue.get(i)));\n }\n\n style.setFrom(element.getStyle());\n \n\n element.setComputedStyle(style);\n // recurse....\n \n HtmlCollection children = element.getChildren();\n for (int i = 0; i < children.getLength(); i++) {\n apply(children.item(i), baseUri, style, childStyles, descendantStyles);\n }\n }\n\n /**\n * Helper class to keep track of and resolve imports.\n */\n public static class Dependency {\n private final URI url;\n private final int[] nesting;\n\n Dependency(URI url, int[] nesting) {\n this.url = url;\n this.nesting = nesting;\n }\n\n /** \n * Returns the URL of the nested style sheet to load.\n */\n public URI getUrl() {\n return url;\n }\n\n /**\n * Returns the nesting positions of the style sheet to load.\n * Used for specificity calculation.\n */\n public int[] getNestingPositions() {\n return nesting;\n }\n }\n}", "public class Document {\n private static final LinkedHashMap<String, ElementType> ELEMENT_TYPES = new LinkedHashMap<>();\n private static final LinkedHashMap<String, ContentType> CONTENT_TYPES = new LinkedHashMap<>();\n \n static void add(String name, ElementType elementType, ContentType contentType) {\n \tELEMENT_TYPES.put(name, elementType);\n \tCONTENT_TYPES.put(name, contentType);\n }\n \n static {\n add(\"a\", ElementType.FORMATTED_TEXT, ContentType.FORMATTED_TEXT);\n add(\"b\", ElementType.FORMATTED_TEXT, ContentType.FORMATTED_TEXT);\n add(\"big\", ElementType.FORMATTED_TEXT, ContentType.FORMATTED_TEXT);\n add(\"br\", ElementType.FORMATTED_TEXT, ContentType.EMPTY);\n add(\"del\", ElementType.FORMATTED_TEXT, ContentType.FORMATTED_TEXT);\n add(\"em\", ElementType.FORMATTED_TEXT, ContentType.FORMATTED_TEXT);\n add(\"font\", ElementType.FORMATTED_TEXT, ContentType.FORMATTED_TEXT);\n add(\"head\", ElementType.DATA, ContentType.DATA_ELEMENTS);\n add(\"html\", ElementType.SKIP, ContentType.COMPONENTS); // head gets special handling\n add(\"i\", ElementType.FORMATTED_TEXT, ContentType.FORMATTED_TEXT);\n add(\"img\", ElementType.INLINE_IMAGE, ContentType.EMPTY); // Might be an image (=LEAF_COMPONENT), too; will get adjusted\n add(\"input\", ElementType.COMPONENT, ContentType.EMPTY);\n add(\"ins\", ElementType.FORMATTED_TEXT, ContentType.FORMATTED_TEXT);\n add(\"link\", ElementType.DATA, ContentType.EMPTY);\n add(\"meta\", ElementType.DATA, ContentType.EMPTY);\n add(\"option\", ElementType.DATA, ContentType.TEXT_ONLY);\n add(\"script\", ElementType.DATA, ContentType.TEXT_ONLY);\n add(\"select\", ElementType.COMPONENT, ContentType.DATA_ELEMENTS);\n add(\"small\", ElementType.FORMATTED_TEXT, ContentType.FORMATTED_TEXT);\n add(\"span\", ElementType.FORMATTED_TEXT, ContentType.FORMATTED_TEXT);\n add(\"strike\", ElementType.FORMATTED_TEXT, ContentType.FORMATTED_TEXT);\n add(\"strong\", ElementType.FORMATTED_TEXT, ContentType.FORMATTED_TEXT);\n add(\"style\", ElementType.DATA, ContentType.TEXT_ONLY);\n add(\"sub\", ElementType.FORMATTED_TEXT, ContentType.FORMATTED_TEXT);\n add(\"sup\", ElementType.FORMATTED_TEXT, ContentType.FORMATTED_TEXT);\n add(\"tbody\", ElementType.SKIP, ContentType.COMPONENTS);\n add(\"text-component\", ElementType.COMPONENT, ContentType.FORMATTED_TEXT);\n add(\"thead\", ElementType.SKIP, ContentType.COMPONENTS);\n add(\"title\", ElementType.DATA, ContentType.TEXT_ONLY);\n add(\"tt\", ElementType.FORMATTED_TEXT, ContentType.FORMATTED_TEXT);\n add(\"u\", ElementType.FORMATTED_TEXT, ContentType.FORMATTED_TEXT);\n }\n\n public static ElementType getElementType(String name) {\n ElementType result = ELEMENT_TYPES.get(name);\n return result == null ? ElementType.COMPONENT : result;\n }\n\n private static ContentType getContentType(String name) {\n ContentType result = CONTENT_TYPES.get(name);\n return result == null ? ContentType.COMPONENTS : result;\n }\n\n\tprivate final Platform platform;\n private final WebSettings webSettings;\n private RequestHandler requestHandler;\n private URI url;\n private Element head;\n private Element body;\n\n\tpublic Document(Platform elementFactory, RequestHandler requestHandler, WebSettings webSettings, URI uri) {\n\t\tthis.platform = elementFactory;\n\t\tthis.requestHandler = requestHandler;\n\t\tif (webSettings == null) {\n\t\t this.webSettings = new WebSettings();\n\t\t this.webSettings.setScale(platform.getPixelPerDp());\n } else {\n this.webSettings = webSettings;\n }\n\t\tthis.url = uri;\n\t}\n \n public Element createElement(String name) {\n \tElementType elementType = getElementType(name);\n Element result = platform.createElement(this, elementType, name);\n \tContentType contentType = getContentType(name);\n return result == null ? new ElementImpl(this, name, elementType, contentType) : result;\n }\n\n\n\tpublic URI getUrl() {\n\t\treturn url;\n\t}\n\n\tpublic URI resolveUrl(String url) {\n\t if (this.url.isOpaque()) {\n try {\n URI uri = new URI(url);\n if (uri.isAbsolute()) {\n return uri;\n }\n String s = this.url.toString();\n int cut;\n if (url.startsWith(\"#\")) {\n cut = s.indexOf('#');\n if (cut == -1) {\n cut = s.length();\n }\n } else {\n cut = s.lastIndexOf('/') + 1;\n }\n return new URI(s.substring(0, cut) + url);\n } catch (URISyntaxException e) {\n throw new RuntimeException(e);\n }\n }\n return this.url.resolve(url);\n }\n\n public RequestHandler getRequestHandler() {\n return requestHandler;\n }\n\n public void setHead(Element head) {\n this.head = head;\n }\n\n public void setBody(Element body) {\n this.body = body;\n }\n \n public Element getBody() {\n return body;\n }\n\n public Element getHead() {\n return head;\n }\n\n public Platform getPlatform() {\n return platform;\n }\n \n public WebSettings getSettings() {\n return webSettings;\n }\n}", "public interface Element {\n String getLocalName();\n void setAttribute(String name, String value);\n String getAttribute(String name);\n\n Element getParentElement();\n void setComputedStyle(CssStyleDeclaration style);\n \n /**\n * Used internally\n */\n ElementType getElementType();\n ContentType getElementContentType();\n\n /**\n * Used internally in insertBefore.\n */\n void setParentElement(Element parent);\n\n HtmlCollection getChildren();\n\n CssStyleDeclaration getStyle();\n CssStyleDeclaration getComputedStyle();\n\n String getTextContent();\n\n void setTextContent(String textContent);\n\n void insertBefore(Element newChild, Element referenceChild);\n Document getOwnerDocument();\n \n}", "public interface Platform {\n\tElement createElement(Document document, ElementType elementType, String name);\n\tvoid openInBrowser(URI url);\n\tInputStream openInputStream(URI url) throws IOException;\n float getPixelPerDp();\n}", "public enum ElementType {\n COMPONENT, DATA, FORMATTED_TEXT, INLINE_IMAGE, \n SKIP // No \"real\" element types\n}", "public class WebSettings {\n float scale = 1;\n public float getScale() {\n return scale;\n }\n public void setScale(float scale) {\n this.scale = scale;\n }\n}" ]
import org.kobjects.nativehtml.css.CssStyleSheet; import org.kobjects.nativehtml.dom.Document; import org.kobjects.nativehtml.dom.Element; import org.kobjects.nativehtml.dom.Platform; import org.kobjects.nativehtml.dom.ElementType; import org.kobjects.nativehtml.layout.WebSettings; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.Reader; import java.net.URI;
package org.kobjects.nativehtml.io; /** * Uses a HtmlParser to generate a widget tree that corresponds to the HTML code. * * Can be re-used, but is not thread safe. */ public class HtmlParser { private final HtmlNormalizer input; private final Platform elementFactory; private CssStyleSheet styleSheet; private Document document; private WebSettings webSettings; private RequestHandler requestHandler; public HtmlParser(Platform elementFactory, RequestHandler requestHandler, WebSettings webSettings) { this.elementFactory = elementFactory; this.requestHandler = requestHandler; this.webSettings = webSettings; try { this.input = new HtmlNormalizer(); } catch (XmlPullParserException e) { throw new RuntimeException(e); } } /** * Parses html from the given reader and returns the body or root element. */
public Element parse(Reader reader, URI baseUri) {
2
kcthota/JSONQuery
src/test/java/com/kcthota/query/FilterTest.java
[ "public static IsNullExpression Null(String property) {\n\treturn new IsNullExpression(val(property));\n}", "public static EqExpression eq(String property, String value) {\n\treturn eq(val(property), TextNode.valueOf(value));\n}", "public static GtExpression gt(String property, Integer value) {\n\treturn new GtExpression(val(property), IntNode.valueOf(value));\n}", "public static LeExpression le(String property, Integer value) {\n\treturn new LeExpression(val(property), IntNode.valueOf(value));\n}", "public static NotExpression not(ComparisonExpression expr) {\n\treturn new NotExpression(expr);\n}", "public static OrExpression or(ComparisonExpression...expressions) {\n\treturn new OrExpression(expressions);\n}", "public class Query extends AbstractQuery {\n\n\tprivate Integer top;\n\n\tprivate Integer skip;\n\n\tpublic Query(JsonNode node) {\n\t\tsuper(node);\n\t}\n\n\t/**\n\t * Number of objects in an ArrayNode to be returned from top\n\t * @param value\n\t * @return\n\t */\n\tpublic Query top(Integer value) {\n\t\tsetTop(value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Number of objects in an Arraynode to be skipped from top\n\t * @param value\n\t * @return\n\t */\n\tpublic Query skip(Integer value) {\n\t\tsetSkip(value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Verifies if the passed expression is true for the JsonNode\n\t * \n\t * @param expr\n\t * Comparison expression to be evaluated\n\t * @return returns if the expression is true for the JsonNode\n\t */\n\tpublic boolean is(ComparisonExpression expr) {\n\t\ttry {\n\t\t\tif (expr != null) {\n\t\t\t\treturn expr.evaluate(node);\n\t\t\t}\n\t\t} catch (MissingNodeException e) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Gets the value for the property from the JsonNode\n\t * \n\t * @param property\n\t * @return\n\t */\n\tpublic JsonNode value(String property) {\n\t\treturn value(new ValueExpression(property));\n\t}\n\n\t/**\n\t * Gets the value as per expression set from the JsonNode\n\t * \n\t * @param expression\n\t * Value expression to be evaluated\n\t * @return Returns the value for the passed expression\n\t */\n\tpublic JsonNode value(ValueExpression expression) {\n\t\treturn expression.evaluate(node);\n\t}\n\n\t/**\n\t * Returns the integer value as per expression set\n\t * \n\t * @param expression\n\t * IntegerValueExpression to be evaluated\n\t * @return Returns the integer value of the result of expression evaluated\n\t */\n\tpublic int value(IntegerValueExpression expression) {\n\t\treturn expression.value(node);\n\t}\n\t\n\t/**\n\t * Returns the long value as per expression set\n\t * \n\t * @param expression\n\t * LongValueExpression to be evaluated\n\t * @return Returns the long value of the result of expression evaluated\n\t */\n\tpublic long value(LongValueExpression expression) {\n\t\treturn expression.value(node);\n\t}\n\t\n\t/**\n\t * Returns the double value as per expression set\n\t * @param expression DoubleValueExpression to be evaluated\n\t * @return Returns the double value of the result of expression evaluated\n\t */\n\tpublic double value(DoubleValueExpression expression) {\n\t\treturn expression.value(node);\n\t}\n\n\t/**\n\t * Checks if property exist in the JsonNode\n\t * \n\t * @param property\n\t * JSON property\n\t * @return Returns the value for the passed property\n\t */\n\tpublic boolean isExist(String property) {\n\t\ttry {\n\t\t\tnew ValueExpression(property).evaluate(node);\n\t\t} catch (MissingNodeException e) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * Allows filtering values in a ArrayNode as per passed ComparisonExpression\n\t * \n\t * @param expression\n\t * @return\n\t */\n\tpublic ArrayNode filter(ComparisonExpression expression) {\n\t\t\n\t\tArrayNode result = new ObjectMapper().createArrayNode();\n\t\tif (node.isArray()) {\n\t\t\tIterator<JsonNode> iterator = node.iterator();\n\t\t\tint validObjectsCount = 0;\n\t\t\tint topCount=0;\n\t\t\twhile (iterator.hasNext()) {\n\t\t\t\tJsonNode curNode = iterator.next();\n\t\t\t\tif (expression==null || (expression!=null && new Query(curNode).is(expression))) {\n\t\t\t\t\tvalidObjectsCount++;\n\t\t\t\t\tif (this.skip != null && this.skip.intValue() > 0 && this.skip.intValue() >= validObjectsCount) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this.top != null && topCount >= this.top.intValue()) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tresult.add(curNode);\n\t\t\t\t\ttopCount++;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new UnsupportedExprException(\"Filters are only supported on ArrayNode objects\");\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Allows applying filter on a property value, which is ArrayNode, as per\n\t * passed ComparisonExpression\n\t * \n\t * @param property\n\t * @param expression\n\t * @return\n\t */\n\tpublic ArrayNode filter(String property, ComparisonExpression expression) {\n\t\tJsonNode propValueNode = this.value(property);\n\t\treturn Query.q(propValueNode).top(this.getTop()).skip(this.getSkip()).filter(expression);\n\t}\n\n\t/**\n\t * Spins up a new instance of Query\n\t * \n\t * @param node\n\t * @return\n\t */\n\tpublic static Query q(JsonNode node) {\n\t\treturn new Query(node);\n\t}\n\n\tpublic Integer getTop() {\n\t\treturn top;\n\t}\n\n\tpublic void setTop(Integer top) {\n\t\tthis.top = top;\n\t}\n\n\tpublic Integer getSkip() {\n\t\treturn skip;\n\t}\n\n\tpublic void setSkip(Integer skip) {\n\t\tthis.skip = skip;\n\t}\n\n}", "@SuppressWarnings(\"serial\")\npublic class UnsupportedExprException extends RuntimeException {\n\n\tpublic UnsupportedExprException(String message) {\n\t\tsuper(message);\n\t}\n\n}" ]
import static com.kcthota.JSONQuery.expressions.Expr.Null; import static com.kcthota.JSONQuery.expressions.Expr.eq; import static com.kcthota.JSONQuery.expressions.Expr.gt; import static com.kcthota.JSONQuery.expressions.Expr.le; import static com.kcthota.JSONQuery.expressions.Expr.not; import static com.kcthota.JSONQuery.expressions.Expr.or; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import org.junit.BeforeClass; import org.junit.Test; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.kcthota.JSONQuery.Query; import com.kcthota.JSONQuery.exceptions.UnsupportedExprException;
/** * */ package com.kcthota.query; /** * @author Krishna Chaitanya Thota * Apr 28, 2015 9:23:50 PM */ public class FilterTest { private static JsonNode node; @BeforeClass public static void setup() { ObjectNode node1 = new ObjectMapper().createObjectNode(); node1.putObject("name").put("firstName", "John").put("lastName", "Doe"); node1.put("age", 25); node1.putNull("address"); node1.put("state", "CA"); ObjectNode node2 = new ObjectMapper().createObjectNode(); node2.putObject("name").put("firstName", "Jane").put("lastName", "Doe"); node2.put("age", 18); node2.put("address", "1st St."); node2.put("state", "CA"); ObjectNode node3 = new ObjectMapper().createObjectNode(); node3.putObject("name").put("firstName", "Jill").put("lastName", "Doe"); node3.put("age", 30); node3.put("address", "2nd St."); node3.put("state", "FL"); node = new ObjectMapper().createArrayNode().add(node1).add(node2).add(node3); } @Test public void testStringFilter() { ArrayNode node = new ObjectMapper().createArrayNode().add("John").add("Kevin").add("Joe").add("Jeff"); Query q=new Query(node); ArrayNode result = q.filter(eq((String)null, "John")); assertThat(result.size()).isEqualTo(1); assertThat(Query.q(result).value("0").textValue()).isEqualTo("John"); } @Test public void testIntegerFilter() { ArrayNode node = new ObjectMapper().createArrayNode().add(1).add(2).add(3).add(4); Query q=new Query(node); ArrayNode result = q.filter(gt((String)null, 2)); assertThat(result.size()).isEqualTo(2); assertThat(Query.q(result).value("0").intValue()).isEqualTo(3); assertThat(Query.q(result).value("1").intValue()).isEqualTo(4); } @Test public void testFloatFilter() { ArrayNode node = new ObjectMapper().createArrayNode().add(1f).add(2.56f).add(3.01f).add(1.4f); Query q=new Query(node); ArrayNode result = q.filter(gt((String)null, 2f)); assertThat(result.size()).isEqualTo(2); assertThat(Query.q(result).value("0").floatValue()).isEqualTo(2.56f); assertThat(Query.q(result).value("1").floatValue()).isEqualTo(3.01f); } @Test public void testJSONNodesFilter1() { Query q=new Query(FilterTest.node);
ArrayNode result = q.filter(le("age", 18));
3
google/safe-html-types
types/src/test/java/com/google/common/html/types/UncheckedConversionsTest.java
[ "public static SafeHtml safeHtmlFromStringKnownToSatisfyTypeContract(String html) {\n return new SafeHtml(html);\n}", "public static SafeScript safeScriptFromStringKnownToSatisfyTypeContract(String script) {\n return new SafeScript(script);\n}", "public static SafeStyle safeStyleFromStringKnownToSatisfyTypeContract(String style) {\n return new SafeStyle(style);\n}", "public static SafeStyleSheet safeStyleSheetFromStringKnownToSatisfyTypeContract(\n String stylesheet) {\n return new SafeStyleSheet(stylesheet);\n}", "public static SafeUrl safeUrlFromStringKnownToSatisfyTypeContract(String url) {\n return new SafeUrl(url);\n}", "public static TrustedResourceUrl trustedResourceUrlFromStringKnownToSatisfyTypeContract(\n String url) {\n return new TrustedResourceUrl(url);\n}", "public static void assertClassIsNotExportable(Class<?> klass) {\n for (Class<?> annotation : EXPORTABLE_CLASS_ANNOTATIONS) {\n if (klass.isAnnotationPresent(annotation.asSubclass(Annotation.class))) {\n throw new AssertionError(\n \"Class should not have annotation \" + annotation.getName()\n + \", @CompileTimeConstant can be bypassed: \" + klass);\n }\n }\n}" ]
import static com.google.common.html.types.UncheckedConversions.safeHtmlFromStringKnownToSatisfyTypeContract; import static com.google.common.html.types.UncheckedConversions.safeScriptFromStringKnownToSatisfyTypeContract; import static com.google.common.html.types.UncheckedConversions.safeStyleFromStringKnownToSatisfyTypeContract; import static com.google.common.html.types.UncheckedConversions.safeStyleSheetFromStringKnownToSatisfyTypeContract; import static com.google.common.html.types.UncheckedConversions.safeUrlFromStringKnownToSatisfyTypeContract; import static com.google.common.html.types.UncheckedConversions.trustedResourceUrlFromStringKnownToSatisfyTypeContract; import static com.google.common.html.types.testing.assertions.Assertions.assertClassIsNotExportable; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import junit.framework.TestCase;
/* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.html.types; /** * Unit tests for {@link UncheckedConversions}. */ @GwtCompatible public class UncheckedConversionsTest extends TestCase { @GwtIncompatible("Assertions.assertClassIsNotExportable") public void testNotExportable() { assertClassIsNotExportable(UncheckedConversions.class); } public void testSafeHtmlFromStringKnownToSatisfyTypeContract() { String html = "<script>this is not valid SafeHtml"; assertEquals( html, safeHtmlFromStringKnownToSatisfyTypeContract(html).getSafeHtmlString()); } public void testSafeScriptFromStringKnownToSatisfyTypeContract() { String script = "invalid SafeScript"; assertEquals( script, safeScriptFromStringKnownToSatisfyTypeContract(script).getSafeScriptString()); } public void testSafeStyleFromStringKnownToSatisfyTypeContract() { String style = "width:expression(this is not valid SafeStyle"; assertEquals( style, safeStyleFromStringKnownToSatisfyTypeContract(style).getSafeStyleString()); } public void testSafeStyleSheetFromStringKnownToSatisfyTypeContract() { String styleSheet = "selector { not a valid SafeStyleSheet"; assertEquals( styleSheet,
safeStyleSheetFromStringKnownToSatisfyTypeContract(styleSheet).getSafeStyleSheetString());
3
gentoku/pinnacle-api-client
src/examples/PlaceBet.java
[ "public class Parameter extends ParameterCore {\n\n\t/**\n\t * Constructor.\n\t */\n\tprivate Parameter () {\n\t\tsuper();\n\t}\n\t\n\t/**\n\t * Factory\n\t * \n\t * @return\n\t */\n\tpublic static Parameter newInstance() {\n\t\treturn new Parameter();\n\t}\n\n\n\t/**\n\t * ID of the target sports.\n\t * \n\t * @param id\n\t */\n\tpublic void sportId(int id) {\n\t\tthis.parameters.put(\"sportId\", id);\n\t}\n\n\t/**\n\t * The leagueIds array may contain a list of comma separated league ids.\n\t * \n\t * @param ids\n\t * @return\n\t */\n\tpublic void leagueIds(long... ids) {\n\t\tString leagueIds = LongStream.of(ids).mapToObj(Long::toString).collect(Collectors.joining(\",\"));\n\t\tthis.parameters.put(\"leagueIds\", leagueIds);\n\t}\n\n\t/**\n\t * This accepts a single leagueId.\n\t * \n\t * @param ids\n\t * @return\n\t */\n\tpublic void leagueId(long id) {\n\t\tthis.parameters.put(\"leagueId\", id);\n\t}\n\n\t/**\n\t * This is used to receive incremental updates. Use the value of last from\n\t * previous fixtures response. When since parameter is not provided, the\n\t * fixtures are delayed up to 1 min to encourage the use of the parameter.\n\t * \n\t * Please note that when using since parameter to get odds you will get in\n\t * the response ONLY changed periods. If a period didn’t have any changes it\n\t * will not be in the response.\n\t * \n\t * @param since\n\t * @return\n\t */\n\tpublic void since(long since) {\n\t\tthis.parameters.put(\"since\", since);\n\t\tthis.withSince = true;\n\t}\n\n\t/**\n\t * To retrieve ONLY live games set the value to islive=1. If sportid is\n\t * provided along with the request, the result will be related to a single\n\t * sport. islive=0 cannot be used without the sportid parameter. This\n\t * ensures that the speed of the feed is not compromised. Sets isLive. This\n\t * is defined as Enum but just a simple boolean value.\n\t */\n\tpublic void isLive(boolean isLive) {\n\t\tString boolean2 = isLive ? \"1\" : \"0\";\n\t\tthis.parameters.put(\"isLive\", boolean2);\n\t}\n\n\t/**\n\t * Category of the special.\n\t * \n\t * @param category\n\t * @throws PinnacleException\n\t */\n\tpublic void category(String category) throws PinnacleException {\n\t\tif (category == null) throw PinnacleException.parameterInvalid(\"Parameter cannot accept null.\");\n\t\tcategory = this.urlEncode(category);\n\t\tthis.parameters.put(\"category\", category);\n\t}\n\n\t/**\n\t * Event id of the linked event\n\t * \n\t * @param eventId\n\t */\n\tpublic void eventId(long eventId) {\n\t\tthis.parameters.put(\"eventId\", eventId);\n\t}\n\n\t/**\n\t * Specific special Id\n\t * \n\t * @param specialId\n\t */\n\tpublic void specialId(long specialId) {\n\t\tthis.parameters.put(\"specialId\", specialId);\n\t}\n\n\t/**\n\t * Format the odds are returned in.\n\t * \n\t * @param oddsFormat\n\t * @throws PinnacleException \n\t */\n\tpublic void oddsFormat(ODDS_FORMAT oddsFormat) throws PinnacleException {\n\t\tif (oddsFormat == null || oddsFormat == ODDS_FORMAT.UNDEFINED) {\n\t\t\tthrow PinnacleException.parameterInvalid(\"Parameter cannot accept null or UNDEFINED.\");\n\t\t}\n\t\tthis.parameters.put(\"oddsFormat\", oddsFormat.toAPI());\n\t}\n\n\t/**\n\t * This represents the period of the match. You can check the numbers by Get\n\t * Periods operation.\n\t * \n\t * @param periodNumber\n\t */\n\tpublic void periodNumber(int periodNumber) {\n\t\tthis.parameters.put(\"periodNumber\", Integer.valueOf(periodNumber));\n\t}\n\n\t/**\n\t * This represents the period of the match. Note that they may change the\n\t * definitions.\n\t * \n\t * @param period\n\t * @throws PinnacleException \n\t */\n\tpublic void periodNumber(PERIOD period) throws PinnacleException {\n\t\tif (period == null) throw PinnacleException.parameterInvalid(\"Parameter cannot accept null.\");\n\t\tthis.parameters.put(\"periodNumber\", period.toAPI());\n\t}\n\n\t/**\n\t * A bet type of four types.\n\t * \n\t * @param type\n\t * @throws PinnacleException \n\t */\n\tpublic void betType(BET_TYPE type) throws PinnacleException {\n\t\tif (type == null || type == BET_TYPE.UNDEFINED) {\n\t\t\tthrow PinnacleException.parameterInvalid(\"Parameter cannot accept null or UNDEFINED.\");\n\t\t}\n\t\tthis.parameters.put(\"betType\", type.toAPI());\n\t}\n\n\t/**\n\t * Chosen team type. This is needed only for SPREAD, MONEYLINE and\n\t * TEAM_TOTAL_POINTS bet types.\n\t * \n\t * @param type\n\t * @throws PinnacleException \n\t */\n\tpublic void team(TEAM_TYPE type) throws PinnacleException {\n\t\tif (type == null || type == TEAM_TYPE.UNDEFINED) {\n\t\t\tthrow PinnacleException.parameterInvalid(\"Parameter cannot accept null or UNDEFINED.\");\n\t\t}\n\t\tthis.parameters.put(\"team\", type.toAPI());\n\t}\n\n\t/**\n\t * Chosen side. This is needed only for TOTAL_POINTS and TEAM_TOTAL_POINTS\n\t * bet type.\n\t * \n\t * @param type\n\t * @throws PinnacleException \n\t */\n\tpublic void side(SIDE_TYPE type) throws PinnacleException {\n\t\tif (type == null || type == SIDE_TYPE.UNDEFINED) {\n\t\t\tthrow PinnacleException.parameterInvalid(\"Parameter cannot accept null or UNDEFINED.\");\n\t\t}\n\t\tthis.parameters.put(\"side\", type.toAPI());\n\t}\n\n\t/**\n\t * Handicap value. This is needed for SPREAD, TOTAL_POINTS and\n\t * TEAM_TOTAL_POINTS bet type.\n\t * \n\t * @param handicap\n\t * @throws PinnacleException \n\t */\n\tpublic void handicap(String handicap) throws PinnacleException {\n\t\tif (handicap == null) throw PinnacleException.parameterInvalid(\"Parameter cannot accept null.\");\n\t\tBigDecimal decimal = new BigDecimal(handicap); // to validate\n\t\tthis.parameters.put(\"handicap\", decimal);\n\t}\n\n\t/**\n\t * Handicap value. This is needed for SPREAD, TOTAL_POINTS and\n\t * TEAM_TOTAL_POINTS bet type.\n\t * \n\t * @param handicap\n\t * @throws PinnacleException \n\t */\n\tpublic void handicap(BigDecimal handicap) throws PinnacleException {\n\t\tif (handicap == null) throw PinnacleException.parameterInvalid(\"Parameter cannot accept null.\");\n\t\tthis.parameters.put(\"handicap\", handicap);\n\t}\n\n\t/**\n\t * Collection of legs.\n\t * \n\t * @param legs\n\t * @throws PinnacleException \n\t */\n\tpublic void legs(Parameter... legs) throws PinnacleException {\n\t\tif (this.hasNull((Object[]) legs)) throw PinnacleException.parameterInvalid(\"Parameter cannot accept null.\");\n\t\tthis.legs = Arrays.asList(legs);\n\t}\n\n\t/**\n\t * Bet type for leg. Note that pinnacle don't use this name for legs in\n\t * getTeaserLines operation, which they implemented later.\n\t * \n\t * @param legBetType\n\t * @throws PinnacleException \n\t */\n\tpublic void legBetType(LEG_BET_TYPE type) throws PinnacleException {\n\t\tif (type == null || type == LEG_BET_TYPE.UNDEFINED) {\n\t\t\tthrow PinnacleException.parameterInvalid(\"Parameter cannot accept null or UNDEFINED.\");\n\t\t}\n\t\tthis.parameters.put(\"legBetType\", type.toAPI());\n\t}\n\n\t/**\n\t * This unique id of the leg. It used to identify and match leg in the\n\t * response.\n\t * \n\t * @return random generated UUID\n\t */\n\tpublic String uniqueLegId() {\n\t\tString uuid = UUID.randomUUID().toString();\n\t\tthis.parameters.put(\"uniqueLegId\", uuid);\n\t\treturn uuid;\n\t}\n\n\t/**\n\t * Client generated GUID for uniquely identifying the leg.\n\t * \n\t * @return\n\t */\n\tpublic String legId() {\n\t\tString uuid = UUID.randomUUID().toString();\n\t\tthis.parameters.put(\"legId\", uuid);\n\t\treturn uuid;\n\t}\n\n\t/**\n\t * Id of the contestant.\n\t * \n\t * @param contestantId\n\t */\n\tpublic void contestantId(long contestantId) {\n\t\tthis.parameters.put(\"contestantId\", contestantId);\n\t}\n\n\t/**\n\t * This unique id of the place bet requests. This is to support idempotent\n\t * requests.\n\t */\n\tpublic void uniqueRequestId() {\n\t\tthis.parameters.put(\"uniqueRequestId\", UUID.randomUUID().toString());\n\t}\n\n\t/**\n\t * Whether or not to accept a bet when there is a line change in favor of\n\t * the client.\n\t * \n\t * @param acceptBetterLine\n\t */\n\tpublic void acceptBetterLine(boolean acceptBetterLine) {\n\t\tthis.parameters.put(\"acceptBetterLine\", acceptBetterLine);\n\t}\n\n\t/**\n\t * Reference to a customer in third party system.\n\t * \n\t * @param customerReference\n\t * @throws PinnacleException\n\t */\n\tpublic void customerReference(String customerReference) throws PinnacleException {\n\t\tif (customerReference == null) throw PinnacleException.parameterInvalid(\"Parameter cannot accept null.\");\n\t\tcustomerReference = this.urlEncode(customerReference);\n\t\tthis.parameters.put(\"customerReference\", customerReference);\n\t}\n\n\t/**\n\t * Wagered amount in Client’s currency.\n\t * \n\t * @param stake\n\t * as String\n\t * @throws PinnacleException \n\t */\n\tpublic void stake(String stake) throws PinnacleException {\n\t\tif (stake == null) throw PinnacleException.parameterInvalid(\"Parameter cannot accept null.\");\n\t\tBigDecimal decimal = new BigDecimal(stake); // to validate\n\t\tthis.parameters.put(\"stake\", decimal);\n\t}\n\n\t/**\n\t * Alternate method of stake.\n\t * \n\t * @param stake\n\t * as BigDecimal\n\t * @throws PinnacleException \n\t */\n\tpublic void stake(BigDecimal stake) throws PinnacleException {\n\t\tif (stake == null) throw PinnacleException.parameterInvalid(\"Parameter cannot accept null.\");\n\t\tthis.parameters.put(\"stake\", stake);\n\t}\n\n\t/**\n\t * Whether the stake amount is risk or win amount.\n\t * \n\t * @param type\n\t * @throws PinnacleException \n\t */\n\tpublic void winRiskStake(WIN_RISK_TYPE type) throws PinnacleException {\n\t\tif (type == null || type == WIN_RISK_TYPE.UNDEFINED) {\n\t\t\tthrow PinnacleException.parameterInvalid(\"Parameter cannot accept null or UNDEFINED.\");\n\t\t}\n\t\tthis.parameters.put(\"winRiskStake\", type.toAPI());\n\t}\n\n\t/**\n\t * Sets lineId as parameter.\n\t * \n\t * @param lineId\n\t * - Line identification.\n\t */\n\tpublic void lineId(long lineId) {\n\t\tthis.parameters.put(\"lineId\", lineId);\n\t}\n\n\t/**\n\t * Sets altLineId as parameter.\n\t * \n\t * @param altLineId\n\t * - Alternate line identification.\n\t */\n\tpublic void altLineId(long altLineId) {\n\t\tthis.parameters.put(\"altLineId\", altLineId);\n\t}\n\n\t/**\n\t * Sets pitcher1MustStart as parameter.\n\t * \n\t * @param pitcher1MustStart\n\t * - Baseball only. Refers to the pitcher for TEAM_TYPE.Team1.\n\t * This applicable only for MONEYLINE bet type, for all other bet\n\t * types this has to be TRUE\n\t */\n\tpublic void pitcher1MustStart(boolean pitcher1MustStart) {\n\t\tthis.parameters.put(\"pitcher1MustStart\", pitcher1MustStart);\n\t}\n\n\t/**\n\t * Sets pitcher2MustStart as parameter.\n\t * \n\t * @param pitcher2MustStart\n\t * - Baseball only. Refers to the pitcher for TEAM_TYPE. Team2.\n\t * This applicable only for MONEYLINE bet type, for all other bet\n\t * types this has to be TRUE\n\t */\n\tpublic void pitcher2MustStart(boolean pitcher2MustStart) {\n\t\tthis.parameters.put(\"pitcher2MustStart\", pitcher2MustStart);\n\t}\n\n\t/**\n\t * Wagered amount in Client’s currency. It is always risk amount when\n\t * placing Parlay bets. NOTE: If round robin options is used this amount\n\t * will apply for all parlays so actual amount wagered will be riskAmount X\n\t * number of Parlays\n\t * \n\t * @param riskAmount\n\t * @throws PinnacleException \n\t */\n\tpublic void riskAmount(String riskAmount) throws PinnacleException {\n\t\tif (riskAmount == null) throw PinnacleException.parameterInvalid(\"Parameter cannot accept null.\");\n\t\tthis.parameters.put(\"riskAmount\", new BigDecimal(riskAmount));\n\t}\n\n\t/**\n\t * Alternate method of riskAmount.\n\t * \n\t * @param riskAmount\n\t * @throws PinnacleException \n\t */\n\tpublic void riskAmount(BigDecimal riskAmount) throws PinnacleException {\n\t\tif (riskAmount == null) throw PinnacleException.parameterInvalid(\"Parameter cannot accept null.\");\n\t\tthis.parameters.put(\"riskAmount\", riskAmount);\n\t}\n\n\t/**\n\t * ARRAY of ROUND_ROBIN_OPTIONS\n\t * \n\t * @param roundRobinOptions\n\t * @throws PinnacleException \n\t */\n\tpublic void roundRobinOptions(ROUND_ROBIN_OPTIONS... roundRobinOptions) throws PinnacleException {\n\t\tif (this.hasNull((Object[]) roundRobinOptions)) {\n\t\t\tthrow PinnacleException.parameterInvalid(\"Parameter cannot accept null.\");\n\t\t}\n\t\tthis.parameters.put(\"roundRobinOptions\", \n\t\t\t\tStream.of(roundRobinOptions)\n\t\t\t\t\t.filter(rr -> rr != ROUND_ROBIN_OPTIONS.UNDEFINED)\n\t\t\t\t\t.map(ROUND_ROBIN_OPTIONS::toAPI)\n\t\t\t\t\t.collect(Collectors.toList()));\n\t}\n\n\t/**\n\t * Unique identifier. Teaser details can be retrieved from a call to Get\n\t * Teaser Groups endpoint.\n\t * \n\t * @param teaserId\n\t */\n\tpublic void teaserId(long teaserId) {\n\t\tthis.parameters.put(\"teaserId\", teaserId);\n\t}\n\n\t/**\n\t * A list of special bets\n\t * @throws PinnacleException \n\t */\n\tpublic void bets(Parameter... bets) throws PinnacleException {\n\t\tif (this.hasNull((Object[]) bets)) throw PinnacleException.parameterInvalid(\"Parameter cannot accept null.\");\n\t\tthis.bets = Arrays.asList(bets);\n\t}\n\n\t/**\n\t * Not needed when betids is submitted.\n\t * \n\t * @param betlist\n\t * @throws PinnacleException \n\t */\n\tpublic void betlist(BETLIST_TYPE betlist) throws PinnacleException {\n\t\tif (betlist == null || betlist == BETLIST_TYPE.UNDEFINED) {\n\t\t\tthrow PinnacleException.parameterInvalid(\"Parameter cannot accept null or UNDEFINED.\");\n\t\t}\n\t\tthis.parameters.put(\"betlist\", betlist.toAPI());\n\t}\n\n\t/**\n\t * Array of bet ids. When betids is submitted, no other parameter is\n\t * necessary. Maximum is 100 ids. Works for all non settled bets and all\n\t * bets settled in the last 30 days\n\t * \n\t * @param ids\n\t * @throws PinnacleException\n\t */\n\tpublic void betids(long... ids) throws PinnacleException {\n\t\tif (ids.length > 100) {\n\t\t\tthrow PinnacleException.parameterInvalid(\"Number of 'betids' exceeds 100 as its maximum.\");\n\t\t}\n\t\tString betIds = LongStream.of(ids).mapToObj(Long::toString).collect(Collectors.joining(\",\"));\n\t\tthis.parameters.put(\"betids\", betIds);\n\t}\n\n\t/**\n\t * Start date of the requested period. Required when betlist parameter is\n\t * submitted. Difference between fromDate and toDdate can’t be more than 30\n\t * days. Expected format is ISO8601 - can be set to just date or date and\n\t * time.\n\t * @throws PinnacleException \n\t */\n\tpublic void fromDate(LocalDateTime fromDate) throws PinnacleException {\n\t\tif (fromDate == null) throw PinnacleException.parameterInvalid(\"Parameter cannot accept null.\");\n\t\tthis.parameters.put(\"fromDate\", fromDate.toString() + \"Z\"); // Z means\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// UTC\n\t}\n\n\t/**\n\t * Alternate method. Time will be set as 00:00:00.\n\t * \n\t * @param fromDate\n\t * @throws PinnacleException \n\t */\n\tpublic void fromDate(LocalDate fromDate) throws PinnacleException {\n\t\tif (fromDate == null) throw PinnacleException.parameterInvalid(\"Parameter cannot accept null.\");\n\t\tLocalTime fromTime = LocalTime.of(0, 0, 0);\n\t\tthis.fromDate(LocalDateTime.of(fromDate, fromTime));\n\t}\n\n\t/**\n\t * Alternate method. ZonedDateTime.toString returns like\n\t * \"2016-12-02T23:59:59Z[UTC]\" but Pinnacle API doesn't accept last square\n\t * brackets so needs to convert to LocalDateTime.\n\t * \n\t * @param fromDate\n\t * @throws PinnacleException \n\t */\n\tpublic void fromDate(ZonedDateTime fromDate) throws PinnacleException {\n\t\tif (fromDate == null) throw PinnacleException.parameterInvalid(\"Parameter cannot accept null.\");\n\t\tZonedDateTime utc = fromDate.withZoneSameInstant(Constants.TIME_ZONE);\n\t\tthis.fromDate(utc.toLocalDateTime());\n\t}\n\n\t/**\n\t * End date of the requested period Required when betlist parameter is\n\t * submitted. Expected format is ISO8601 - can be set to just date or date\n\t * and time. toDate value is exclusive, meaning it cannot be equal to\n\t * fromDate\n\t * @throws PinnacleException \n\t */\n\tpublic void toDate(LocalDateTime fromDate) throws PinnacleException {\n\t\tif (fromDate == null) throw PinnacleException.parameterInvalid(\"Parameter cannot accept null.\");\n\t\tthis.parameters.put(\"toDate\", fromDate.toString() + \"Z\"); // Z means UTC\n\t}\n\n\t/**\n\t * Alternate method. Time will be set as 23:59:59.\n\t * \n\t * @param fromDate\n\t * @throws PinnacleException \n\t */\n\tpublic void toDate(LocalDate fromDate) throws PinnacleException {\n\t\tif (fromDate == null) throw PinnacleException.parameterInvalid(\"Parameter cannot accept null.\");\n\t\tLocalTime fromTime = LocalTime.of(23, 59, 59);\n\t\tthis.toDate(LocalDateTime.of(fromDate, fromTime));\n\t}\n\n\t/**\n\t * Alternate method. ZonedDateTime.toString returns like\n\t * \"2016-12-02T23:59:59Z[UTC]\" but Pinnacle API doesn't accept last square\n\t * brackets so needs to convert to LocalDateTime.\n\t * \n\t * @param fromDate\n\t * @throws PinnacleException \n\t */\n\tpublic void toDate(ZonedDateTime fromDate) throws PinnacleException {\n\t\tif (fromDate == null) throw PinnacleException.parameterInvalid(\"Parameter cannot accept null.\");\n\t\tZonedDateTime utc = fromDate.withZoneSameInstant(Constants.TIME_ZONE);\n\t\tthis.toDate(utc.toLocalDateTime());\n\t}\n\n\tpublic void cultureCodes(CULTURE_CODE... codes) throws PinnacleException {\n\t\tif (this.hasNull((Object[]) codes)) throw PinnacleException.parameterInvalid(\"Parameter cannot accept null.\");\n\t\tString combined = Stream.of(codes).map(CULTURE_CODE::toAPI).collect(Collectors.joining(\"|\"));\n\t\tthis.parameters.put(\"cultureCodes\", combined);\n\t}\n\n\tpublic void baseTexts(String... baseTexts) throws PinnacleException {\n\t\tif (this.hasNull((Object[]) baseTexts)) throw PinnacleException.parameterInvalid(\"Parameter cannot accept null.\");\n\t\tList<String> encodedTexts = new ArrayList<>();\n\t\tfor (String text : baseTexts) {\n\t\t\tString encoded = this.urlEncode(text);\n\t\t\tencodedTexts.add(encoded);\n\t\t}\n\t\tString combined = encodedTexts.stream().collect(Collectors.joining(\"|\"));\n\t\tthis.parameters.put(\"baseTexts\", combined);\n\t}\n\t\n}", "public class PinnacleAPI {\n\n\t/**\n\t * Base64 value of UTF-8 encoded \"username:password\" for authentication.\n\t */\n\tprivate final String credentials;\n\n\t/**\n\t * Constructor with credentials.\n\t * \n\t * @param credentials\n\t */\n\tprivate PinnacleAPI(String credentials) {\n\t\tthis.credentials = credentials;\n\t}\n\n\t/**\n\t * Factory with credentials.\n\t * \n\t * @param credentials\n\t * @return\n\t */\n\tpublic static PinnacleAPI open(String credentials) {\n\t\treturn new PinnacleAPI(credentials);\n\t}\n\n\t/**\n\t * Factory with raw username and password.\n\t * \n\t * @param username\n\t * @param password\n\t * @return\n\t * @throws PinnacleException\n\t */\n\tpublic static PinnacleAPI open(String username, String password) throws PinnacleException {\n\t\tString credentials = encode(username, password);\n\t\treturn new PinnacleAPI(credentials);\n\t}\n\n\t/**\n\t * Encodes username and password by Base64.\n\t * \n\t * @param username\n\t * @param password\n\t * @return\n\t * @throws PinnacleException\n\t * @throws UnsupportedEncodingException\n\t */\n\tprivate static String encode(String username, String password) throws PinnacleException {\n\t\ttry {\n\t\t\tString id = username + \":\" + password;\n\t\t\tbyte[] bytes = id.getBytes(Constants.CHARSET);\n\t\t\treturn Base64.getEncoder().encodeToString(bytes);\n\t\t} catch (UnsupportedEncodingException e) {\n\t\t\tthrow PinnacleException.parameterInvalid(\n\t\t\t\t\t\"Couldn't encode your username and password. Caught UnsupportedEncodingException: \"\n\t\t\t\t\t\t\t+ e.getMessage());\n\t\t}\n\t}\n\n\t/**\n\t * Returns URL from string. Converts MalformedURLException to\n\t * PinnacleException if catches.\n\t * \n\t * @param url\n\t * @return\n\t * @throws PinnacleException\n\t */\n\tprivate static URL getUrl(String url) throws PinnacleException {\n\t\ttry {\n\t\t\treturn new URL(url);\n\t\t} catch (MalformedURLException e) { // should not catch\n\t\t\tthrow PinnacleException\n\t\t\t\t\t.parameterInvalid(\"Malformed URL created in the code. Not from input.\" + e.getMessage());\n\t\t}\n\t}\n\n\t/**\n\t * Sends requests to 'GetSports' and returns its response.\n\t * \n\t * @return Response\n\t * @throws PinnacleException\n\t */\n\tprivate Response getSports() throws PinnacleException {\n\t\tURL url = getUrl(Constants.BASE_URL + \"/v2/sports\");\n\t\tRequest request = Request.newRequest(url).get();\n\t\treturn request.execute(this.credentials);\n\t}\n\n\t/**\n\t * Sends requests to 'GetSports' and returns its response as JSON plain\n\t * text.\n\t * \n\t * @return JSON text\n\t * @throws PinnacleException\n\t */\n\tpublic String getSportsAsJson() throws PinnacleException {\n\t\treturn this.getSports().text();\n\t}\n\n\t/**\n\t * Sends requests to 'GetSports' and returns its response as mapped Object.\n\t * \n\t * @return Sports - isEmpty will be set true when JSON text is empty and\n\t * isFlawed will be set when JSON text doesn't have all of required\n\t * keys.\n\t * @throws PinnacleException\n\t */\n\tpublic Sports getSportsAsObject() throws PinnacleException {\n\t\treturn Sports.parse(this.getSportsAsJson());\n\t}\n\n\t/**\n\t * Sends requests to 'GetLeagues' and returns its response.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Response\n\t * @throws PinnacleException\n\t */\n\tprivate Response getLeagues(Parameter parameter) throws PinnacleException {\n\t\tValidators.toGetLeagues(parameter);\n\t\tURL url = getUrl(Constants.BASE_URL + \"/v2/leagues?\" + parameter.toUrlQuery());\n\t\tRequest request = Request.newRequest(url).get();\n\t\treturn request.execute(this.credentials);\n\t}\n\n\t/**\n\t * Sends requests to 'GetLeagues' and returns its response as JSON plain\n\t * text.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return JSON text\n\t * @throws PinnacleException\n\t */\n\tpublic String getLeaguesAsJson(Parameter parameter) throws PinnacleException {\n\t\treturn this.getLeagues(parameter).text();\n\t}\n\n\t/**\n\t * Sends requests to 'GetLeagues' and returns its response as mapped Object.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Leagues - isEmpty will be set true when JSON text is empty and\n\t * isFlawed will be set when JSON text doesn't have all of required\n\t * keys.\n\t * @throws PinnacleException\n\t */\n\tpublic Leagues getLeaguesAsObject(Parameter parameter) throws PinnacleException {\n\t\treturn Leagues.parse(this.getLeaguesAsJson(parameter));\n\t}\n\n\t/**\n\t * Sends requests to 'GetFixtures' and returns its response.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Response\n\t * @throws PinnacleException\n\t */\n\tprivate Response getFixtures(Parameter parameter) throws PinnacleException {\n\t\tValidators.toGetFixtures(parameter);\n\t\tURL url = getUrl(Constants.BASE_URL + \"/v1/fixtures?\" + parameter.toUrlQuery());\n\t\tRequest request = Request.newRequest(url).get().fairUse(parameter.withSince());\n\t\treturn request.execute(this.credentials);\n\t}\n\n\t/**\n\t * Sends requests to 'GetFixtures' and returns its response as JSON plain\n\t * text.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return JSON text\n\t * @throws PinnacleException\n\t */\n\tpublic String getFixturesAsJson(Parameter parameter) throws PinnacleException {\n\t\treturn this.getFixtures(parameter).text();\n\t}\n\n\t/**\n\t * Sends requests to 'GetFixtures' and returns its response as mapped\n\t * Object.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Fixtures - isEmpty will be set true when JSON text is empty and\n\t * isFlawed will be set when JSON text doesn't have all of required\n\t * keys.\n\t * @throws PinnacleException\n\t */\n\tpublic Fixtures getFixturesAsObject(Parameter parameter) throws PinnacleException {\n\t\treturn Fixtures.parse(this.getFixturesAsJson(parameter));\n\t}\n\n\t/**\n\t * Sends requests to 'GetSettledFixtures' and returns its response.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Response\n\t * @throws PinnacleException\n\t */\n\tprivate Response getSettledFixtures(Parameter parameter) throws PinnacleException {\n\t\tValidators.toGetSettledFixtures(parameter);\n\t\tURL url = getUrl(Constants.BASE_URL + \"/v1/fixtures/settled?\" + parameter.toUrlQuery());\n\t\tRequest request = Request.newRequest(url).get().fairUse(parameter.withSince());\n\t\treturn request.execute(this.credentials);\n\t}\n\n\t/**\n\t * Sends requests to 'GetSettledFixtures' and returns its response as JSON\n\t * plain text.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return JSON text\n\t * @throws PinnacleException\n\t */\n\tpublic String getSettledFixturesAsJson(Parameter parameter) throws PinnacleException {\n\t\treturn this.getSettledFixtures(parameter).text();\n\t}\n\n\t/**\n\t * Sends requests to 'GetSettledFixtures' and returns its response as mapped\n\t * Object.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return SettledFixtures - isEmpty will be set true when JSON text is\n\t * empty and isFlawed will be set when JSON text doesn't have all of\n\t * required keys.\n\t * @throws PinnacleException\n\t */\n\tpublic SettledFixtures getSettledFixturesAsObject(Parameter parameter) throws PinnacleException {\n\t\treturn SettledFixtures.parse(this.getSettledFixturesAsJson(parameter));\n\t}\n\n\t/**\n\t * Sends requests to 'GetSpecialFixtures' and returns its response.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Response\n\t * @throws PinnacleException\n\t */\n\tprivate Response getSpecialFixtures(Parameter parameter) throws PinnacleException {\n\t\tValidators.toGetSpecialFixtures(parameter);\n\t\tURL url = getUrl(Constants.BASE_URL + \"/v1/fixtures/special?\" + parameter.toUrlQuery());\n\t\tRequest request = Request.newRequest(url).get().fairUse(parameter.withSince());\n\t\treturn request.execute(this.credentials);\n\t}\n\n\t/**\n\t * Sends requests to 'GetSpecialFixtures' and returns its response as JSON\n\t * plain text.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return JSON text\n\t * @throws PinnacleException\n\t */\n\tpublic String getSpecialFixturesAsJson(Parameter parameter) throws PinnacleException {\n\t\treturn this.getSpecialFixtures(parameter).text();\n\t}\n\n\t/**\n\t * Sends requests to 'GetSpecialFixtures' and returns its response as mapped\n\t * Object.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return SpecialFixtures - isEmpty will be set true when JSON text is\n\t * empty and isFlawed will be set when JSON text doesn't have all of\n\t * required keys.\n\t * @throws PinnacleException\n\t */\n\tpublic SpecialFixtures getSpecialFixturesAsObject(Parameter parameter) throws PinnacleException {\n\t\treturn SpecialFixtures.parse(this.getSpecialFixturesAsJson(parameter));\n\t}\n\n\t/**\n\t * Sends requests to 'GetSettledSpecialFixtures' and returns its response.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Response\n\t * @throws PinnacleException\n\t */\n\tprivate Response getSettledSpecialFixtures(Parameter parameter) throws PinnacleException {\n\t\tValidators.toGetSettledSpecialFixtures(parameter);\n\t\tURL url = getUrl(Constants.BASE_URL + \"/v1/fixtures/special/settled?\" + parameter.toUrlQuery());\n\t\tRequest request = Request.newRequest(url).get().fairUse(parameter.withSince());\n\t\treturn request.execute(this.credentials);\n\t}\n\n\t/**\n\t * Sends requests to 'GetSettledSpecialFixtures' and returns its response as\n\t * JSON plain text.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return JSON text\n\t * @throws PinnacleException\n\t */\n\tpublic String getSettledSpecialFixturesAsJson(Parameter parameter) throws PinnacleException {\n\t\treturn this.getSettledSpecialFixtures(parameter).text();\n\t}\n\n\t/**\n\t * Sends requests to 'GetSettledSpecialFixtures' and returns its response as\n\t * mapped Object.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return SettledSpecialFixtures - isEmpty will be set true when JSON text\n\t * is empty and isFlawed will be set when JSON text doesn't have all\n\t * of required keys.\n\t * @throws PinnacleException\n\t */\n\tpublic SettledSpecialFixtures getSettledSpecialFixturesAsObject(Parameter parameter) throws PinnacleException {\n\t\treturn SettledSpecialFixtures.parse(this.getSettledSpecialFixturesAsJson(parameter));\n\t}\n\n\t/**\n\t * Sends requests to 'GetTeaserGroups' and returns its response.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Response\n\t * @throws PinnacleException\n\t */\n\tprivate Response getTeaserGroups(Parameter parameter) throws PinnacleException {\n\t\tValidators.toGetTeaserGroups(parameter);\n\t\tURL url = getUrl(Constants.BASE_URL + \"/v1/teaser/groups?\" + parameter.toUrlQuery());\n\t\tRequest request = Request.newRequest(url).get();\n\t\treturn request.execute(this.credentials);\n\t}\n\n\t/**\n\t * Sends requests to 'GetTeaserGroups' and returns its response as JSON\n\t * plain text.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return JSON text\n\t * @throws PinnacleException\n\t */\n\tpublic String getTeaserGroupsAsJson(Parameter parameter) throws PinnacleException {\n\t\treturn this.getTeaserGroups(parameter).text();\n\t}\n\n\t/**\n\t * Sends requests to 'GetTeaserGroups' and returns its response as mapped\n\t * Object.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return TeaserGroups - isEmpty will be set true when JSON text is empty\n\t * and isFlawed will be set when JSON text doesn't have all of\n\t * required keys.\n\t * @throws PinnacleException\n\t */\n\tpublic TeaserGroups getTeaserGroupsAsObject(Parameter parameter) throws PinnacleException {\n\t\treturn TeaserGroups.parse(this.getTeaserGroupsAsJson(parameter));\n\t}\n\n\t/**\n\t * Sends requests to 'GetOdds' and returns its response.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Response\n\t * @throws PinnacleException\n\t */\n\tprivate Response getOdds(Parameter parameter) throws PinnacleException {\n\t\tValidators.toGetOdds(parameter);\n\t\tURL url = getUrl(Constants.BASE_URL + \"/v1/odds?\" + parameter.toUrlQuery());\n\t\tRequest request = Request.newRequest(url).get().fairUse(parameter.withSince());\n\t\treturn request.execute(this.credentials);\n\t}\n\n\t/**\n\t * Sends requests to 'GetOdds' and returns its response as JSON plain text.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return JSON text\n\t * @throws PinnacleException\n\t */\n\tpublic String getOddsAsJson(Parameter parameter) throws PinnacleException {\n\t\treturn this.getOdds(parameter).text();\n\t}\n\n\t/**\n\t * Sends requests to 'GetOdds' and returns its response as mapped Object.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Odds - isEmpty will be set true when JSON text is empty and\n\t * isFlawed will be set when JSON text doesn't have all of required\n\t * keys.\n\t * @throws PinnacleException\n\t */\n\tpublic Odds getOddsAsObject(Parameter parameter) throws PinnacleException {\n\t\treturn Odds.parse(this.getOddsAsJson(parameter));\n\t}\n\n\t/**\n\t * Sends requests to 'GetParlayOdds' and returns its response.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Response\n\t * @throws PinnacleException\n\t */\n\tprivate Response getParlayOdds(Parameter parameter) throws PinnacleException {\n\t\tValidators.toGetParlayOdds(parameter);\n\t\tURL url = getUrl(Constants.BASE_URL + \"/v1/odds/parlay?\" + parameter.toUrlQuery());\n\t\tRequest request = Request.newRequest(url).get().fairUse(parameter.withSince());\n\t\treturn request.execute(this.credentials);\n\t}\n\n\t/**\n\t * Sends requests to 'GetParlayOdds' and returns its response as JSON plain\n\t * text.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return JSON text\n\t * @throws PinnacleException\n\t */\n\tpublic String getParlayOddsAsJson(Parameter parameter) throws PinnacleException {\n\t\treturn this.getParlayOdds(parameter).text();\n\t}\n\n\t/**\n\t * Sends requests to 'GetParlayOdds' and returns its response as mapped\n\t * Object.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Odds - isEmpty will be set true when JSON text is empty and\n\t * isFlawed will be set when JSON text doesn't have all of required\n\t * keys.\n\t * @throws PinnacleException\n\t */\n\tpublic Odds getParlayOddsAsObject(Parameter parameter) throws PinnacleException {\n\t\treturn Odds.parse(this.getParlayOddsAsJson(parameter));\n\t}\n\n\t/**\n\t * Sends requests to 'GetTeaserOdds' and returns its response.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Response\n\t * @throws PinnacleException\n\t */\n\tprivate Response getTeaserOdds(Parameter parameter) throws PinnacleException {\n\t\tValidators.toGetTeaserOdds(parameter);\n\t\tURL url = getUrl(Constants.BASE_URL + \"/v1/odds/teaser?\" + parameter.toUrlQuery());\n\t\tRequest request = Request.newRequest(url).get().fairUse(parameter.withSince());\n\t\treturn request.execute(this.credentials);\n\t}\n\n\t/**\n\t * Sends requests to 'GetTeaserOdds' and returns its response as JSON plain\n\t * text.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return JSON text\n\t * @throws PinnacleException\n\t */\n\tpublic String getTeaserOddsAsJson(Parameter parameter) throws PinnacleException {\n\t\treturn this.getTeaserOdds(parameter).text();\n\t}\n\n\t/**\n\t * Sends requests to 'GetTeaserOdds' and returns its response as mapped\n\t * Object.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return TeaserOdds - isEmpty will be set true when JSON text is empty and\n\t * isFlawed will be set when JSON text doesn't have all of required\n\t * keys.\n\t * @throws PinnacleException\n\t */\n\tpublic TeaserOdds getTeaserOddsAsObject(Parameter parameter) throws PinnacleException {\n\t\treturn TeaserOdds.parse(this.getTeaserOddsAsJson(parameter));\n\t}\n\n\t/**\n\t * Sends requests to 'GetSpecialOdds' and returns its response.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Response\n\t * @throws PinnacleException\n\t */\n\tprivate Response getSpecialOdds(Parameter parameter) throws PinnacleException {\n\t\tValidators.toGetSpecialOdds(parameter);\n\t\tURL url = getUrl(Constants.BASE_URL + \"/v1/odds/special?\" + parameter.toUrlQuery());\n\t\tRequest request = Request.newRequest(url).get().fairUse(parameter.withSince());\n\t\treturn request.execute(this.credentials);\n\t}\n\n\t/**\n\t * Sends requests to 'GetSpecialOdds' and returns its response as JSON plain\n\t * text.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return JSON text\n\t * @throws PinnacleException\n\t */\n\tpublic String getSpecialOddsAsJson(Parameter parameter) throws PinnacleException {\n\t\treturn this.getSpecialOdds(parameter).text();\n\t}\n\n\t/**\n\t * Sends requests to 'GetSpecialOdds' and returns its response as mapped\n\t * Object.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return SpecialOdds - isEmpty will be set true when JSON text is empty\n\t * and isFlawed will be set when JSON text doesn't have all of\n\t * required keys.\n\t * @throws PinnacleException\n\t */\n\tpublic SpecialOdds getSpecialOddsAsObject(Parameter parameter) throws PinnacleException {\n\t\treturn SpecialOdds.parse(this.getSpecialOddsAsJson(parameter));\n\t}\n\n\t/**\n\t * Sends requests to 'GetCurrencies' and returns its response.\n\t * \n\t * @return Response\n\t * @throws PinnacleException\n\t */\n\tprivate Response getCurrencies() throws PinnacleException {\n\t\tURL url = getUrl(Constants.BASE_URL + \"/v2/currencies\");\n\t\tRequest request = Request.newRequest(url).get();\n\t\treturn request.execute(this.credentials);\n\t}\n\n\t/**\n\t * Sends requests to 'GetCurrencies' and returns its response as JSON plain\n\t * text.\n\t * \n\t * @return JSON text\n\t * @throws PinnacleException\n\t */\n\tpublic String getCurrenciesAsJson() throws PinnacleException {\n\t\treturn this.getCurrencies().text();\n\t}\n\n\t/**\n\t * Sends requests to 'GetCurrencies' and returns its response as mapped\n\t * Object.\n\t * \n\t * @return Currencies - isEmpty will be set true when JSON text is empty and\n\t * isFlawed will be set when JSON text doesn't have all of required\n\t * keys.\n\t * @throws PinnacleException\n\t */\n\tpublic Currencies getCurrenciesAsObject() throws PinnacleException {\n\t\treturn Currencies.parse(this.getCurrenciesAsJson());\n\t}\n\n\t/**\n\t * Sends requests to 'GetClientBalance' and returns its response.\n\t * \n\t * @return Response\n\t * @throws PinnacleException\n\t */\n\tprivate Response getClientBalance() throws PinnacleException {\n\t\tURL url = getUrl(Constants.BASE_URL + \"/v1/client/balance\");\n\t\tRequest request = Request.newRequest(url).get();\n\t\treturn request.execute(this.credentials);\n\t}\n\n\t/**\n\t * Sends requests to 'GetClientBalance' and returns its response as JSON\n\t * plain text.\n\t * \n\t * @return JSON text\n\t * @throws PinnacleException\n\t */\n\tpublic String getClientBalanceAsJson() throws PinnacleException {\n\t\treturn this.getClientBalance().text();\n\t}\n\n\t/**\n\t * Sends requests to 'GetClientBalance' and returns its response as mapped\n\t * Object.\n\t * \n\t * @return ClientBalance - isEmpty will be set true when JSON text is empty\n\t * and isFlawed will be set when JSON text doesn't have all of\n\t * required keys.\n\t * @throws PinnacleException\n\t */\n\tpublic ClientBalance getClientBalanceAsObject() throws PinnacleException {\n\t\treturn ClientBalance.parse(this.getClientBalanceAsJson());\n\t}\n\n\t/**\n\t * Sends requests to 'GetLine' and returns its response.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Response\n\t * @throws PinnacleException\n\t */\n\tprivate Response getLine(Parameter parameter) throws PinnacleException {\n\t\tValidators.toGetLine(parameter);\n\t\tURL url = getUrl(Constants.BASE_URL + \"/v1/line?\" + parameter.toUrlQuery());\n\t\tRequest request = Request.newRequest(url).get();\n\t\treturn request.execute(this.credentials);\n\t}\n\n\t/**\n\t * Sends requests to 'GetLine' and returns its response as JSON plain text.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return JSON text\n\t * @throws PinnacleException\n\t */\n\tpublic String getLineAsJson(Parameter parameter) throws PinnacleException {\n\t\treturn this.getLine(parameter).text();\n\t}\n\n\t/**\n\t * Sends requests to 'GetLine' and returns its response as mapped Object.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Line - isEmpty will be set true when JSON text is empty and\n\t * isFlawed will be set when JSON text doesn't have all of required\n\t * keys.\n\t * @throws PinnacleException\n\t */\n\tpublic Line getLineAsObject(Parameter parameter) throws PinnacleException {\n\t\treturn Line.parse(this.getLineAsJson(parameter));\n\t}\n\n\t/**\n\t * Sends requests to 'GetParlayLines' and returns its response.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Response\n\t * @throws PinnacleException\n\t */\n\tprivate Response getParlayLines(Parameter parameter) throws PinnacleException {\n\t\tValidators.toGetParlayLines(parameter);\n\t\tURL url = getUrl(Constants.BASE_URL + \"/v1/line/parlay\");\n\t\tRequest request = Request.newRequest(url).post(parameter);\n\t\treturn request.execute(this.credentials);\n\t}\n\n\t/**\n\t * Sends requests to 'GetParlayLines' and returns its response as JSON plain\n\t * text.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return JSON text\n\t * @throws PinnacleException\n\t */\n\tpublic String getParlayLinesAsJson(Parameter parameter) throws PinnacleException {\n\t\treturn this.getParlayLines(parameter).text();\n\t}\n\n\t/**\n\t * Sends requests to 'GetParlayLines' and returns its response as mapped\n\t * Object.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return ParlayLines - isEmpty will be set true when JSON text is empty\n\t * and isFlawed will be set when JSON text doesn't have all of\n\t * required keys.\n\t * @throws PinnacleException\n\t */\n\tpublic ParlayLines getParlayLinesAsObject(Parameter parameter) throws PinnacleException {\n\t\treturn ParlayLines.parse(this.getParlayLinesAsJson(parameter));\n\t}\n\n\t/**\n\t * Sends requests to 'GetTeaserLines' and returns its response.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Response\n\t * @throws PinnacleException\n\t */\n\tprivate Response getTeaserLines(Parameter parameter) throws PinnacleException {\n\t\tValidators.toGetTeaserLines(parameter);\n\t\tURL url = getUrl(Constants.BASE_URL + \"/v1/line/teaser\");\n\t\tRequest request = Request.newRequest(url).post(parameter);\n\t\treturn request.execute(this.credentials);\n\t}\n\n\t/**\n\t * Sends requests to 'GetTeaserLines' and returns its response as JSON plain\n\t * text.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return JSON text\n\t * @throws PinnacleException\n\t */\n\tpublic String getTeaserLinesAsJson(Parameter parameter) throws PinnacleException {\n\t\treturn this.getTeaserLines(parameter).text();\n\t}\n\n\t/**\n\t * Sends requests to 'GetTeaserLines' and returns its response as mapped\n\t * Object.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return TeaserLines - isEmpty will be set true when JSON text is empty\n\t * and isFlawed will be set when JSON text doesn't have all of\n\t * required keys.\n\t * @throws PinnacleException\n\t */\n\tpublic TeaserLines getTeaserLinesAsObject(Parameter parameter) throws PinnacleException {\n\t\treturn TeaserLines.parse(this.getTeaserLinesAsJson(parameter));\n\t}\n\n\t/**\n\t * Sends requests to 'GetSpecialLines' and returns its response.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Response\n\t * @throws PinnacleException\n\t */\n\tprivate Response getSpecialLines(Parameter parameter) throws PinnacleException {\n\t\tValidators.toGetSpecialLines(parameter);\n\t\tURL url = getUrl(Constants.BASE_URL + \"/v1/line/special?\" + parameter.toUrlQuery());\n\t\tRequest request = Request.newRequest(url).get();\n\t\treturn request.execute(this.credentials);\n\t}\n\n\t/**\n\t * Sends requests to 'GetSpecialLines' and returns its response as JSON\n\t * plain text.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return JSON text\n\t * @throws PinnacleException\n\t */\n\tpublic String getSpecialLinesAsJson(Parameter parameter) throws PinnacleException {\n\t\treturn this.getSpecialLines(parameter).text();\n\t}\n\n\t/**\n\t * Sends requests to 'GetSpecialLines' and returns its response as mapped\n\t * Object.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return SpecialLines - isEmpty will be set true when JSON text is empty\n\t * and isFlawed will be set when JSON text doesn't have all of\n\t * required keys.\n\t * @throws PinnacleException\n\t */\n\tpublic SpecialLines getSpecialLinesAsObject(Parameter parameter) throws PinnacleException {\n\t\treturn SpecialLines.parse(this.getSpecialLinesAsJson(parameter));\n\t}\n\n\t/**\n\t * Sends requests to 'PlaceBet' and returns its response.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Response\n\t * @throws PinnacleException\n\t */\n\tprivate Response placeBet(Parameter parameter) throws PinnacleException {\n\t\tValidators.toPlaceBet(parameter);\n\t\tURL url = getUrl(Constants.BASE_URL + \"/v1/bets/place\");\n\t\tRequest request = Request.newRequest(url).post(parameter);\n\t\treturn request.execute(this.credentials);\n\t}\n\n\t/**\n\t * Sends requests to 'PlaceBet' and returns its response as JSON plain text.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return JSON text\n\t * @throws PinnacleException\n\t */\n\tpublic String placeBetAsJson(Parameter parameter) throws PinnacleException {\n\t\treturn this.placeBet(parameter).text();\n\t}\n\n\t/**\n\t * Sends requests to 'PlaceBet' and returns its response as mapped Object.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return PlacedBet - isEmpty will be set true when JSON text is empty and\n\t * isFlawed will be set when JSON text doesn't have all of required\n\t * keys.\n\t * @throws PinnacleException\n\t */\n\tpublic PlacedBet placeBetAsObject(Parameter parameter) throws PinnacleException {\n\t\treturn PlacedBet.parse(this.placeBetAsJson(parameter));\n\t}\n\n\t/**\n\t * Sends requests to 'PlaceParlayBet' and returns its response.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Response\n\t * @throws PinnacleException\n\t */\n\tprivate Response placeParlayBet(Parameter parameter) throws PinnacleException {\n\t\tValidators.toPlaceParlayBet(parameter);\n\t\tURL url = getUrl(Constants.BASE_URL + \"/v1/bets/parlay\");\n\t\tRequest request = Request.newRequest(url).post(parameter);\n\t\treturn request.execute(this.credentials);\n\t}\n\n\t/**\n\t * Sends requests to 'PlaceParlayBet' and returns its response as JSON plain\n\t * text.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return JSON text\n\t * @throws PinnacleException\n\t */\n\tpublic String placeParlayBetAsJson(Parameter parameter) throws PinnacleException {\n\t\treturn this.placeParlayBet(parameter).text();\n\t}\n\n\t/**\n\t * Sends requests to 'PlaceParlayBet' and returns its response as mapped\n\t * Object.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return PlacedParlayBet - isEmpty will be set true when JSON text is\n\t * empty and isFlawed will be set when JSON text doesn't have all of\n\t * required keys.\n\t * @throws PinnacleException\n\t */\n\tpublic PlacedParlayBet placeParlayBetAsObject(Parameter parameter) throws PinnacleException {\n\t\treturn PlacedParlayBet.parse(this.placeParlayBetAsJson(parameter));\n\t}\n\n\t/**\n\t * Sends requests to 'PlaceTeaserBet' and returns its response.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Response\n\t * @throws PinnacleException\n\t */\n\tprivate Response placeTeaserBet(Parameter parameter) throws PinnacleException {\n\t\tValidators.toPlaceTeaserBet(parameter);\n\t\tURL url = getUrl(Constants.BASE_URL + \"/v1/bets/teaser\");\n\t\tRequest request = Request.newRequest(url).post(parameter);\n\t\treturn request.execute(this.credentials);\n\t}\n\n\t/**\n\t * Sends requests to 'PlaceTeaserBet' and returns its response as JSON plain\n\t * text.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return JSON text\n\t * @throws PinnacleException\n\t */\n\tpublic String placeTeaserBetAsJson(Parameter parameter) throws PinnacleException {\n\t\treturn this.placeTeaserBet(parameter).text();\n\t}\n\n\t/**\n\t * Sends requests to 'PlaceTeaserBet' and returns its response as mapped\n\t * Object.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return PlacedTeaserBet - isEmpty will be set true when JSON text is\n\t * empty and isFlawed will be set when JSON text doesn't have all of\n\t * required keys.\n\t * @throws PinnacleException\n\t */\n\tpublic PlacedTeaserBet placeTeaserBetAsObject(Parameter parameter) throws PinnacleException {\n\t\treturn PlacedTeaserBet.parse(this.placeTeaserBetAsJson(parameter));\n\t}\n\n\t/**\n\t * Sends requests to 'PlaceSpecialBet' and returns its response.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Response\n\t * @throws PinnacleException\n\t */\n\tprivate Response placeSpecialBet(Parameter parameter) throws PinnacleException {\n\t\tValidators.toPlaceSpecialBet(parameter);\n\t\tURL url = getUrl(Constants.BASE_URL + \"/v1/bets/special\");\n\t\tRequest request = Request.newRequest(url).post(parameter);\n\t\treturn request.execute(this.credentials);\n\t}\n\n\t/**\n\t * Sends requests to 'PlaceSpecialBet' and returns its response as JSON\n\t * plain text.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return JSON text\n\t * @throws PinnacleException\n\t */\n\tpublic String placeSpecialBetAsJson(Parameter parameter) throws PinnacleException {\n\t\treturn this.placeSpecialBet(parameter).text();\n\t}\n\n\t/**\n\t * Sends requests to 'PlaceSpecialBet' and returns its response as mapped\n\t * Object.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return PlacedSpecialBet - isEmpty will be set true when JSON text is\n\t * empty and isFlawed will be set when JSON text doesn't have all of\n\t * required keys.\n\t * @throws PinnacleException\n\t */\n\tpublic PlacedSpecialBet placeSpecialBetAsObject(Parameter parameter) throws PinnacleException {\n\t\treturn PlacedSpecialBet.parse(this.placeSpecialBetAsJson(parameter));\n\t}\n\n\t/**\n\t * Sends requests to 'GetBets' and returns its response.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Response\n\t * @throws PinnacleException\n\t */\n\tprivate Response getBets(Parameter parameter) throws PinnacleException {\n\t\tValidators.toGetBets(parameter);\n\t\tURL url = getUrl(Constants.BASE_URL + \"/v1/bets?\" + parameter.toUrlQuery());\n\t\tRequest request = Request.newRequest(url).get();\n\t\treturn request.execute(this.credentials);\n\t}\n\n\t/**\n\t * Sends requests to 'GetBets' and returns its response as JSON plain text.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return JSON text\n\t * @throws PinnacleException\n\t */\n\tpublic String getBetsAsJson(Parameter parameter) throws PinnacleException {\n\t\treturn this.getBets(parameter).text();\n\t}\n\n\t/**\n\t * Sends requests to 'GetBets' and returns its response as mapped Object.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Bets - isEmpty will be set true when JSON text is empty and\n\t * isFlawed will be set when JSON text doesn't have all of required\n\t * keys.\n\t * @throws PinnacleException\n\t */\n\tpublic Bets getBetsAsObject(Parameter parameter) throws PinnacleException {\n\t\treturn Bets.parse(this.getBetsAsJson(parameter));\n\t}\n\n\t/**\n\t * Sends requests to 'GetInrunning' and returns its response.\n\t * \n\t * @return Response\n\t * @throws PinnacleException\n\t */\n\tprivate Response getInrunning() throws PinnacleException {\n\t\tURL url = getUrl(Constants.BASE_URL + \"/v1/inrunning\");\n\t\tRequest request = Request.newRequest(url).get();\n\t\treturn request.execute(this.credentials);\n\t}\n\n\t/**\n\t * Sends requests to 'GetInrunning' and returns its response as JSON plain\n\t * text.\n\t * \n\t * @return JSON text\n\t * @throws PinnacleException\n\t */\n\tpublic String getInrunningAsJson() throws PinnacleException {\n\t\treturn this.getInrunning().text();\n\t}\n\n\t/**\n\t * Sends requests to 'GetInrunning' and returns its response as mapped\n\t * Object.\n\t * \n\t * @return Inrunning - isEmpty will be set true when JSON text is empty and\n\t * isFlawed will be set when JSON text doesn't have all of required\n\t * keys.\n\t * @throws PinnacleException\n\t */\n\tpublic Inrunning getInrunningAsObject() throws PinnacleException {\n\t\treturn Inrunning.parse(this.getInrunningAsJson());\n\t}\n\n\t/**\n\t * Sends requests to 'GetTranslations' and returns its response.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Response\n\t * @throws PinnacleException\n\t */\n\tprivate Response getTranslations(Parameter parameter) throws PinnacleException {\n\t\tValidators.toGetTranslations(parameter);\n\t\tURL url = getUrl(Constants.BASE_URL + \"/v1/translations?\" + parameter.toUrlQuery());\n\t\tRequest request = Request.newRequest(url).get();\n\t\treturn request.execute(this.credentials);\n\t}\n\n\t/**\n\t * Sends requests to 'GetTranslations' and returns its response as JSON\n\t * plain text.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return JSON text\n\t * @throws PinnacleException\n\t */\n\tpublic String getTranslationsAsJson(Parameter parameter) throws PinnacleException {\n\t\treturn this.getTranslations(parameter).text();\n\t}\n\n\t/**\n\t * Sends requests to 'GetTranslations' and returns its response as mapped\n\t * Object.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Translations - isEmpty will be set true when JSON text is empty\n\t * and isFlawed will be set when JSON text doesn't have all of\n\t * required keys.\n\t * @throws PinnacleException\n\t */\n\tpublic Translations getTranslationsAsObject(Parameter parameter) throws PinnacleException {\n\t\treturn Translations.parse(this.getTranslationsAsJson(parameter));\n\t}\n\n\t/**\n\t * Sends requests to 'GetPeriods' and returns its response.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Response\n\t * @throws PinnacleException\n\t */\n\tprivate Response getPeriods(Parameter parameter) throws PinnacleException {\n\t\tValidators.toGetPeriods(parameter);\n\t\tURL url = getUrl(Constants.BASE_URL + \"/v1/periods?\" + parameter.toUrlQuery());\n\t\tRequest request = Request.newRequest(url).get();\n\t\treturn request.execute(this.credentials);\n\t}\n\n\t/**\n\t * Sends requests to 'GetPeriods' and returns its response as JSON plain\n\t * text.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return JSON text\n\t * @throws PinnacleException\n\t */\n\tpublic String getPeriodsAsJson(Parameter parameter) throws PinnacleException {\n\t\treturn this.getPeriods(parameter).text();\n\t}\n\n\t/**\n\t * Sends requests to 'GetPeriods' and returns its response as mapped Object.\n\t * \n\t * @param parameter\n\t * - must be set proper values.\n\t * @return Periods - isEmpty will be set true when JSON text is empty and\n\t * isFlawed will be set when JSON text doesn't have all of required\n\t * keys.\n\t * @throws PinnacleException\n\t */\n\tpublic Periods getPeriodsAsObject(Parameter parameter) throws PinnacleException {\n\t\treturn Periods.parse(this.getPeriodsAsJson(parameter));\n\t}\n\n\t/**\n\t * Sends requests to 'GetCancellationReasons' and returns its response.\n\t * \n\t * @return Response\n\t * @throws PinnacleException\n\t */\n\tprivate Response getCancellationReasons() throws PinnacleException {\n\t\tURL url = getUrl(Constants.BASE_URL + \"/v1/cancellationreasons\");\n\t\tRequest request = Request.newRequest(url).get();\n\t\treturn request.execute(this.credentials);\n\t}\n\n\t/**\n\t * Sends requests to 'GetCancellationReasons' and returns its response as\n\t * JSON plain text.\n\t * \n\t * @return JSON text\n\t * @throws PinnacleException\n\t */\n\tpublic String getCancellationReasonsAsJson() throws PinnacleException {\n\t\treturn this.getCancellationReasons().text();\n\t}\n\n\t/**\n\t * Sends requests to 'GetCancellationReasons' and returns its response as\n\t * mapped Object.\n\t * \n\t * @return CancellationReasons - isEmpty will be set true when JSON text is\n\t * empty and isFlawed will be set when JSON text doesn't have all of\n\t * required keys.\n\t * @throws PinnacleException\n\t */\n\tpublic CancellationReasons getCancellationReasonsAsObject() throws PinnacleException {\n\t\treturn CancellationReasons.parse(this.getCancellationReasonsAsJson());\n\t}\n\n}", "@SuppressWarnings(\"serial\")\npublic class PinnacleException extends IOException {\n\n\tenum TYPE {\n\t\tCONNECTION_FAILED, ERROR_RETURNED, PARAMETER_INVALID, JSON_UNPARSABLE;\n\t}\n\n\tprivate TYPE errorType;\n\n\tpublic TYPE errorType() {\n\t\treturn this.errorType;\n\t}\n\n\tprivate String errorJson;\n\n\tpublic String errorJson() {\n\t\treturn this.errorJson;\n\t}\n\n\t/*\n\t * public GenericException parsedErrorJson () throws PinnacleException {\n\t * return GenericException.parse(this.errorJson); }\n\t */\n\tprivate int statusCode;\n\n\tpublic int statusCode() {\n\t\treturn this.statusCode;\n\t}\n\n\tprivate String unparsableJson;\n\n\tpublic String unparsableJson() {\n\t\treturn this.unparsableJson;\n\t}\n\n\tprivate PinnacleException(String message, TYPE errorType) {\n\t\tsuper(message);\n\t\tthis.errorType = errorType;\n\t}\n\n\tstatic PinnacleException connectionFailed(String message) {\n\t\treturn new PinnacleException(message, TYPE.CONNECTION_FAILED);\n\t}\n\n\tstatic PinnacleException errorReturned(int statusCode, String errorJson) {\n\t\tPinnacleException ex = new PinnacleException(\"API returned an error response:[\" + statusCode + \"] \" + errorJson,\n\t\t\t\tTYPE.ERROR_RETURNED);\n\t\tex.statusCode = statusCode;\n\t\tex.errorJson = errorJson;\n\t\treturn ex;\n\t}\n\n\tstatic PinnacleException parameterInvalid(String message) {\n\t\treturn new PinnacleException(message, TYPE.PARAMETER_INVALID);\n\t}\n\n\tstatic PinnacleException jsonUnparsable(String unparsableJson) {\n\t\tPinnacleException ex = new PinnacleException(\"Couldn't parse JSON: \" + unparsableJson, TYPE.JSON_UNPARSABLE);\n\t\tex.unparsableJson = unparsableJson;\n\t\treturn ex;\n\t}\n}", "public class PlacedBet extends AbstractDataObject {\n\n\tprivate PLACEBET_RESPONSE_STATUS status;\n\n\tpublic PLACEBET_RESPONSE_STATUS status() {\n\t\treturn this.status;\n\t}\n\n\tprivate Optional<PLACEBET_ERROR_CODE> errorCode;\n\n\tpublic Optional<PLACEBET_ERROR_CODE> errorCode() {\n\t\treturn this.errorCode;\n\t}\n\n\tprivate Optional<Long> betId;\n\n\tpublic Optional<Long> betId() {\n\t\treturn this.betId;\n\t}\n\n\tprivate String uniqueRequestId;\n\n\tpublic String uniqueRequestId() {\n\t\treturn this.uniqueRequestId;\n\t}\n\n\tprivate Boolean betterLineWasAccepted;\n\n\tpublic Boolean betterLineWasAccepted() {\n\t\treturn this.betterLineWasAccepted;\n\t}\n\n\tprivate Optional<BigDecimal> price;\n\n\tpublic Optional<BigDecimal> price() {\n\t\treturn this.price;\n\t}\n\n\tprivate PlacedBet(Json json) {\n\t\tthis.status = json.getAsString(\"status\").map(PLACEBET_RESPONSE_STATUS::fromAPI).orElse(null);\n\t\tthis.errorCode = json.getAsString(\"errorCode\").map(PLACEBET_ERROR_CODE::fromAPI);\n\t\tthis.betId = json.getAsLong(\"betId\");\n\t\tthis.uniqueRequestId = json.getAsString(\"uniqueRequestId\").orElse(null);\n\t\tthis.betterLineWasAccepted = json.getAsBoolean(\"betterLineWasAccepted\").orElse(null);\n\t\tthis.price = json.getAsBigDecimal(\"price\");\n\t\tthis.checkRequiredKeys();\n\t}\n\n\tprivate PlacedBet() {\n\t\tthis.isEmpty = true;\n\t}\n\n\tpublic static PlacedBet parse(String jsonText) throws PinnacleException {\n\t\treturn jsonText.equals(\"{}\") ? new PlacedBet() : new PlacedBet(Json.of(jsonText));\n\t}\n\n\t@Override\n\tboolean hasRequiredKeyWithNull() {\n\t\treturn this.status == null || this.uniqueRequestId == null || this.betterLineWasAccepted == null;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"PlacedBet [status=\" + status + \", errorCode=\" + errorCode + \", betId=\" + betId + \", uniqueRequestId=\"\n\t\t\t\t+ uniqueRequestId + \", betterLineWasAccepted=\" + betterLineWasAccepted + \", price=\" + price + \"]\";\n\t}\n}", "public enum BET_TYPE {\n\n\tMONEYLINE,\n\tTEAM_TOTAL_POINTS,\n\tSPREAD,\n\tTOTAL_POINTS,\n\tUNDEFINED;\n\n\tpublic String toAPI () {\n\t\treturn this.name();\n\t}\n\t\n\tpublic static BET_TYPE fromAPI (String text) {\n\t\ttry {\n\t\t\treturn BET_TYPE.valueOf(text);\n\t\t} catch (IllegalArgumentException e) {\n\t\t\treturn BET_TYPE.UNDEFINED;\n\t\t}\n\t}\n}", "public enum ODDS_FORMAT {\n\n\tAMERICAN,\n\tDECIMAL,\n\tHONGKONG,\n\tINDONESIAN,\n\tMALAY,\n\tUNDEFINED;\n\n\tpublic String toAPI () {\n\t\treturn this.name();\n\t}\n\t\n\tpublic static ODDS_FORMAT fromAPI (String text) {\n\t\ttry {\n\t\t\treturn ODDS_FORMAT.valueOf(text);\n\t\t} catch (IllegalArgumentException e) {\n\t\t\treturn ODDS_FORMAT.UNDEFINED;\n\t\t}\n\t}\n}", "public enum PERIOD {\n\t\n\tBADMINTON_MATCH(\"0\"),\n\tBADMINTON_1ST_GAME(\"1\"),\n\tBADMINTON_2ND_GAME(\"2\"),\n\tBADMINTON_3RD_GAME(\"3\"),\n\tBANDY_MATCH(\"0\"),\n\tBANDY_1ST_HALF(\"1\"),\n\tBANDY_2ND_HALF(\"2\"),\n\tBASEBALL_GAME(\"0\"),\n\tBASEBALL_1ST_HALF(\"1\"),\n\tBASEBALL_2ND_HALF(\"2\"),\n\tBASKETBALL_GAME(\"0\"),\n\tBASKETBALL_1ST_HALF(\"1\"),\n\tBASKETBALL_2ND_HALF(\"2\"),\n\tBASKETBALL_1ST_QUARTER(\"3\"),\n\tBASKETBALL_2ND_QUARTER(\"4\"),\n\tBASKETBALL_3RD_QUARTER(\"5\"),\n\tBASKETBALL_4TH_QUARTER(\"6\"),\n\tBEACH_VOLLEYBALL_MATCH(\"0\"),\n\tBEACH_VOLLEYBALL_1ST_SET(\"1\"),\n\tBEACH_VOLLEYBALL_2ND_SET(\"2\"),\n\tBEACH_VOLLEYBALL_3RD_SET(\"3\"),\n\tBOXING_FIGHT(\"0\"),\n\tCHESS_MATCH(\"0\"),\n\tCRICKET_MATCH(\"0\"),\n\tCRICKET_1ST_INNING(\"1\"),\n\tCRICKET_2ND_INNING(\"2\"),\n\tCURLING_GAME(\"0\"),\n\tCURLING_1ST_END(\"1\"),\n\tDARTS_MATCH(\"0\"),\n\tDARTS_1ST_SET(\"1\"),\n\tDARTS_2ND_SET(\"2\"),\n\tDARTS_3RD_SET(\"3\"),\n\tDARTS_4TH_SET(\"4\"),\n\tDARTS_5TH_SET(\"5\"),\n\tDARTS_LEGS_MATCH(\"0\"),\n\tDARTS_LEGS_1ST_LEG(\"1\"),\n\tDARTS_LEGS_2ND_LEG(\"2\"),\n\tDARTS_LEGS_3RD_LEG(\"3\"),\n\tDARTS_LEGS_4TH_LEG(\"4\"),\n\tDARTS_LEGS_5TH_LEG(\"5\"),\n\tDARTS_LEGS_6TH_LEG(\"6\"),\n\tE_SPORTS_MATCH(\"0\"),\n\tE_SPORTS_1ST_PERIOD(\"1\"),\n\tFIELD_HOCKEY_MATCH(\"0\"),\n\tFIELD_HOCKEY_1ST_HALF(\"1\"),\n\tFIELD_HOCKEY_2ND_HALF(\"2\"),\n\tFLOORBALL_MATCH(\"0\"),\n\tFLOORBALL_1ST_PERIOD(\"1\"),\n\tFLOORBALL_2ND_PERIOD(\"2\"),\n\tFLOORBALL_3RD_PERIOD(\"3\"),\n\tFOOTBALL_GAME(\"0\"),\n\tFOOTBALL_1ST_HALF(\"1\"),\n\tFOOTBALL_2ND_HALF(\"2\"),\n\tFOOTBALL_1ST_QUARTER(\"3\"),\n\tFOOTBALL_2ND_QUARTER(\"4\"),\n\tFOOTBALL_3RD_QUARTER(\"5\"),\n\tFOOTBALL_4TH_QUARTER(\"6\"),\n\tFUTSAL_MATCH(\"0\"),\n\tFUTSAL_1ST_HALF(\"1\"),\n\tFUTSAL_2ND_HALF(\"2\"),\n\tGOLF_MATCHUPS(\"0\"),\n\tHANDBALL_MATCH(\"0\"),\n\tHANDBALL_1ST_HALF(\"1\"),\n\tHANDBALL_2ND_HALF(\"2\"),\n\tHOCKEY_GAME(\"0\"),\n\tHOCKEY_1ST_PERIOD(\"1\"),\n\tHOCKEY_2ND_PERIOD(\"2\"),\n\tHOCKEY_3RD_PERIOD(\"3\"),\n\tHORSE_RACING_RACE(\"0\"),\n\tLACROSSE_MATCH(\"0\"),\n\tLACROSSE_1ST_HALF(\"1\"),\n\tLACROSSE_2ST_HALF(\"2\"),\n\tLACROSSE_1ST_QUARTER(\"3\"),\n\tLACROSSE_2ND_QUARTER(\"4\"),\n\tLACROSSE_3RD_QUARTER(\"5\"),\n\tLACROSSE_4TH_QUARTER(\"6\"),\n\tMIXED_MARTIAL_ARTS_FIGHT(\"0\"),\n\tMIXED_MARTIAL_ARTS_ROUND_1(\"1\"),\n\tMIXED_MARTIAL_ARTS_ROUND_2(\"2\"),\n\tMIXED_MARTIAL_ARTS_ROUND_3(\"3\"),\n\tMIXED_MARTIAL_ARTS_ROUND_4(\"4\"),\n\tMIXED_MARTIAL_ARTS_ROUND_5(\"5\"),\n\tOTHER_SPORTS_GAME(\"0\"),\n\tPOLITICS_ELECTION(\"0\"),\n\tRINK_HOCKEY_MATCH(\"0\"),\n\tRINK_HOCKEY_1ST_PERIOD(\"1\"),\n\tRINK_HOCKEY_2ND_PERIOD(\"2\"),\n\tRUGBY_LEAGUE_MATCH(\"0\"),\n\tRUGBY_LEAGUE_1ST_HALF(\"1\"),\n\tRUGBY_LEAGUE_2ND_HALF(\"2\"),\n\tRUGBY_UNION_MATCH(\"0\"),\n\tRUGBY_UNION_1ST_HALF(\"1\"),\n\tRUGBY_UNION_2ND_HALF(\"2\"),\n\tSNOOKER_MATCH(\"0\"),\n\tSNOOKER_1ST_FRAME(\"1\"),\n\tSOCCER_MATCH(\"0\"),\n\tSOCCER_1ST_HALF(\"1\"),\n\tSOCCER_2ND_HALF(\"2\"),\n\tSOFTBALL_GAME(\"0\"),\n\tSOFTBALL_1ST_HALF(\"1\"),\n\tSOFTBALL_2ST_HALF(\"2\"),\n\tSQUASH_MATCH(\"0\"),\n\tSQUASH_1ST_GAME(\"1\"),\n\tSQUASH_2ND_GAME(\"2\"),\n\tSQUASH_3RD_GAME(\"3\"),\n\tSQUASH_4TH_GAME(\"4\"),\n\tSQUASH_5TH_GAME(\"5\"),\n\tTABLE_TENNIS_MATCH(\"0\"),\n\tTABLE_TENNIS_1ST_GAME(\"1\"),\n\tTABLE_TENNIS_2ND_GAME(\"2\"),\n\tTABLE_TENNIS_3RD_GAME(\"3\"),\n\tTABLE_TENNIS_4TH_GAME(\"4\"),\n\tTABLE_TENNIS_5TH_GAME(\"5\"),\n\tTABLE_TENNIS_6TH_GAME(\"6\"),\n\tTENNIS_MATCH(\"0\"),\n\tTENNIS_1ST_SET_WINNER(\"1\"),\n\tTENNIS_2ND_SET_WINNER(\"2\"),\n\tTENNIS_3RD_SET_WINNER(\"3\"),\n\tTENNIS_4TH_SET_WINNER(\"4\"),\n\tTENNIS_5TH_SET_WINNER(\"5\"),\n\tVOLLEYBALL_MATCH(\"0\"),\n\tVOLLEYBALL_1ST_SET(\"1\"),\n\tVOLLEYBALL_2ND_SET(\"2\"),\n\tVOLLEYBALL_3RD_SET(\"3\"),\n\tVOLLEYBALL_4TH_SET(\"4\"),\n\tVOLLEYBALL_5TH_SET(\"5\"),\n\tVOLLEYBALL_POINTS_GAME(\"0\"),\n\tVOLLEYBALL_POINTS_1ST_SET(\"1\"),\n\tVOLLEYBALL_POINTS_2ND_SET(\"2\"),\n\tVOLLEYBALL_POINTS_3RD_SET(\"3\"),\n\tVOLLEYBALL_POINTS_4TH_SET(\"4\"),\n\tVOLLEYBALL_POINTS_5TH_SET(\"5\"),\n\tWATER_POLO_MATCH(\"0\"),\n\tWATER_POLO_1ST_PERIOD(\"1\"),\n\tWATER_POLO_2ND_PERIOD(\"2\"),\n\tWATER_POLO_3RD_PERIOD(\"3\"),\n\tWATER_POLO_4TH_PERIOD(\"4\"),\n\tPADEL_TENNIS_MATCH(\"0\"),\n\tPADEL_TENNIS_1ST_SET_WINNER(\"1\"),\n\tPADEL_TENNIS_2ND_SET_WINNER(\"2\"),\n\tPADEL_TENNIS_3RD_SET_WINNER(\"3\"),\n\tAUSSIE_RULES_FOOTBAL_GAME(\"0\"),\n\tAUSSIE_RULES_FOOTBAL_1ST_HALF(\"1\"),\n\tAUSSIE_RULES_FOOTBAL_2ND_HALF(\"2\"),\n\tAUSSIE_RULES_FOOTBAL_1ST_QUARTER(\"3\"),\n\tAUSSIE_RULES_FOOTBAL_2ND_QUARTER(\"4\"),\n\tAUSSIE_RULES_FOOTBAL_3RD_QUARTER(\"5\"),\n\tAUSSIE_RULES_FOOTBAL_4TH_QUARTER(\"6\"),\n\tAUSSIE_RULES_GAME(\"0\"),\n\tAUSSIE_RULES_1ST_HALF(\"1\"),\n\tAUSSIE_RULES_2ND_HALF(\"2\"),\n\tAUSSIE_RULES_1ST_QUARTER(\"3\"),\n\tAUSSIE_RULES_2ND_QUARTER(\"4\"),\n\tAUSSIE_RULES_3RD_QUARTER(\"5\"),\n\tAUSSIE_RULES_4TH_QUARTER(\"6\"),\n\tALPINE_SKIING_MATCHUPS(\"0\"),\n\tBIATHLON_MATCHUPS(\"0\"),\n\tSKI_JUMPING_MATCHUPS(\"0\"),\n\tCROSS_COUNTRY_MATCHUPS(\"0\"),\n\tFORMULA_1_MATCHUPS(\"0\"),\n\tCYCLING_MATCHUPS(\"0\"),\n\tBOBSLEIGH_MATCHUPS(\"0\"),\n\tFIGURE_SKATING_MATCHUPS(\"0\"),\n\tFREESTYLE_SKIING_MATCHUPS(\"0\"),\n\tLUGE_MATCHUPS(\"0\"),\n\tNORDIC_COMBINED_MATCHUPS(\"0\"),\n\tSHORT_TRACK_MATCHUPS(\"0\"),\n\tSKELETON_MATCHUPS(\"0\"),\n\tSNOW_BOARDING_MATCHUPS(\"0\"),\n\tSPEED_SKATING_MATCHUPS(\"0\");\n\n\tprivate final String value;\n\n\tprivate PERIOD(final String value) {\n\t\tthis.value = value;\n\t}\n\n\tpublic String toAPI() {\n\t\treturn this.value;\n\t}\n\n}", "public enum TEAM_TYPE {\n\n\tDRAW(\"Draw\"),\n\tTEAM_1(\"Team1\"),\n\tTEAM_2(\"Team2\"),\n\tUNDEFINED(\"undefined\");\n\n\tprivate final String value;\n\t\n\tprivate TEAM_TYPE (final String value) {\n\t\tthis.value = value;\n\t}\n\t\n\tpublic String toAPI () {\n\t\treturn this.value;\n\t}\n\t\n\tpublic static TEAM_TYPE fromAPI (String value) {\n\t\treturn Arrays.stream(TEAM_TYPE.values())\n\t\t .filter(e -> e.value.equals(value))\n\t\t .findAny()\n\t\t .orElse(TEAM_TYPE.UNDEFINED);\n\t}\n}", "public enum WIN_RISK_TYPE {\n\n\tRISK,\n\tWIN,\n\tUNDEFINED;\n\n\tpublic String toAPI () {\n\t\treturn this.name();\n\t}\n\t\n\tpublic static WIN_RISK_TYPE fromAPI (String text) {\n\t\ttry {\n\t\t\treturn WIN_RISK_TYPE.valueOf(text);\n\t\t} catch (IllegalArgumentException e) {\n\t\t\treturn WIN_RISK_TYPE.UNDEFINED;\n\t\t}\n\t}\n}" ]
import pinnacle.api.Parameter; import pinnacle.api.PinnacleAPI; import pinnacle.api.PinnacleException; import pinnacle.api.dataobjects.PlacedBet; import pinnacle.api.enums.BET_TYPE; import pinnacle.api.enums.ODDS_FORMAT; import pinnacle.api.enums.PERIOD; import pinnacle.api.enums.TEAM_TYPE; import pinnacle.api.enums.WIN_RISK_TYPE;
package examples; public class PlaceBet { public static void main(String[] args) throws PinnacleException { // settings String username = "yourUserName"; String password = "yourPassword"; PinnacleAPI api = PinnacleAPI.open(username, password); // parameter Parameter parameter = Parameter.newInstance(); parameter.uniqueRequestId(); parameter.acceptBetterLine(true); //parameter.customerReference(); parameter.oddsFormat(ODDS_FORMAT.DECIMAL); parameter.stake("100.0"); parameter.winRiskStake(WIN_RISK_TYPE.WIN); parameter.sportId(29); parameter.eventId(687863980); parameter.periodNumber(PERIOD.SOCCER_1ST_HALF);
parameter.betType(BET_TYPE.MONEYLINE);
4
suninformation/ymate-payment-v2
ymate-payment-alipay/src/main/java/net/ymate/payment/alipay/request/AliPayTradeRefundQuery.java
[ "public class AliPayAccountMeta implements Serializable {\n\n /**\n * 支付宝分配给开发者的应用ID\n */\n private String appId;\n\n /**\n * 同步返回地址,HTTP/HTTPS开头字符串\n */\n private String returnUrl;\n\n /**\n * 支付宝服务器主动通知商户服务器里指定的页面http/https路径\n */\n private String notifyUrl;\n\n /**\n * 返回格式\n */\n private String format;\n\n /**\n * 请求使用的编码格式\n */\n private String charset;\n\n /**\n * 商户生成签名字符串所使用的签名算法类型,目前支持RSA2和RSA,推荐使用RSA2\n */\n private IAliPay.SignType signType;\n\n /**\n * 私钥\n */\n private String privateKey;\n\n /**\n * 公钥\n */\n private String publicKey;\n\n public AliPayAccountMeta(String appId, String signType, String privateKey, String publicKey) {\n if (StringUtils.isBlank(appId)) {\n throw new NullArgumentException(\"app_id\");\n }\n if (StringUtils.isBlank(signType) || !StringUtils.equalsIgnoreCase(signType, IAliPay.Const.SIGN_TYPE_RSA2) && !StringUtils.equalsIgnoreCase(signType, IAliPay.Const.SIGN_TYPE_RSA)) {\n throw new IllegalArgumentException(\"sign_type\");\n }\n if (StringUtils.isBlank(privateKey)) {\n throw new NullArgumentException(\"private_key\");\n }\n if (StringUtils.isBlank(publicKey)) {\n throw new NullArgumentException(\"public_key\");\n }\n this.appId = appId;\n this.signType = IAliPay.SignType.valueOf(signType.toUpperCase());\n this.privateKey = privateKey;\n this.publicKey = publicKey;\n }\n\n public AliPayAccountMeta(String appId, String returnUrl, String notifyUrl, String signType, String privateKey, String publicKey) {\n this(appId, signType, privateKey, publicKey);\n //\n this.returnUrl = returnUrl;\n this.notifyUrl = notifyUrl;\n }\n\n public String getAppId() {\n return appId;\n }\n\n public String getReturnUrl() {\n return returnUrl;\n }\n\n public void setReturnUrl(String returnUrl) {\n this.returnUrl = returnUrl;\n }\n\n public String getNotifyUrl() {\n return notifyUrl;\n }\n\n public void setNotifyUrl(String notifyUrl) {\n this.notifyUrl = notifyUrl;\n }\n\n public String getFormat() {\n return format;\n }\n\n public void setFormat(String format) {\n this.format = format;\n }\n\n public String getCharset() {\n return charset;\n }\n\n public void setCharset(String charset) {\n this.charset = charset;\n }\n\n public IAliPay.SignType getSignType() {\n return signType;\n }\n\n public String getPrivateKey() {\n return privateKey;\n }\n\n public String getPublicKey() {\n return publicKey;\n }\n}", "public class AliPayBaseRequest<DATA extends IAliPayRequestData, RESPONSE extends IAliPayResponse> implements IAliPayRequest<RESPONSE> {\n\n private AliPayAccountMeta accountMeta;\n\n private String method;\n\n private String version;\n\n private DATA bizContent;\n\n private IAliPayResponseParser<RESPONSE> responseParser;\n\n private boolean needNotify;\n\n private boolean needReturn;\n\n public AliPayBaseRequest(AliPayAccountMeta accountMeta, String method, String version, DATA bizContent, boolean needNotify, boolean needReturn, IAliPayResponseParser<RESPONSE> responseParser) {\n if (accountMeta == null) {\n throw new NullArgumentException(\"accountMeta\");\n }\n if (StringUtils.isBlank(method)) {\n throw new NullArgumentException(\"method\");\n }\n if (bizContent == null) {\n throw new NullArgumentException(\"bizContent\");\n }\n if (responseParser == null) {\n throw new NullArgumentException(\"responseParser\");\n }\n //\n this.accountMeta = accountMeta;\n this.method = method;\n this.version = StringUtils.defaultIfBlank(version, \"1.0\");\n this.bizContent = bizContent;\n //\n this.needNotify = needNotify;\n this.needReturn = needReturn;\n //\n this.responseParser = responseParser;\n }\n\n @Override\n public IAliPayReqeustSender<RESPONSE> build() throws Exception {\n Map<String, String> _params = new HashMap<String, String>();\n //\n String _charset = StringUtils.defaultIfBlank(accountMeta.getCharset(), IAliPay.Const.CHARSET_UTF8);\n //\n _params.put(IAliPay.Const.APP_ID, accountMeta.getAppId());\n _params.put(IAliPay.Const.METHOD, method);\n _params.put(IAliPay.Const.CHARSET, _charset);\n _params.put(IAliPay.Const.FORMAT, accountMeta.getFormat());\n _params.put(IAliPay.Const.SIGN_TYPE, accountMeta.getSignType().name());\n _params.put(IAliPay.Const.TIMESTAMP, DateTimeUtils.formatTime(System.currentTimeMillis(), IAliPay.Const.DATE_TIME_FORMAT));\n _params.put(IAliPay.Const.VERSION, version);\n //\n if (needNotify) {\n if (StringUtils.isNotBlank(accountMeta.getNotifyUrl())) {\n _params.put(IAliPay.Const.NOTIFY_URL, accountMeta.getNotifyUrl());\n }\n }\n if (needReturn) {\n if (StringUtils.isNotBlank(accountMeta.getReturnUrl())) {\n _params.put(IAliPay.Const.RETURN_URL, accountMeta.getReturnUrl());\n }\n }\n //\n String _bizContentStr = JSON.toJSONString(this.bizContent.buildRequestParams(), SerializerFeature.QuoteFieldNames);\n _params.put(IAliPay.Const.BIZ_CONTENT_KEY, _bizContentStr);\n //\n String _signStr = SignatureUtils.sign(_params, accountMeta.getPrivateKey(), _charset, accountMeta.getSignType());\n _params.put(IAliPay.Const.SIGN, _signStr);\n //\n return new DefaultAliPayRequestSender<RESPONSE>(_params, _charset, this.responseParser);\n }\n\n @Override\n public AliPayAccountMeta getAccountMeta() {\n return accountMeta;\n }\n\n @Override\n public String getMethod() {\n return method;\n }\n\n @Override\n public String getVersion() {\n return version;\n }\n\n public DATA getBizContent() {\n return bizContent;\n }\n}", "public abstract class AliPayBaseResponse implements IAliPayResponse {\n\n private String code;\n\n private String msg;\n\n @JSONField(name = \"sub_code\")\n private String subCode;\n\n @JSONField(name = \"sub_msg\")\n private String subMsg;\n\n private String sign;\n\n @Override\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n @Override\n public String getMsg() {\n return msg;\n }\n\n public void setMsg(String msg) {\n this.msg = msg;\n }\n\n @Override\n public String getSubCode() {\n return subCode;\n }\n\n public void setSubCode(String subCode) {\n this.subCode = subCode;\n }\n\n @Override\n public String getSubMsg() {\n return subMsg;\n }\n\n public void setSubMsg(String subMsg) {\n this.subMsg = subMsg;\n }\n\n @Override\n public String getSign() {\n return sign;\n }\n\n @Override\n public void setSign(String sign) {\n this.sign = sign;\n }\n}", "public class AliPayBaseResponseParser<RESPONSE extends IAliPayResponse> implements IAliPayResponseParser<RESPONSE> {\n\n private static final Log _LOG = LogFactory.getLog(AliPayBaseResponseParser.class);\n\n private String __methodName;\n\n private Class<? extends RESPONSE> __class;\n\n public AliPayBaseResponseParser(Class<? extends RESPONSE> clazz, String methodName) {\n if (clazz == null) {\n throw new NullArgumentException(\"clazz\");\n }\n if (StringUtils.isBlank(methodName)) {\n throw new NullArgumentException(\"methodName\");\n }\n __class = clazz;\n __methodName = StringUtils.replace(methodName, \".\", \"_\") + IAliPay.Const.RESPONSE_SUFFIX;\n }\n\n @Override\n public RESPONSE parserResponse(String responseContent) throws Exception {\n JSONObject _result = JSON.parseObject(responseContent);\n String _sign = _result.getString(IAliPay.Const.SIGN);\n RESPONSE _data = _result.getObject(__methodName, __class);\n if (!StringUtils.equals(_data.getCode(), \"10000\")) {\n if (_LOG.isDebugEnabled()) {\n _LOG.debug(\"ResponseContent: \" + responseContent);\n }\n if (StringUtils.isNotBlank(_data.getSubCode()) && AliPayException.__ERRORS.containsKey(_data.getSubCode())) {\n throw new AliPayException(_data.getSubCode(), _data.getSubMsg());\n } else {\n throw new AliPayException(_data.getCode(), _data.getMsg());\n }\n } else {\n _data.setSign(_sign);\n }\n return _data;\n }\n}", "public class TradeRefundQueryData implements IAliPayRequestData {\n\n /**\n * 订单支付时传入的商户订单号,和支付宝交易号不能同时为空。 trade_no,out_trade_no如果同时存在优先取trade_no\n */\n private String outTradeNo;\n\n /**\n * 支付宝交易号, 和商户订单号不能同时为空\n */\n private String tradeNo;\n\n /**\n * 请求退款接口时,传入的退款请求号,如果在退款请求时未传入,则该值为创建交易时的外部交易号\n */\n private String outRequestNo;\n\n public TradeRefundQueryData(String outTradeNo, String tradeNo, String outRequestNo) {\n if (StringUtils.isBlank(outTradeNo) && StringUtils.isBlank(tradeNo)) {\n throw new NullArgumentException(\"outTradeNo or tradeNo\");\n }\n if (StringUtils.isBlank(outRequestNo)) {\n throw new NullArgumentException(\"outRequestNo\");\n }\n this.outTradeNo = outTradeNo;\n this.tradeNo = tradeNo;\n this.outRequestNo = outRequestNo;\n }\n\n @Override\n public Map<String, String> buildRequestParams() {\n Map<String, String> _params = new HashMap<String, String>();\n //\n _params.put(\"out_request_no\", outRequestNo);\n //\n if (StringUtils.isNotBlank(outTradeNo)) {\n _params.put(\"out_trade_no\", outTradeNo);\n }\n if (StringUtils.isNotBlank(tradeNo)) {\n _params.put(\"trade_no\", tradeNo);\n }\n //\n return _params;\n }\n\n public String getOutTradeNo() {\n return outTradeNo;\n }\n\n public void setOutTradeNo(String outTradeNo) {\n this.outTradeNo = outTradeNo;\n }\n\n public String getTradeNo() {\n return tradeNo;\n }\n\n public void setTradeNo(String tradeNo) {\n this.tradeNo = tradeNo;\n }\n\n public String getOutRequestNo() {\n return outRequestNo;\n }\n\n public void setOutRequestNo(String outRequestNo) {\n this.outRequestNo = outRequestNo;\n }\n}" ]
import com.alibaba.fastjson.annotation.JSONField; import net.ymate.payment.alipay.base.AliPayAccountMeta; import net.ymate.payment.alipay.base.AliPayBaseRequest; import net.ymate.payment.alipay.base.AliPayBaseResponse; import net.ymate.payment.alipay.base.AliPayBaseResponseParser; import net.ymate.payment.alipay.data.TradeRefundQueryData; import org.apache.commons.lang.StringUtils;
/* * Copyright 2007-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ymate.payment.alipay.request; /** * 统一收单交易退款查询 * <p> * 商户可使用该接口查询自已通过alipay.trade.refund提交的退款请求是否执行成功。 * 该接口的返回码10000,仅代表本次查询操作成功,不代表退款成功。 * 如果该接口返回了查询数据,则代表退款成功,如果没有查询到则代表未退款成功,可以调用退款接口进行重试。 * 重试时请务必保证退款请求号一致 * * @author 刘镇 ([email protected]) on 17/6/12 上午12:31 * @version 1.0 */ public class AliPayTradeRefundQuery extends AliPayBaseRequest<TradeRefundQueryData, AliPayTradeRefundQuery.Response> { private static final String METHOD_NAME = "alipay.trade.fastpay.refund.query";
public AliPayTradeRefundQuery(AliPayAccountMeta accountMeta, TradeRefundQueryData bizContent) {
0
NymphWeb/nymph
com/nymph/bean/core/ScannerNymphBeans.java
[ "public interface BeansComponent {\n\t/**\n\t * 根据注解类型获取组件Bean\n\t * @param anno\t指定的注解\n\t * @return\t\t对应的bean组件\n\t */\n\tOptional<Object> getComponent(Class<? extends Annotation> anno);\n\n\t/**\n\t * 获取拦截器链\n\t * @return\n\t */\n\tList<Interceptors> getInterceptors();\n\t/**\n\t * 过滤出组件的Bean\n\t * @param bean bean实例\n\t */\n\tvoid filter(Object bean);\n\n}", "public interface BeansHandler {\n\t/**\n\t * 在注册到bean容器之前的处理\n\t * @param beansClass bean的实例\n\t * @return 表示最终要存入容器的对象\n\t * @throws Exception \n\t */\n\tObject handlerBefore(Object bean);\n\t/**\n\t * 在注册到bean容器之后的处理\n\t * @param bean\tbean的实例\n\t */\n\tvoid handlerAfter(Object bean);\n\n}", "public class MapperInfoContainer {\n\n\tprivate final Map<String, MapperInfo> httpMap = new HashMap<>();\n\n\t/**\n\t * 对拥有@HTTP注解的bean进行处理主要是将@HTTP注解的value和@Request系列注解(@GET这种)\n\t * 的value拼接成一个完整的表示url地址的字符串, 然后存入map中, 这样当一个请求访问过来\n\t * 时只需要拿到这个请求的uri就可以直接获取到对应的Class和Method,如果用@UrlHolder\n\t * 注解这种占位符形式的url的话就只有遍历来寻找是否存在请求所映射的类了\n\t * @param clazz\t待处理的Class\n\t */\n\tpublic void filterAlsoSave(Class<?> clazz) throws IllegalAccessException {\n\t\tHTTP http = clazz.getAnnotation(HTTP.class);\n\t\t// 没有@HTTP注解的bean则不进行处理\n\t\tif (http == null)\n\t\t\treturn;\n\n\t\tfor (Method method : clazz.getDeclaredMethods()) {\n\t\t\tAnnotation[] annotations = method.getAnnotations();\n\t\t\tAnnotation request = AnnoUtil.get(annotations, Request.class);\n\t\t\tif (request != null) {\n\t\t\t\tmethodModifierCheck(method);\n\t\t\t\tString url = joinUrl(http.value(), request);\n\t\t\t\thttpMap.put(url, new MapperInfo(clazz.getName(), method));\n\t\t\t}\n\t\t}\n\t}\n\t/**\n\t * 将web映射对象的@HTTP注解和 方法的请求注解(@GET,@POST 等) 的值拼接成一个完整的url\n\t * @param spaceVal\t-@HTTP注解value方法的值\n\t * @param method\t方法上的请求方式注解(@GET或其他)\n\t * @return\t\t\t拼接好的url\n\t */\n\tprivate String joinUrl(String spaceVal, Annotation method) {\n\t\tString methodVal = AnnoUtil.getValueOfValueMethod(method);\n\t\treturn (\"/\".equals(spaceVal) || spaceVal.equals(\"\") ? \"\" :\n\t\t\t\tspaceVal.startsWith(\"/\") ? spaceVal : \"/\" + spaceVal)\n\t\t\t\t+ (!methodVal.startsWith(\"/\") ? \"/\" + methodVal : methodVal);\n\t}\n\n\t/**\n\t * 方法修饰符检查, 不为public时抛出异常\n\t * @param method\n\t * @throws IllegalAccessException\n\t */\n\tprivate void methodModifierCheck(Method method) throws IllegalAccessException {\n\t\tif (method.getModifiers() != Modifier.PUBLIC) {\n\t\t\tthrow new IllegalAccessException(\"方法的修饰符必须为public , method: \" + method.getName());\n\t\t}\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn String.valueOf(httpMap);\n\t}\n\n\tpublic MapperInfo getMapperInfo(String url) {\n\t\treturn httpMap.get(url);\n\t}\n\n\tpublic Set<Entry<String, MapperInfo>> getAllMapperInfo() {\n\t\treturn httpMap.entrySet();\n\t}\n\n\t/** 容器内存放的对象 */\n\tpublic class MapperInfo implements Cloneable {\n\t\t// web层映射类的类名\n\t\tprivate String name;\n\t\t// 路径对应的方法\n\t\tprivate Method method;\n\t\t// @UrlVal注解的value值\n\t\tprivate Map<String, String> placeHolder;\n\n\t\tpublic MapperInfo(String name, Method method) {\n\t\t\tthis.name = name;\n\t\t\tthis.method = method;\n\t\t}\n\n\t\tpublic MapperInfo() {}\n\n\t\tpublic String getName() {\n\t\t\treturn name;\n\t\t}\n\n\t\tpublic void setName(String name) {\n\t\t\tthis.name = name;\n\t\t}\n\n\t\tpublic Method getMethod() {\n\t\t\treturn method;\n\t\t}\n\n\t\tpublic void setMethod(Method method) {\n\t\t\tthis.method = method;\n\t\t}\n\n\t\tpublic Map<String, String> getPlaceHolder() {\n\t\t\treturn placeHolder;\n\t\t}\n\n\t\tpublic void setPlaceHolder(Map<String, String> placeHolder) {\n\t\t\tthis.placeHolder = placeHolder;\n\t\t}\n\n\t\tpublic MapperInfo initialize(Map<String, String> placeHolder) throws CloneNotSupportedException {\n\t\t\tMapperInfo httpBean = (MapperInfo)this.clone();\n\t\t\thttpBean.setPlaceHolder(placeHolder);\n\t\t\treturn httpBean;\n\t\t}\n\t}\n}", "public class Configuration {\n\t// xml的组件配置\n\tprivate List<Object> component;\n\t// 关于web的配置\n\tprivate WebConfig webConfig;\n\t// 关于包扫描的配置\n\tprivate List<String> scanner;\n\t// 指定bean处理器\n\tprivate String beansHandler;\n\t\n\tpublic Optional<String> getBeansHandler() {\n\t\treturn Optional.ofNullable(beansHandler);\n\t}\n\n\tpublic void setBeansHandler(String beansHandler) {\n\t\tthis.beansHandler = beansHandler;\n\t}\n\n\tpublic WebConfig getWebConfig() {\n\t\treturn webConfig;\n\t}\n\n\tpublic void setWebConfig(WebConfig webConfig) {\n\t\tthis.webConfig = webConfig;\n\t}\n\n\tpublic List<String> getScanner() {\n\t\treturn scanner == null ? Collections.emptyList() : scanner;\n\t}\n\n\tpublic void setScanner(List<String> scanner) {\n\t\tthis.scanner = scanner;\n\t}\n\n\tpublic List<Object> getComponent() {\n\t\treturn component == null ? Collections.emptyList() : component;\n\t}\n\n\tpublic void setComponent(List<Object> component) {\n\t\tthis.component = component;\n\t}\n\t\n\tpublic void addConfiguration(Configuration configuration) {\n\t\tif (component == null) {\n\t\t\tcomponent = new ArrayList<>();\n\t\t\tcomponent.addAll(configuration.getComponent());\n\t\t} else {\n\t\t\tcomponent.addAll(configuration.getComponent());\n\t\t}\n\t}\n\t\n}", "public abstract class AnnoUtil {\n\t\n\t/**\n\t * 判断一个注解数组是否包含某个注解相同类型的注解...\n\t * @param annos 注解数组\n\t * @param parent 目标注解\n\t * @return 注解数组中包含的注解\n\t */\n\tpublic static Annotation get(Annotation[] annos, Class<? extends Annotation> parent) {\n\t\tfor (Annotation annotation : annos) {\n\t\t\tif (annotation.annotationType().isAnnotationPresent(parent)) {\n\t\t\t\treturn annotation;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\t/**\n\t * 判断一个注解数组是否包含某个注解相同类型的注解...\n\t * @param annos 注解数组\n\t * @param parent 目标注解\n\t * @return 注解数组中包含的注解类型\n\t */\n\tpublic static Class<? extends Annotation> getType(Annotation[] annos, Class<? extends Annotation> parent) {\n\t\tfor (Annotation annotation : annos) {\n\t\t\tClass<? extends Annotation> annotationType = annotation.annotationType();\n\t\t\tif (annotationType.isAnnotationPresent(parent)) {\n\t\t\t\treturn annotationType;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t/**\n\t * 判断一个注解数组中是否包含某个注解\n\t * @param annos\t\t注解数组\n\t * @param parent\t目标注解\n\t * @return <code>true</code> <b>or</b> <code>false</code>\n\t */\n\tpublic static boolean exist(Annotation[] annos, Class<? extends Annotation> parent) {\n\t\tfor (Annotation annotation : annos) {\n\t\t\tif (annotation.annotationType().isAnnotationPresent(parent) || \n\t\t\t\tannotation.annotationType() == parent) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\t/**\n\t * 获取注解的指定方法的值\n\t * @param annotation 目标注解\n\t * @param methodName 注解的方法名\n\t * @return\t\t\t 结果\n\t */\n\tpublic static Object invoke(Annotation annotation, String methodName) {\n\t\ttry {\n\t\t\tClass<? extends Annotation> annotationType = annotation.annotationType();\n\t\t\treturn annotationType.getMethod(methodName).invoke(annotation);\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\treturn null;\n\t\t}\n\t}\n\t\n\t/**\n\t * 获取注解的value方法的值\n\t * @param annotation 目标注解\n\t * @return\t\t\t 结果\n\t */\n\tpublic static String getValueOfValueMethod(Annotation annotation) {\n\t\treturn String.valueOf(invoke(annotation, \"value\"));\n\t}\n\n}", "public abstract class BasicUtil {\n\t\n\t/**\n\t * 根据类路径反射创建对象\n\t * \n\t * @param classLocation\n\t * @return\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static <T> List<T> newInstance(List<String> classLocation) {\n\t\treturn classLocation.stream().map(ele -> (T)newInstance(ele)).collect(Collectors.toList());\n\t}\n\t\n\t/**\n\t * 根据类的全路径创建出一个对象\n\t * @param className 包名加类名的字符串\n\t * @return\t\t\t该类的对象\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic static <T> T newInstance(String className) {\n\t\ttry {\n\t\t\tClass<?> forName = Class.forName(className);\n\t\t\treturn (T) forName.newInstance();\n\t\t} catch (Exception e) {\n\t\t\tthrow new RuntimeException(e.getMessage());\n\t\t}\n\t}\n\n\t/**\n\t * 根据Class创建出一个实例\n\t * @param clazz\n\t * @param <T>\n\t * @return\n\t */\n\tpublic static <T> T newInstance(Class<T> clazz) {\n\t\ttry {\n\t\t\treturn clazz.newInstance();\n\t\t} catch (Exception e) {\n\t\t\tthrow new RuntimeException(e.getMessage());\n\t\t}\n\t}\n\n\t/**\n\t * 获取classpath路径下的资源\n\t * @param location\n\t * @return\n\t */\n\tpublic static String getSource(String location) {\n\t\tURL url = getDefaultClassLoad().getResource(location.replace(\".\", \"/\"));\n\t\treturn url == null ? \"\" : url.getPath();\n\t}\n\t\n\t/**\n\t * 获取默认的类加载器\n\t * @return\n\t */\n\tpublic static ClassLoader getDefaultClassLoad() {\n\t\tClassLoader loader = Thread.currentThread().getContextClassLoader();\n\t\tif (loader == null)\n\t\t\tloader = BasicUtil.class.getClassLoader();\n\t\tif (loader == null)\n\t\t\tloader = ClassLoader.getSystemClassLoader();\n\t\t\n\t\treturn loader;\n\t}\n\t/**\n\t * 将字符串转换成和字段对应的类型\n\t * \n\t * @param field\n\t * @param value\n\t * @return\n\t */\n\tpublic static Serializable convert(Field field, String value) {\n\t\treturn convert(field.getType(), value);\n\t}\n\n\t/**\n\t * 将字符串转成和给定Class对应的类型\n\t * @param clazz\n\t * @param value\n\t * @return\n\t */\n\tpublic static Serializable convert(Class<?> clazz, String value) {\n\t\tif (String.class == clazz) {\n\t\t\treturn value;\n\t\t} else if (int.class == clazz || Integer.class == clazz) {\n\t\t\treturn Integer.valueOf(value);\n\t\t} else if (boolean.class == clazz || Boolean.class == clazz) {\n\t\t\treturn Boolean.valueOf(value);\n\t\t} else if (double.class == clazz || Double.class == clazz) {\n\t\t\treturn Double.valueOf(value);\n\t\t} else if (long.class == clazz || Long.class == clazz) {\n\t\t\treturn Long.valueOf(value);\n\t\t} else if (byte.class == clazz || Byte.class == clazz) {\n\t\t\treturn Byte.valueOf(value);\n\t\t} else if (float.class == clazz || Float.class == clazz) {\n\t\t\treturn Float.valueOf(value);\n\t\t} else if (short.class == clazz || Short.class == clazz) {\n\t\t\treturn Short.valueOf(value);\n\t\t} else if (char.class == clazz || Character.class == clazz) {\n\t\t\treturn value.charAt(0);\n\t\t} \n\t\treturn null;\n\t}\n\n\t/**\n\t * 判断一个Class是否是基本类型(包含了String)\n\t * @param clazz\n\t * @return\n\t */\n\tpublic static boolean isCommonType(Class<?> clazz) {\n\t\treturn String.class == clazz ||\n\t\t\t\tint.class == clazz || Integer.class == clazz ||\n\t\t\t\tboolean.class == clazz || Boolean.class == clazz || \n\t\t\t\tdouble.class == clazz || Double.class == clazz ||\n\t\t\t\tlong.class == clazz || Long.class == clazz || \n\t\t\t\tbyte.class == clazz || Byte.class == clazz || \n\t\t\t\tfloat.class == clazz || Float.class == clazz || \n\t\t\t\tshort.class == clazz || Short.class == clazz || \n\t\t\t\tchar.class == clazz || Character.class == clazz;\n\t}\n\n\t/**\n\t * 判断一个Class是否是集合类型\n\t * \n\t * @param clazz\n\t * @return\n\t */\n\tpublic static boolean isCollection(Class<?> clazz) {\n\t\tif (Collection.class.isAssignableFrom(clazz))\n\t\t\treturn true;\n\t\treturn false;\n\t}\n\t/**\n\t * 判断一个Class是否是Map类型\n\t * @param clazz\n\t * @return\n\t */\n\tpublic static boolean isMap(Class<?> clazz) {\n\t\tif (Map.class.isAssignableFrom(clazz))\n\t\t\treturn true;\n\t\treturn false;\n\t}\n\n\t/**\n\t * 判断一个class是否是数组\n\t * @param clazz\n\t * @return\n\t */\n\tpublic static boolean isArray(Class<?> clazz) {\n\t\tif (clazz.getSimpleName().endsWith(\"[]\"))\n\t\t\treturn true;\n\t\treturn false;\n\t}\n\n\t/**\n\t * 判断一个字段是否是基本类型(包含String)\n\t * @param field\n\t * @return\n\t */\n\tpublic static boolean isCommonType(Field field) {\n\t\treturn isCommonType(field.getType());\n\t}\n\t/**\n\t * 关闭各种连接资源\n\t * \n\t * @param closeable\n\t */\n\tpublic static void closed(AutoCloseable... closeable) {\n\t\tfor (AutoCloseable autoCloseable : closeable) {\n\t\t\ttry {\n\t\t\t\tif (autoCloseable != null) {\n\t\t\t\t\tautoCloseable.close();\n\t\t\t\t}\n\t\t\t} catch (Exception e) {}\n\t\t}\n\t}\n\n\t/**\n\t * @备注: 判断集合的泛型是否是普通 类型\n\t * @param type\n\t * @return\n\t */\n\tpublic static boolean isCommonCollection(Type type) {\n\t\tif (type == null)\n\t\t\treturn false;\n\t\tClass<?> clazz = (Class<?>) ((ParameterizedType)type).getActualTypeArguments()[0];\n\t\tif (Number.class.isAssignableFrom(clazz) || String.class.isAssignableFrom(clazz)) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * @备注: 将一个String数组转换为clazz类型的list集合\n\t * @param clazz\n\t * @param array\n\t * @return\n\t */\n\tpublic static List<?> convertList(Class<?> clazz, String[] array) {\n\t\tif (String[].class.equals(clazz)) {\n\t\t\treturn Arrays.asList(array).stream().collect(Collectors.toList());\n\t\t} else if (Integer[].class.equals(clazz)) {\n\t\t\treturn Arrays.asList(array).stream().map(ele -> Integer.valueOf(ele)).collect(Collectors.toList());\n\t\t} else if (Long[].class.equals(clazz)) {\n\t\t\treturn Arrays.asList(array).stream().map(ele -> Long.valueOf(ele)).collect(Collectors.toList());\n\t\t} else if (Boolean[].class.equals(clazz)) {\n\t\t\treturn Arrays.asList(array).stream().map(ele -> Boolean.valueOf(ele)).collect(Collectors.toList());\n\t\t} else if (Double[].class.equals(clazz)) {\n\t\t\treturn Arrays.asList(array).stream().map(ele -> Double.valueOf(ele)).collect(Collectors.toList());\n\t\t}\n\t\treturn Collections.emptyList();\n\t}\n\t\n\t/**\n\t * 判断一个数组是否为空和长度是否为0\n\t * @param target\n\t * @return\n\t */\n\tpublic static boolean notNullAndLenNotZero(Object[] target) {\n\t\tif (target == null || target.length == 0) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\t/**\n\t * 如果目标对象为null则返回默认对象\n\t * @param target\t\n\t * @param defaults\n\t * @return\n\t */\n\tpublic static <T> T ifNullDefault(T target, T defaults) {\n\t\tif (target == null) {\n\t\t\treturn defaults;\n\t\t}\n\t\treturn target;\n\t}\n\t\n\t/**\n\t * 如果List为null则返回一个空的List\n\t * @param list\n\t * @return\n\t */\n\tpublic static <T>List<T> ofNullList(List<T> list) {\n\t\treturn list == null ? Collections.emptyList() : list;\n\t}\n\t\n}", "public abstract class JarUtil {\n\t\n\t/**\n\t * 根据给出的包路径寻找jar包\n\t * @param jarLocation\n\t * @return\n\t */\n\tpublic static JarFile getJarFile(String jarLocation) {\n\t\tString location = jarLocation.replace(\".\", \"/\");\n\t\tString source = BasicUtil.getSource(location);\n\t\tString replace = source.replace(\"file:/\", \"\")\n\t\t\t\t.replace(String.format(\"!/%s\", location), \"\");\n\t\t\n\t\ttry {\n\t\t\treturn new JarFile(replace);\n\t\t} catch (IOException e) {\n\t\t\treturn null;\n\t\t}\n\t}\n}" ]
import java.io.File; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.jar.JarEntry; import java.util.jar.JarFile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.nymph.annotation.Bean; import com.nymph.annotation.ConfigurationBean; import com.nymph.bean.BeansComponent; import com.nymph.bean.BeansHandler; import com.nymph.bean.web.MapperInfoContainer; import com.nymph.config.Configuration; import com.nymph.utils.AnnoUtil; import com.nymph.utils.BasicUtil; import com.nymph.utils.JarUtil;
package com.nymph.bean.core; /** * 根据包路径扫描所有的bean * @author NYMPH * @date 2017年9月26日2017年9月26日 */ public class ScannerNymphBeans { private static final Logger LOG = LoggerFactory.getLogger(ScannerNymphBeans.class); // 存放bean的容器 private Map<String, Object> beansContainer; // 处理http相关的bean映射信息
private MapperInfoContainer handler;
2
onepf/OPFPush
samples/pushchat/src/main/java/org/onepf/pushchat/ui/dialog/AddContactDialogFragment.java
[ "public class PushChatApplication extends Application {\n\n private static final String GCM_SENDER_ID = \"707033278505\";\n\n private static final String NOKIA_SENDER_ID = \"pushsample\";\n\n private String uuid;\n\n private RefWatcher refWatcher;\n\n @Override\n public void onCreate() {\n super.onCreate();\n refWatcher = LeakCanary.install(this);\n\n OPFLog.setEnabled(BuildConfig.DEBUG, true);\n OPFLog.logMethod();\n\n uuid = UuidGenerator.generateUuid(this);\n\n OPFLog.i(\"Generated uuid : %s\", uuid);\n final Configuration.Builder configBuilder = new Configuration.Builder()\n .addProviders(\n new GCMProvider(this, GCM_SENDER_ID),\n new ADMProvider(this),\n new NokiaNotificationsProvider(this, NOKIA_SENDER_ID)\n )\n .setSelectSystemPreferred(true)\n .setEventListener(new PushEventListener());\n\n OPFPush.init(this, configBuilder.build());\n OPFPush.getHelper().register();\n }\n\n public String getUUID() {\n return uuid;\n }\n\n public RefWatcher getRefWatcher() {\n return refWatcher;\n }\n}", "@SuppressWarnings(\"PMD.NonThreadSafeSingleton\")\npublic final class DatabaseHelper extends SQLiteOpenHelper {\n\n private static final String DATABASE_NAME = \"org.onepf.pushchat.db\";\n private static final int DATABASE_VERSION = 1;\n\n private static final String COMMA_SEP = \",\";\n\n private static final String SQL_CREATE_CONTACTS_TABLE =\n \"CREATE TABLE \" + ContactsContract.TABLE_NAME + \" ( \"\n + ContactEntry.ID + \" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL\" + COMMA_SEP\n + ContactEntry.NAME + \" TEXT\" + COMMA_SEP\n + ContactEntry.UUID + \" TEXT UNIQUE NOT NULL\"\n + \" )\";\n\n private static final String SQL_CREATE_MESSAGES_TABLE =\n \"CREATE TABLE \" + MessagesContract.TABLE_NAME + \" ( \"\n + MessageEntry.ID + \" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL\" + COMMA_SEP\n + MessageEntry.SENDER_UUID + \" TEXT NOT NULL\" + COMMA_SEP\n + MessageEntry.SENDER_NAME + \" TEXT\" + COMMA_SEP\n + MessageEntry.MESSAGE + \" TEXT NOT NULL\" + COMMA_SEP\n + MessageEntry.RECEIVED_TIME + \" LONG\"\n + \" )\";\n\n private static final String SQL_DELETE_CONTACTS_TABLE = \"DROP TABLE IF EXISTS \"\n + ContactsContract.TABLE_NAME;\n\n private static final String SQL_DELETE_MESSAGES_TABLE = \"DROP TABLE IF EXISTS \"\n + MessagesContract.TABLE_NAME;\n\n private static final int MESSAGE_OPERATION_TOKEN = 1;\n private static final int CONTACT_OPERATION_TOKEN = 2;\n private static final int QUERY_UUIDS_TOKEN = 3;\n private static final int QUERY_CONTACT_NAME_TOKEN = 4;\n\n @NonNull\n private final Context appContext;\n\n @NonNull\n private final AsyncQueryHandler asyncQueryHandler;\n\n private static volatile DatabaseHelper instance;\n\n private DatabaseHelper(@NonNull final Context context) {\n super(context, DATABASE_NAME, null, DATABASE_VERSION);\n this.appContext = context.getApplicationContext();\n this.asyncQueryHandler = new CommonAsyncQueryHandler(context.getContentResolver());\n }\n\n public static DatabaseHelper getInstance(@NonNull final Context context) {\n if (instance == null) {\n synchronized (DatabaseHelper.class) {\n if (instance == null) {\n instance = new DatabaseHelper(context);\n }\n }\n }\n\n return instance;\n }\n\n @Override\n public void onCreate(@NonNull final SQLiteDatabase sqLiteDatabase) {\n sqLiteDatabase.execSQL(SQL_CREATE_CONTACTS_TABLE);\n sqLiteDatabase.execSQL(SQL_CREATE_MESSAGES_TABLE);\n }\n\n @Override\n public void onUpgrade(@NonNull final SQLiteDatabase sqLiteDatabase,\n final int oldVersion,\n final int newVersion) {\n if (oldVersion < newVersion) {\n sqLiteDatabase.execSQL(SQL_DELETE_MESSAGES_TABLE);\n sqLiteDatabase.execSQL(SQL_DELETE_CONTACTS_TABLE);\n onCreate(sqLiteDatabase);\n }\n }\n\n public void addMessage(@NonNull final Message message) {\n new QueryContactNameQueryHandler(appContext.getContentResolver(), queryContactNameCallback(message))\n .startQuery(\n QUERY_CONTACT_NAME_TOKEN,\n null,\n ContactsContract.TABLE_URI,\n new String[]{ContactEntry.NAME},\n ContactEntry.UUID + \"=?\",\n new String[]{message.getSenderUuid()},\n null\n );\n }\n\n private QueryContactNameQueryHandler.QueryContactNameCallback queryContactNameCallback(\n @NonNull final Message message\n ) {\n return new QueryContactNameQueryHandler.QueryContactNameCallback() {\n @Override\n public void onComplete(@NonNull final String name) {\n final ContentValues contentValues = new ContentValues();\n contentValues.put(MessageEntry.SENDER_UUID, message.getSenderUuid());\n contentValues.put(MessageEntry.SENDER_NAME, name);\n contentValues.put(MessageEntry.MESSAGE, message.getMessageText());\n contentValues.put(MessageEntry.RECEIVED_TIME, message.getReceivedTime());\n\n asyncQueryHandler.startInsert(MESSAGE_OPERATION_TOKEN, null, MessagesContract.TABLE_URI, contentValues);\n }\n };\n }\n\n public void deleteMessages() {\n asyncQueryHandler.startDelete(MESSAGE_OPERATION_TOKEN, null, MessagesContract.TABLE_URI, null, null);\n }\n\n public void addContact(@NonNull final Contact contact) {\n final String contactName = contact.getName();\n final String contactUuid = contact.getUuid();\n\n final ContentValues contactContentValues = new ContentValues();\n contactContentValues.put(ContactEntry.NAME, contactName);\n contactContentValues.put(ContactEntry.UUID, contactUuid);\n\n asyncQueryHandler.startInsert(CONTACT_OPERATION_TOKEN, null, ContactsContract.TABLE_URI, contactContentValues);\n\n final ContentValues messageContentValues = new ContentValues();\n messageContentValues.put(MessageEntry.SENDER_NAME, contactName);\n asyncQueryHandler.startUpdate(\n MESSAGE_OPERATION_TOKEN,\n null,\n MessagesContract.TABLE_URI,\n messageContentValues,\n MessageEntry.SENDER_UUID + \"=?\",\n new String[]{contactUuid}\n );\n }\n\n public void deleteContact(final long id) {\n asyncQueryHandler.startDelete(\n CONTACT_OPERATION_TOKEN,\n null,\n ContactsContract.TABLE_URI,\n ContactEntry.ID + \"=?\",\n new String[]{String.valueOf(id)}\n );\n }\n\n public void queryAllContactsUuids(@NonNull final QueryContactsUuidsCallback callback) {\n new ContactsUuidsAsyncQueryHandler(appContext.getContentResolver(), callback).startQuery(\n QUERY_UUIDS_TOKEN,\n null,\n ContactsContract.TABLE_URI,\n new String[]{ContactEntry.UUID},\n null,\n null,\n null\n );\n }\n\n public boolean isUuidAdded(@NonNull final String uuid) {\n final Cursor cursor = getReadableDatabase().query(\n ContactsContract.TABLE_NAME,\n new String[]{ContactEntry.UUID},\n ContactEntry.UUID + \"=?\",\n new String[]{uuid},\n null,\n null,\n null\n );\n\n final boolean isUuidAdded = cursor.getCount() > 0;\n cursor.close();\n return isUuidAdded;\n }\n\n public boolean isContactsTableEmpty() {\n final Cursor cursor = getReadableDatabase().query(\n ContactsContract.TABLE_NAME,\n new String[]{ContactEntry.ID},\n null,\n null,\n null,\n null,\n null\n );\n\n final boolean isEmpty = cursor.getCount() == 0;\n cursor.close();\n return isEmpty;\n }\n\n @NonNull\n public String querySenderUuidById(final long id) {\n final Cursor cursor = getReadableDatabase().query(\n MessagesContract.TABLE_NAME,\n new String[]{MessageEntry.SENDER_UUID},\n MessageEntry.ID + \"=?\",\n new String[]{String.valueOf(id)},\n null,\n null,\n null\n );\n\n String senderUuid = \"\";\n if (cursor.getCount() != 0) {\n cursor.moveToFirst();\n senderUuid = cursor.getString(cursor.getColumnIndexOrThrow(MessageEntry.SENDER_UUID));\n }\n cursor.close();\n return senderUuid;\n }\n\n public static class ContactsUuidsAsyncQueryHandler extends AsyncQueryHandler {\n\n @NonNull\n private final QueryContactsUuidsCallback callback;\n\n public ContactsUuidsAsyncQueryHandler(@NonNull final ContentResolver contentResolver,\n @NonNull final QueryContactsUuidsCallback callback) {\n super(contentResolver);\n this.callback = callback;\n }\n\n @Override\n protected void onQueryComplete(final int token, final Object cookie, final Cursor cursor) {\n final Set<String> uuids = new HashSet<>();\n if (token == QUERY_UUIDS_TOKEN) {\n cursor.moveToFirst();\n while (true) {\n uuids.add(cursor.getString(cursor.getColumnIndexOrThrow(ContactEntry.UUID)));\n if (cursor.isLast()) {\n break;\n }\n cursor.moveToNext();\n }\n }\n cursor.close();\n callback.onComplete(uuids);\n }\n\n public interface QueryContactsUuidsCallback {\n\n void onComplete(@NonNull final Set<String> uuids);\n }\n }\n\n private static class CommonAsyncQueryHandler extends AsyncQueryHandler {\n\n public CommonAsyncQueryHandler(@NonNull final ContentResolver contentResolver) {\n super(contentResolver);\n }\n }\n\n private static class QueryContactNameQueryHandler extends AsyncQueryHandler {\n\n @NonNull\n private final QueryContactNameCallback callback;\n\n public QueryContactNameQueryHandler(@NonNull final ContentResolver contentResolver,\n @NonNull final QueryContactNameCallback callback) {\n super(contentResolver);\n this.callback = callback;\n }\n\n @Override\n protected void onQueryComplete(final int token, final Object cookie, final Cursor cursor) {\n if (token == QUERY_CONTACT_NAME_TOKEN) {\n if (cursor.getCount() > 0) {\n cursor.moveToFirst();\n callback.onComplete(cursor.getString(cursor.getColumnIndexOrThrow(ContactEntry.NAME)));\n } else {\n callback.onComplete(\"\");\n }\n }\n cursor.close();\n }\n\n private interface QueryContactNameCallback {\n\n void onComplete(@NonNull final String name);\n }\n }\n}", "public final class Contact {\n\n @NonNull\n private final String name;\n\n @NonNull\n private final String uuid;\n\n public Contact(@NonNull final String name, @NonNull final String uuid) {\n this.name = name;\n this.uuid = uuid;\n }\n\n @NonNull\n public String getName() {\n return name;\n }\n\n @NonNull\n public String getUuid() {\n return uuid;\n }\n}", "public final class ExistResponse {\n\n @SerializedName(\"exist\")\n public final boolean exist;\n\n public ExistResponse(final boolean exist) {\n this.exist = exist;\n }\n}", "public final class NetworkController {\n\n private final PushService pushService;\n\n @SuppressWarnings(\"PMD.AccessorClassGeneration\")\n private static final class NetworkControllerHolder {\n private static final NetworkController INSTANCE = new NetworkController();\n }\n\n private NetworkController() {\n final RestAdapter restAdapter = new RestAdapter.Builder()\n .setEndpoint(\"https://onepf-opfpush.appspot.com/_ah/api/opfpush/v1\")\n .setConverter(new GsonConverter(new GsonBuilder().create()))\n .build();\n pushService = restAdapter.create(PushService.class);\n }\n\n public static NetworkController getInstance() {\n return NetworkControllerHolder.INSTANCE;\n }\n\n public void register(@NonNull final Context context,\n @NonNull final String providerName,\n @NonNull final String registrationId) {\n\n final RegistrationRequestBody body =\n new RegistrationRequestBody(getUuid(context), providerName, registrationId);\n\n pushService.register(body, registrationCallback(context, providerName, registrationId));\n }\n\n public void unregister(@NonNull final Context context) {\n final UnregistrationRequestBody body = new UnregistrationRequestBody(getUuid(context));\n pushService.unregister(body, unregistrationCallback(context));\n }\n\n public void pushMessage(@NonNull final Context context,\n @NonNull final String message,\n @NonNull final Callback<PushMessageResponse> pushMessageCallback) {\n DatabaseHelper.getInstance(context).queryAllContactsUuids(\n new QueryContactsUuidsCallback() {\n @Override\n public void onComplete(@NonNull final Set<String> uuids) {\n final PushMessageRequestBody body = new PushMessageRequestBody(\n uuids,\n getUuid(context),\n message\n );\n pushService.push(body, pushMessageCallback);\n }\n });\n }\n\n public void exist(@NonNull final String uuid,\n @NonNull final Callback<ExistResponse> callback) {\n pushService.exist(uuid, callback);\n }\n\n public void getTopics(@NonNull final Context context,\n @NonNull final Callback<TopicsResponse> callback) {\n pushService.getTopics(getUuid(context), callback);\n }\n\n public void subscribe(@NonNull final Context context,\n @NonNull final String topic,\n @NonNull final Callback<Object> callback) {\n pushService.subscribe(new SubscribeOrUnsubscribeRequestBody(topic, getUuid(context)), callback);\n }\n\n public void unsubscribe(@NonNull final Context context,\n @NonNull final String topic,\n @NonNull final Callback<Object> callback) {\n pushService.unsubscribe(new SubscribeOrUnsubscribeRequestBody(topic, getUuid(context)), callback);\n }\n\n private String getUuid(@NonNull final Context context) {\n final PushChatApplication application = (PushChatApplication) context.getApplicationContext();\n return application.getUUID();\n }\n\n private Callback<RegistrationResponse> registrationCallback(\n @NonNull final Context context,\n @NonNull final String providerName,\n @NonNull final String registrationId\n ) {\n return new Callback<RegistrationResponse>() {\n @Override\n public void success(@NonNull final RegistrationResponse registrationResponse,\n @NonNull final Response response) {\n OPFLog.logMethod(registrationResponse, response);\n\n StateController.putRegIdSavedOnServerValue(context, true);\n\n final Intent registeredIntent = new Intent(REGISTERED_ACTION);\n registeredIntent.putExtra(PROVIDER_NAME_EXTRA_KEY, providerName);\n registeredIntent.putExtra(Constants.REGISTRATION_ID_EXTRA_KEY, registrationId);\n context.sendBroadcast(registeredIntent);\n context.sendBroadcast(new Intent(HIDE_PROGRESS_BAR_ACTION));\n }\n\n @Override\n public void failure(@NonNull final RetrofitError error) {\n OPFLog.logMethod(error);\n OPFLog.e(error.getMessage());\n register(context, providerName, registrationId);\n }\n };\n }\n\n private Callback<UnregistrationResponse> unregistrationCallback(\n @NonNull final Context context\n ) {\n return new Callback<UnregistrationResponse>() {\n @Override\n public void success(@NonNull final UnregistrationResponse unregistrationResponse,\n @NonNull final Response response) {\n OPFLog.logMethod(unregistrationResponse, response);\n\n StateController.putRegIdSavedOnServerValue(context, false);\n\n context.sendBroadcast(new Intent(UNREGISTERED_ACTION));\n context.sendBroadcast(new Intent(HIDE_PROGRESS_BAR_ACTION));\n }\n\n @Override\n public void failure(@NonNull final RetrofitError error) {\n OPFLog.logMethod(error);\n OPFLog.e(error.getMessage());\n unregister(context);\n }\n };\n }\n}" ]
import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.Dialog; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import org.onepf.pushchat.PushChatApplication; import org.onepf.pushchat.R; import org.onepf.pushchat.db.DatabaseHelper; import org.onepf.pushchat.model.db.Contact; import org.onepf.pushchat.model.response.ExistResponse; import org.onepf.pushchat.retrofit.NetworkController; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response;
/* * Copyright 2012-2015 One Platform Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onepf.pushchat.ui.dialog; /** * @author Roman Savin * @since 06.05.2015 */ public class AddContactDialogFragment extends DialogFragment { public static final String TAG = AddContactDialogFragment.class.getName(); public static AddContactDialogFragment newInstance() { return new AddContactDialogFragment(); } @SuppressLint("InflateParams") @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity()); final View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_add_contact, null); final EditText nameEditText = (EditText) view.findViewById(R.id.contact_name_edit_text); final EditText uuidEditText = (EditText) view.findViewById(R.id.uuid_edit_text); final TextView errorTextView = (TextView) view.findViewById(R.id.error_text); final Button okButton = (Button) view.findViewById(R.id.ok_button); uuidEditText.addTextChangedListener(new AfterTextChangedWatcher() { @Override public void afterTextChanged(final Editable s) { okButton.setEnabled(!s.toString().isEmpty() && !nameEditText.getText().toString().isEmpty()); } }); nameEditText.addTextChangedListener(new AfterTextChangedWatcher() { @Override public void afterTextChanged(final Editable s) { okButton.setEnabled(!s.toString().isEmpty() && !uuidEditText.getText().toString().isEmpty()); } }); okButton.setOnClickListener(onClickListener(nameEditText, uuidEditText, errorTextView)); dialogBuilder.setTitle(getString(R.string.add_contact_title)) .setView(view); return dialogBuilder.create(); } private View.OnClickListener onClickListener(@NonNull final EditText nameEditText, @NonNull final EditText uuidEditText, @NonNull final TextView errorTextView) { return new View.OnClickListener() { @Override public void onClick(View v) { //Perform checks before adding contact to DB final String name = nameEditText.getText().toString(); final String uuid = uuidEditText.getText().toString(); final PushChatApplication application = (PushChatApplication) getActivity().getApplication(); final String ownUuid = application.getUUID(); if (ownUuid.equals(uuid)) { errorTextView.setText(R.string.own_uuid_error); errorTextView.setVisibility(View.VISIBLE); } else if (DatabaseHelper.getInstance(getActivity()).isUuidAdded(uuid)) { errorTextView.setText(R.string.uuid_already_added); errorTextView.setVisibility(View.VISIBLE); } else { //check existing and add to DB errorTextView.setVisibility(View.GONE);
NetworkController.getInstance().exist(uuid, existCallback(name, uuid, errorTextView));
4
DDoS/JICI
src/main/java/ca/sapon/jici/lexer/literal/NullLiteral.java
[ "public class Environment {\n // TODO make me thread safe\n private static final Map<String, Class<?>> DEFAULT_CLASSES = new HashMap<>();\n private final Map<String, Class<?>> classes = new LinkedHashMap<>(DEFAULT_CLASSES);\n private final Map<String, Variable> variables = new LinkedHashMap<>();\n\n static {\n for (String name : ReflectionUtil.JAVA_LANG_CLASSES) {\n try {\n DEFAULT_CLASSES.put(name, Class.forName(\"java.lang.\" + name));\n } catch (ClassNotFoundException e) {\n throw new IllegalStateException(\"class java.lang.\" + name + \" not found\");\n }\n }\n }\n\n public void importClass(Class<?> _class) {\n final String name = _class.getCanonicalName();\n // Validate the type of class\n if (_class.isPrimitive()) {\n throw new UnsupportedOperationException(\"Can't import a primitive type: \" + name);\n }\n if (_class.isArray()) {\n throw new UnsupportedOperationException(\"Can't import an array class: \" + name);\n }\n if (_class.isAnonymousClass()) {\n throw new UnsupportedOperationException(\"Can't import an anonymous class: \" + name);\n }\n // Check for existing import under the same simple name\n final String simpleName = _class.getSimpleName();\n final Class<?> existing = classes.get(simpleName);\n // ignore cases where the classes are the same as redundant imports are allowed\n if (existing != null && _class != existing) {\n throw new UnsupportedOperationException(\"Class \" + name + \" clashes with existing import \" + existing.getCanonicalName());\n }\n // Add the class to the imports\n classes.put(simpleName, _class);\n }\n\n public Class<?> findClass(Identifier name) {\n return classes.get(name.getSource());\n }\n\n public Class<?> getClass(Identifier name) {\n final Class<?> _class = findClass(name);\n if (_class == null) {\n throw new UnsupportedOperationException(\"Class \" + name.getSource() + \" does not exist\");\n }\n return _class;\n }\n\n public Collection<Class<?>> getClasses() {\n return classes.values();\n }\n\n public boolean hasClass(Identifier name) {\n return classes.containsKey(name.getSource());\n }\n\n public boolean hasClass(Class<?> _class) {\n return classes.containsValue(_class);\n }\n\n public void declareVariable(Identifier name, LiteralType type, Value value) {\n if (hasVariable(name)) {\n throw new UnsupportedOperationException(\"Variable \" + name.getSource() + \" is already declared\");\n }\n variables.put(name.getSource(), new Variable(name, type, value));\n }\n\n public LiteralType getVariableType(Identifier name) {\n return findVariable(name).getType();\n }\n\n public Value getVariable(Identifier name) {\n return findVariable(name).getValue();\n }\n\n public Collection<Variable> getVariables() {\n return variables.values();\n }\n\n public void setVariable(Identifier name, Value value) {\n findVariable(name).setValue(value);\n }\n\n public boolean hasVariable(Identifier name) {\n return variables.containsKey(name.getSource());\n }\n\n private Variable findVariable(Identifier name) {\n final String nameString = name.getSource();\n final Variable variable = variables.get(nameString);\n if (variable == null) {\n throw new UnsupportedOperationException(\"Variable \" + nameString + \" does not exist\");\n }\n return variable;\n }\n\n public static class Variable {\n private final Identifier name;\n private final LiteralType type;\n private Value value;\n\n private Variable(Identifier name, LiteralType type, Value value) {\n this.name = name;\n this.type = type;\n this.value = value;\n }\n\n public Identifier getName() {\n return name;\n }\n\n public LiteralType getType() {\n return type;\n }\n\n public boolean initialized() {\n return value != null;\n }\n\n public Value getValue() {\n if (!initialized()) {\n throw new UnsupportedOperationException(\"Variable \" + name.getSource() + \" has not been initialized\");\n }\n return value;\n }\n\n private void setValue(Value value) {\n this.value = value;\n }\n }\n}", "public class EvaluatorException extends SourceException {\n private static final long serialVersionUID = 1;\n\n public EvaluatorException(Throwable cause, SourceIndexed indexed) {\n this(\"EvaluatorException\", cause, indexed);\n }\n\n public EvaluatorException(String error, Throwable cause, SourceIndexed indexed) {\n super(getMessage(error, cause), cause, null, indexed.getStart(), indexed.getEnd());\n }\n\n public EvaluatorException(String error, SourceIndexed indexed) {\n this(error, indexed.getStart(), indexed.getEnd());\n }\n\n public EvaluatorException(String error, int start, int end) {\n super(error, null, start, end);\n }\n\n private static String getMessage(String error, Throwable cause) {\n if (cause == null) {\n return error;\n }\n String causeMessage = cause.getMessage();\n if (causeMessage != null) {\n causeMessage = causeMessage.trim();\n if (causeMessage.isEmpty()) {\n causeMessage = null;\n }\n }\n error += \" (\" + cause.getClass().getSimpleName();\n if (causeMessage != null) {\n error += \": \" + causeMessage;\n }\n return getMessage(error, cause.getCause()) + \")\";\n }\n}", "public interface Value {\n boolean asBoolean();\n\n byte asByte();\n\n short asShort();\n\n char asChar();\n\n int asInt();\n\n long asLong();\n\n float asFloat();\n\n double asDouble();\n\n Object asObject();\n\n String asString();\n\n <T> T as();\n\n ValueKind getKind();\n\n boolean isPrimitive();\n\n Class<?> getTypeClass();\n\n String toString();\n}", "public enum ValueKind {\n BOOLEAN(Boolean.class) {\n @Override\n public BooleanValue defaultValue() {\n return BooleanValue.defaultValue();\n }\n\n @Override\n public BooleanValue wrap(Object object) {\n if (object instanceof Boolean) {\n return BooleanValue.of((Boolean) object);\n }\n throw new UnsupportedOperationException(\"Cannot convert an object to a boolean\");\n }\n\n @Override\n public BooleanValue convert(Value value) {\n return BooleanValue.of(value.asBoolean());\n }\n },\n BYTE(Byte.class) {\n @Override\n public ByteValue defaultValue() {\n return ByteValue.defaultValue();\n }\n\n @Override\n public ByteValue wrap(Object object) {\n if (object instanceof Byte) {\n return ByteValue.of((Byte) object);\n }\n throw new UnsupportedOperationException(\"Cannot convert an object to a byte\");\n }\n\n @Override\n public ByteValue convert(Value value) {\n return ByteValue.of(value.asByte());\n }\n },\n SHORT(Short.class) {\n @Override\n public ShortValue defaultValue() {\n return ShortValue.defaultValue();\n }\n\n @Override\n public ShortValue wrap(Object object) {\n if (object instanceof Short) {\n return ShortValue.of((Short) object);\n }\n throw new UnsupportedOperationException(\"Cannot convert an object to a short\");\n }\n\n @Override\n public ShortValue convert(Value value) {\n return ShortValue.of(value.asShort());\n }\n },\n CHAR(Character.class) {\n @Override\n public CharValue defaultValue() {\n return CharValue.defaultValue();\n }\n\n @Override\n public CharValue wrap(Object object) {\n if (object instanceof Character) {\n return CharValue.of((Character) object);\n }\n throw new UnsupportedOperationException(\"Cannot convert an object to a char\");\n }\n\n @Override\n public CharValue convert(Value value) {\n return CharValue.of(value.asChar());\n }\n },\n INT(Integer.class) {\n @Override\n public IntValue defaultValue() {\n return IntValue.defaultValue();\n }\n\n @Override\n public IntValue wrap(Object object) {\n if (object instanceof Integer) {\n return IntValue.of((Integer) object);\n }\n throw new UnsupportedOperationException(\"Cannot convert an object to an int\");\n }\n\n @Override\n public IntValue convert(Value value) {\n return IntValue.of(value.asInt());\n }\n },\n LONG(Long.class) {\n @Override\n public LongValue defaultValue() {\n return LongValue.defaultValue();\n }\n\n @Override\n public LongValue wrap(Object object) {\n if (object instanceof Long) {\n return LongValue.of((Long) object);\n }\n throw new UnsupportedOperationException(\"Cannot convert an object to a long\");\n }\n\n @Override\n public LongValue convert(Value value) {\n return LongValue.of(value.asLong());\n }\n },\n FLOAT(Float.class) {\n @Override\n public FloatValue defaultValue() {\n return FloatValue.defaultValue();\n }\n\n @Override\n public FloatValue wrap(Object object) {\n if (object instanceof Float) {\n return FloatValue.of((Float) object);\n }\n throw new UnsupportedOperationException(\"Cannot convert an object to a float\");\n }\n\n @Override\n public FloatValue convert(Value value) {\n return FloatValue.of(value.asFloat());\n }\n },\n DOUBLE(Double.class) {\n @Override\n public DoubleValue defaultValue() {\n return DoubleValue.defaultValue();\n }\n\n @Override\n public DoubleValue wrap(Object object) {\n if (object instanceof Double) {\n return DoubleValue.of((Double) object);\n }\n throw new UnsupportedOperationException(\"Cannot convert an object to a double\");\n }\n\n @Override\n public DoubleValue convert(Value value) {\n return DoubleValue.of(value.asDouble());\n }\n },\n VOID(Void.class) {\n @Override\n public Value defaultValue() {\n return VoidValue.defaultValue();\n }\n\n @Override\n public Value wrap(Object object) {\n if (object instanceof Void) {\n return VoidValue.THE_VOID;\n }\n throw new UnsupportedOperationException(\"Cannot convert an object to void\");\n }\n\n @Override\n public Value convert(Value value) {\n throw new UnsupportedOperationException(\"Cannot convert anything to void\");\n }\n },\n OBJECT(null) {\n @Override\n public ObjectValue defaultValue() {\n return ObjectValue.defaultValue();\n }\n\n @Override\n public ObjectValue wrap(Object object) {\n return ObjectValue.of(object);\n }\n\n @Override\n public ObjectValue convert(Value value) {\n return ObjectValue.of(value.asObject());\n }\n };\n private static final Map<Class<?>, ValueKind> BOX_TO_KIND = new HashMap<>();\n private final Class<?> boxingClass;\n\n static {\n for (ValueKind kind : values()) {\n BOX_TO_KIND.put(kind.getBoxingClass(), kind);\n }\n }\n\n ValueKind(Class<?> boxingClass) {\n this.boxingClass = boxingClass;\n }\n\n public abstract Value defaultValue();\n\n public abstract Value wrap(Object object);\n\n public abstract Value convert(Value value);\n\n public Class<?> getBoxingClass() {\n return boxingClass;\n }\n\n public static Value unbox(Object box) {\n final ValueKind kind = BOX_TO_KIND.get(box.getClass());\n if (kind == null) {\n return null;\n }\n if (kind == OBJECT) {\n throw new UnsupportedOperationException(\"Not a box type: \" + box.getClass().getSimpleName());\n }\n return kind.wrap(box);\n }\n}", "public class NullType extends SingleReferenceType {\n public static final NullType THE_NULL = new NullType();\n\n private NullType() {\n }\n\n @Override\n public String getName() {\n return \"null\";\n }\n\n @Override\n public boolean isArray() {\n return false;\n }\n\n @Override\n public boolean isReifiable() {\n return true;\n }\n\n @Override\n public boolean convertibleTo(Type to) {\n // Null can be converted to any reference type (so anything that isn't a primitive type)\n return !to.isPrimitive();\n }\n\n @Override\n public boolean isNull() {\n return true;\n }\n\n @Override\n public NullType getErasure() {\n return this;\n }\n\n @Override\n public boolean isUncheckedConversion(Type to) {\n return false;\n }\n\n @Override\n public NullType capture() {\n return this;\n }\n\n @Override\n public Set<LiteralReferenceType> getDirectSuperTypes() {\n throw new UnsupportedOperationException(\"Can't list the direct super types of the null types as it is the universal set\");\n }\n\n @Override\n public Set<LiteralReferenceType> getSuperTypes() {\n return getDirectSuperTypes();\n }\n\n @Override\n public SingleReferenceType asArray(int dimensions) {\n throw new UnsupportedOperationException(\"Cannot have an array of the null type\");\n }\n\n @Override\n public Object newArray(int length) {\n throw new UnsupportedOperationException(\"Cannot instantiate an array of the null type\");\n }\n\n @Override\n public Object newArray(int[] lengths) {\n throw new UnsupportedOperationException(\"Cannot instantiate an array of the null type\");\n }\n\n @Override\n public ComponentType getComponentType() {\n throw new UnsupportedOperationException(\"Not an array type\");\n }\n\n @Override\n public LiteralReferenceType getInnerClass(String name, TypeArgument[] typeArguments) {\n throw new UnsupportedOperationException(\"Cannot dereference the null type\");\n }\n\n @Override\n public ConstructorCallable getConstructor(TypeArgument[] typeArguments, Type[] arguments) {\n throw new UnsupportedOperationException(\"Cannot dereference the null type\");\n }\n\n @Override\n public ClassVariable getField(String name) {\n throw new UnsupportedOperationException(\"Cannot dereference the null type\");\n }\n\n @Override\n public Callable getMethod(String name, TypeArgument[] typeArguments, Type[] arguments) {\n throw new UnsupportedOperationException(\"Cannot dereference the null type\");\n }\n\n @Override\n public boolean equals(Object other) {\n return this == other || other instanceof NullType;\n }\n\n @Override\n public int hashCode() {\n return 9849851;\n }\n}", "public interface Type {\n String getName();\n\n ValueKind getKind();\n\n boolean isVoid();\n\n boolean isNull();\n\n boolean isPrimitive();\n\n boolean isNumeric();\n\n boolean isIntegral();\n\n boolean isBoolean();\n\n boolean isArray();\n\n boolean isReference();\n\n boolean isReifiable();\n\n boolean convertibleTo(Type to);\n\n Type capture();\n\n @Override\n String toString();\n\n @Override\n boolean equals(Object other);\n\n @Override\n int hashCode();\n}", "public enum TokenID {\n IDENTIFIER(TokenGroup.IDENTIFIER),\n KEYWORD_ASSERT(TokenGroup.UNSPECIFIED),\n KEYWORD_IF(TokenGroup.UNSPECIFIED),\n KEYWORD_ELSE(TokenGroup.UNSPECIFIED),\n KEYWORD_WHILE(TokenGroup.UNSPECIFIED),\n KEYWORD_DO(TokenGroup.UNSPECIFIED),\n KEYWORD_FOR(TokenGroup.UNSPECIFIED),\n KEYWORD_BREAK(TokenGroup.UNSPECIFIED),\n KEYWORD_CONTINUE(TokenGroup.UNSPECIFIED),\n KEYWORD_SWITCH(TokenGroup.UNSPECIFIED),\n KEYWORD_CASE(TokenGroup.UNSPECIFIED),\n KEYWORD_DEFAULT(TokenGroup.UNSPECIFIED),\n KEYWORD_RETURN(TokenGroup.UNSPECIFIED),\n KEYWORD_THROW(TokenGroup.UNSPECIFIED),\n KEYWORD_TRY(TokenGroup.UNSPECIFIED),\n KEYWORD_CATCH(TokenGroup.UNSPECIFIED),\n KEYWORD_FINALLY(TokenGroup.UNSPECIFIED),\n KEYWORD_VOID(TokenGroup.UNSPECIFIED),\n KEYWORD_BOOLEAN(TokenGroup.PRIMITIVE_TYPE),\n KEYWORD_BYTE(TokenGroup.PRIMITIVE_TYPE),\n KEYWORD_SHORT(TokenGroup.PRIMITIVE_TYPE),\n KEYWORD_CHAR(TokenGroup.PRIMITIVE_TYPE),\n KEYWORD_INT(TokenGroup.PRIMITIVE_TYPE),\n KEYWORD_LONG(TokenGroup.PRIMITIVE_TYPE),\n KEYWORD_FLOAT(TokenGroup.PRIMITIVE_TYPE),\n KEYWORD_DOUBLE(TokenGroup.PRIMITIVE_TYPE),\n KEYWORD_CLASS(TokenGroup.CLASS_TYPE),\n KEYWORD_INTERFACE(TokenGroup.CLASS_TYPE),\n KEYWORD_ENUM(TokenGroup.CLASS_TYPE),\n KEYWORD_EXTENDS(TokenGroup.UNSPECIFIED),\n KEYWORD_IMPLEMENTS(TokenGroup.UNSPECIFIED),\n KEYWORD_SUPER(TokenGroup.SELF_REFERENCE),\n KEYWORD_THIS(TokenGroup.SELF_REFERENCE),\n KEYWORD_PACKAGE(TokenGroup.UNSPECIFIED),\n KEYWORD_IMPORT(TokenGroup.UNSPECIFIED),\n KEYWORD_PUBLIC(TokenGroup.ACCESS_MODIFIER),\n KEYWORD_PROTECTED(TokenGroup.ACCESS_MODIFIER),\n KEYWORD_PRIVATE(TokenGroup.ACCESS_MODIFIER),\n KEYWORD_THROWS(TokenGroup.UNSPECIFIED),\n KEYWORD_ABSTRACT(TokenGroup.OTHER_MODIFIER),\n KEYWORD_STRICTFP(TokenGroup.OTHER_MODIFIER),\n KEYWORD_TRANSIENT(TokenGroup.OTHER_MODIFIER),\n KEYWORD_VOLATILE(TokenGroup.OTHER_MODIFIER),\n KEYWORD_FINAL(TokenGroup.OTHER_MODIFIER),\n KEYWORD_STATIC(TokenGroup.OTHER_MODIFIER),\n KEYWORD_SYNCHRONIZED(TokenGroup.OTHER_MODIFIER),\n KEYWORD_NATIVE(TokenGroup.OTHER_MODIFIER),\n KEYWORD_NEW(TokenGroup.UNSPECIFIED),\n KEYWORD_INSTANCEOF(TokenGroup.BINARY_OPERATOR),\n KEYWORD_GOTO(TokenGroup.UNUSED),\n KEYWORD_CONST(TokenGroup.UNUSED),\n SYMBOL_PERIOD(TokenGroup.CALL_OPERATOR),\n SYMBOL_COMMA(TokenGroup.UNSPECIFIED),\n SYMBOL_COLON(TokenGroup.UNSPECIFIED),\n SYMBOL_SEMICOLON(TokenGroup.UNSPECIFIED),\n SYMBOL_PLUS(TokenGroup.ADD_OPERATOR),\n SYMBOL_MINUS(TokenGroup.ADD_OPERATOR),\n SYMBOL_MULTIPLY(TokenGroup.MULTIPLY_OPERATOR),\n SYMBOL_DIVIDE(TokenGroup.MULTIPLY_OPERATOR),\n SYMBOL_MODULO(TokenGroup.MULTIPLY_OPERATOR),\n SYMBOL_INCREMENT(TokenGroup.UNARY_OPERATOR),\n SYMBOL_DECREMENT(TokenGroup.UNARY_OPERATOR),\n SYMBOL_BITWISE_AND(TokenGroup.BINARY_OPERATOR),\n SYMBOL_BITWISE_OR(TokenGroup.BINARY_OPERATOR),\n SYMBOL_BITWISE_NOT(TokenGroup.UNARY_OPERATOR),\n SYMBOL_BITWISE_XOR(TokenGroup.BINARY_OPERATOR),\n SYMBOL_LOGICAL_LEFT_SHIFT(TokenGroup.SHIFT_OPERATOR),\n SYMBOL_ARITHMETIC_RIGHT_SHIFT(TokenGroup.SHIFT_OPERATOR),\n SYMBOL_LOGICAL_RIGHT_SHIFT(TokenGroup.SHIFT_OPERATOR),\n SYMBOL_BOOLEAN_NOT(TokenGroup.UNARY_OPERATOR),\n SYMBOL_BOOLEAN_AND(TokenGroup.BINARY_OPERATOR),\n SYMBOL_BOOLEAN_OR(TokenGroup.BINARY_OPERATOR),\n SYMBOL_LESSER(TokenGroup.COMPARISON_OPERATOR),\n SYMBOL_GREATER(TokenGroup.COMPARISON_OPERATOR),\n SYMBOL_GREATER_OR_EQUAL(TokenGroup.COMPARISON_OPERATOR),\n SYMBOL_LESSER_OR_EQUAL(TokenGroup.COMPARISON_OPERATOR),\n SYMBOL_EQUAL(TokenGroup.EQUAL_OPERATOR),\n SYMBOL_NOT_EQUAL(TokenGroup.EQUAL_OPERATOR),\n SYMBOL_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_ADD_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_SUBTRACT_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_MULTIPLY_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_DIVIDE_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_REMAINDER_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_BITWISE_AND_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_BITWISE_OR_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_BITWISE_XOR_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_LOGICAL_LEFT_SHIFT_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_ARITHMETIC_RIGHT_SHIFT_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_LOGICAL_RIGHT_SHIFT_ASSIGN(TokenGroup.ASSIGNMENT),\n SYMBOL_OPEN_PARENTHESIS(TokenGroup.UNSPECIFIED),\n SYMBOL_CLOSE_PARENTHESIS(TokenGroup.UNSPECIFIED),\n SYMBOL_OPEN_BRACKET(TokenGroup.UNSPECIFIED),\n SYMBOL_CLOSE_BRACKET(TokenGroup.UNSPECIFIED),\n SYMBOL_OPEN_BRACE(TokenGroup.UNSPECIFIED),\n SYMBOL_CLOSE_BRACE(TokenGroup.UNSPECIFIED),\n SYMBOL_DOUBLE_SLASH(TokenGroup.COMMENT_DELIMITER),\n SYMBOL_SLASH_STAR(TokenGroup.COMMENT_DELIMITER),\n SYMBOL_STAR_SLASH(TokenGroup.COMMENT_DELIMITER),\n SYMBOL_QUESTION_MARK(TokenGroup.UNSPECIFIED),\n SYMBOL_DOUBLE_PERIOD(TokenGroup.UNUSED),\n SYMBOL_TRIPLE_PERIOD(TokenGroup.UNSPECIFIED),\n SYMBOL_DOUBLE_COLON(TokenGroup.UNSPECIFIED),\n SYMBOL_ARROW(TokenGroup.UNSPECIFIED),\n SYMBOL_AT(TokenGroup.UNSPECIFIED),\n LITERAL_TRUE(TokenGroup.LITERAL),\n LITERAL_FALSE(TokenGroup.LITERAL),\n LITERAL_CHARACTER(TokenGroup.LITERAL),\n LITERAL_NULL(TokenGroup.LITERAL),\n LITERAL_STRING(TokenGroup.LITERAL),\n LITERAL_DOUBLE(TokenGroup.LITERAL),\n LITERAL_FLOAT(TokenGroup.LITERAL),\n LITERAL_INT(TokenGroup.LITERAL),\n LITERAL_LONG(TokenGroup.LITERAL);\n private final TokenGroup group;\n\n TokenID(TokenGroup group) {\n this.group = group;\n }\n\n public TokenGroup getGroup() {\n return group;\n }\n}" ]
import ca.sapon.jici.evaluator.Environment; import ca.sapon.jici.evaluator.EvaluatorException; import ca.sapon.jici.evaluator.value.Value; import ca.sapon.jici.evaluator.value.ValueKind; import ca.sapon.jici.evaluator.type.NullType; import ca.sapon.jici.evaluator.type.Type; import ca.sapon.jici.lexer.TokenID;
/* * This file is part of JICI, licensed under the MIT License (MIT). * * Copyright (c) 2015-2016 Aleksi Sapon <http://sapon.ca/jici/> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package ca.sapon.jici.lexer.literal; public class NullLiteral extends Literal { private static final String nullSource = "null"; private NullLiteral(int index) { super(TokenID.LITERAL_NULL, nullSource, index); } @Override public boolean asBoolean() { throw new EvaluatorException("Cannot convert an object to a boolean", this); } @Override public byte asByte() { throw new EvaluatorException("Cannot convert an object to a byte", this); } @Override public short asShort() { throw new EvaluatorException("Cannot convert an object to a short", this); } @Override public char asChar() { throw new EvaluatorException("Cannot convert an object to a char", this); } @Override public int asInt() { throw new EvaluatorException("Cannot convert an object to an int", this); } @Override public long asLong() { throw new EvaluatorException("Cannot convert an object to a long", this); } @Override public float asFloat() { throw new EvaluatorException("Cannot convert an object to a float", this); } @Override public double asDouble() { throw new EvaluatorException("Cannot convert an object to a double", this); } @Override public Object asObject() { return null; } @Override public String asString() { return "null"; } @Override public <T> T as() { return null; } @Override public ValueKind getKind() { return ValueKind.OBJECT; } @Override public boolean isPrimitive() { return false; } @Override public Class<?> getTypeClass() { return null; } @Override public Type getType(Environment environment) { return NullType.THE_NULL; } public static boolean is(String source) { return nullSource.equals(source); } @Override
public Value getValue(Environment environment) {
2
Vauff/Maunz-Discord
src/com/vauff/maunzdiscord/threads/ReactionAddThread.java
[ "public abstract class AbstractCommand\n{\n\t/**\n\t * Holds all messages as keys which await a reaction by a specific user.\n\t * The values hold an instance of {@link Await}\n\t */\n\tpublic static final HashMap<Snowflake, Await> AWAITED = new HashMap<>();\n\n\t/**\n\t * Enum holding the different bot permissions commands may require to use\n\t *\n\t * EVERYONE - No permission required\n\t * GUILD_ADMIN - ADMINISTRATOR or MANAGE_GUILD permission required\n\t * BOT_ADMIN - User must be listed in config.json botOwners\n\t */\n\tpublic enum BotPermission\n\t{\n\t\tEVERYONE,\n\t\tGUILD_ADMIN,\n\t\tBOT_ADMIN\n\t}\n\n\t/**\n\t * Defines aliases that can be used to trigger the command.\n\t * The main alias should also be defined in here\n\t *\n\t * @return A string array of all valid aliases\n\t */\n\tpublic abstract String[] getAliases();\n\n\t/**\n\t * Helper method that returns the primary (first) alias\n\t *\n\t * @return The primary alias\n\t */\n\tpublic final String getFirstAlias()\n\t{\n\t\treturn getAliases()[0];\n\t}\n\n\t/**\n\t * An array of CommandHelp objects that hold information about the command to display in /help\n\t *\n\t * @return An array of {@link CommandHelp}\n\t */\n\tpublic abstract CommandHelp[] getHelp();\n\n\t/**\n\t * Permission level required to use this command\n\t *\n\t * @return The permission level\n\t */\n\tpublic abstract BotPermission getPermissionLevel();\n}", "public abstract class AbstractLegacyCommand<M extends MessageCreateEvent> extends AbstractCommand\n{\n\t/**\n\t * Executes this command\n\t *\n\t * @param event The event by which this command got triggered\n\t * @throws Exception If an exception gets thrown by any implementing methods\n\t */\n\tpublic abstract void exe(M event, MessageChannel channel, User author) throws Exception;\n\n\t/**\n\t * Gets called when a reaction is added to a message defined prior in {@link AbstractLegacyCommand#waitForReaction(Snowflake, Snowflake)}\n\t *\n\t * @param event The event holding information about the added reaction\n\t * @param message The Message that was reacted to\n\t */\n\tpublic void onReactionAdd(ReactionAddEvent event, Message message) throws Exception\n\t{\n\t}\n\n\t/**\n\t * Sets up this command to await a reaction by the user who triggered this command\n\t *\n\t * @param messageID The message which should get reacted on\n\t * @param userID The user who triggered this command\n\t */\n\tpublic final void waitForReaction(Snowflake messageID, Snowflake userID)\n\t{\n\t\tAWAITED.put(messageID, new Await(userID, this));\n\t}\n}", "public abstract class AbstractSlashCommand<M extends ChatInputInteractionEvent> extends AbstractCommand\n{\n\t/**\n\t * Executes this command\n\t *\n\t * @param interaction The interaction that executing this command creates\n\t * @throws Exception If an exception gets thrown by any implementing methods\n\t */\n\tpublic abstract void exe(M interaction, Guild guild, MessageChannel channel, User author) throws Exception;\n\n\t/**\n\t * Gets called when a reaction is added to a message defined prior in {@link AbstractSlashCommand#waitForReaction(Snowflake, Snowflake, ChatInputInteractionEvent)}\n\t *\n\t * @param reactionEvent The event holding information about the added reaction\n\t * @param interactionEvent The interaction event that triggered this\n\t * @param message The Message that was reacted to\n\t */\n\tpublic void onReactionAdd(ReactionAddEvent reactionEvent, ChatInputInteractionEvent interactionEvent, Message message) throws Exception\n\t{\n\t}\n\n\t/**\n\t * Returns the ApplicationCommandRequest object for this command\n\t */\n\tpublic abstract ApplicationCommandRequest getCommand();\n\n\t/**\n\t * Defines the name used to trigger the command.\n\t *\n\t * @return A string containing the name of the command\n\t */\n\tpublic abstract String getName();\n\n\t/**\n\t * Sets up this command to await a reaction by the user who triggered this command\n\t *\n\t * @param messageID The message which should get reacted on\n\t * @param userID The user who triggered this command\n\t */\n\tpublic final void waitForReaction(Snowflake messageID, Snowflake userID, ChatInputInteractionEvent event)\n\t{\n\t\tAWAITED.put(messageID, new Await(userID, this, event));\n\t}\n\n\t@Override\n\tpublic final String[] getAliases()\n\t{\n\t\treturn new String[] { getName() };\n\t}\n\n\t@Override\n\tpublic final CommandHelp[] getHelp()\n\t{\n\t\tif (getCommand().options().isAbsent())\n\t\t\treturn new CommandHelp[] { new CommandHelp(\"\", getCommand().description().get()) };\n\n\t\tList<CommandHelp> commandHelps = new ArrayList<>();\n\t\tCommandHelp commandHelp = new CommandHelp(\"\", getCommand().description().get());\n\t\tboolean noSubCmds = true;\n\n\t\tfor (ApplicationCommandOptionData option : getCommand().options().get())\n\t\t{\n\t\t\tif (option.type() == ApplicationCommandOption.Type.SUB_COMMAND.getValue())\n\t\t\t{\n\t\t\t\tnoSubCmds = false;\n\n\t\t\t\tcommandHelps.add(parseHelpSubCommand(option, null));\n\t\t\t}\n\t\t\telse if (option.type() == ApplicationCommandOption.Type.SUB_COMMAND_GROUP.getValue())\n\t\t\t{\n\t\t\t\tnoSubCmds = false;\n\n\t\t\t\tif (option.options().isAbsent())\n\t\t\t\t\tcontinue;\n\n\t\t\t\tfor (ApplicationCommandOptionData subCmd : option.options().get())\n\t\t\t\t\tcommandHelps.add(parseHelpSubCommand(subCmd, option.name()));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (option.required().isAbsent() || !option.required().get())\n\t\t\t\t\tcommandHelp.setArguments(commandHelp.getArguments() + \"[\" + option.name() + \"] \");\n\t\t\t\telse\n\t\t\t\t\tcommandHelp.setArguments(commandHelp.getArguments() + \"<\" + option.name() + \"> \");\n\t\t\t}\n\t\t}\n\n\t\tif (noSubCmds)\n\t\t{\n\t\t\tcommandHelp.setArguments(commandHelp.getArguments().trim());\n\t\t\tcommandHelps.add(commandHelp);\n\t\t}\n\n\t\treturn commandHelps.toArray(new CommandHelp[commandHelps.size()]);\n\t}\n\n\tprivate CommandHelp parseHelpSubCommand(ApplicationCommandOptionData subCommand, String rootName)\n\t{\n\t\tCommandHelp commandHelp = new CommandHelp(\"\", subCommand.description());\n\n\t\tif (!Objects.isNull(rootName))\n\t\t\tcommandHelp.setArguments(rootName + \" \");\n\n\t\tcommandHelp.setArguments(commandHelp.getArguments() + subCommand.name() + \" \");\n\n\t\tif (!subCommand.options().isAbsent())\n\t\t{\n\t\t\tfor (ApplicationCommandOptionData option : subCommand.options().get())\n\t\t\t{\n\t\t\t\tif (option.required().isAbsent() || !option.required().get())\n\t\t\t\t\tcommandHelp.setArguments(commandHelp.getArguments() + \"[\" + option.name() + \"] \");\n\t\t\t\telse\n\t\t\t\t\tcommandHelp.setArguments(commandHelp.getArguments() + \"<\" + option.name() + \"> \");\n\t\t\t}\n\t\t}\n\n\t\tcommandHelp.setArguments(commandHelp.getArguments().trim());\n\n\t\treturn commandHelp;\n\t}\n}", "public class Logger\n{\n\tpublic static org.apache.logging.log4j.Logger log;\n\n\tpublic static void onChatInputInteraction(ChatInputInteractionEvent event)\n\t{\n\t\ttry\n\t\t{\n\t\t\tString userName = event.getInteraction().getUser().getUsername();\n\t\t\tString userId = event.getInteraction().getUser().getId().asString();\n\t\t\tString channelId = event.getInteraction().getChannel().block().getId().asString();\n\t\t\tString channelName = ((GuildChannel) event.getInteraction().getChannel().block()).getName();\n\t\t\tString guildName = event.getInteraction().getGuild().block().getName();\n\t\t\tString guildId = event.getInteraction().getGuild().block().getId().asString();\n\t\t\tString cmdName = event.getInteraction().getCommandInteraction().get().getName().get();\n\n\t\t\tLogger.log.debug(userName + \" (\" + userId + \") | \" + guildName + \" (\" + guildId + \") | #\" + channelName + \" (\" + channelId + \") | used /\" + cmdName + getArguments(event.getInteraction().getCommandInteraction().get().getOptions()));\n\t\t}\n\t\tcatch (Exception e)\n\t\t{\n\t\t\tLogger.log.error(\"\", e);\n\t\t}\n\t}\n\n\tpublic static void onMessageCreate(MessageCreateEvent event)\n\t{\n\t\ttry\n\t\t{\n\t\t\tif (event.getMessage().getAuthor().isPresent() && !event.getMessage().getFlags().contains(Message.Flag.LOADING))\n\t\t\t\tlogMessage(event.getMessage());\n\t\t}\n\t\tcatch (Exception e)\n\t\t{\n\t\t\tLogger.log.error(\"\", e);\n\t\t}\n\t}\n\n\tpublic static void onMessageUpdate(MessageUpdateEvent event)\n\t{\n\t\ttry\n\t\t{\n\t\t\tif (event.getMessage().block().getAuthor().isPresent() && event.getOld().isPresent() && event.getOld().get().getFlags().contains(Message.Flag.LOADING))\n\t\t\t{\n\t\t\t\tMessage msg;\n\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tmsg = event.getMessage().block();\n\t\t\t\t}\n\t\t\t\tcatch (Exception e)\n\t\t\t\t{\n\t\t\t\t\t// Message is not available to us, unsure why this is so frequent on this event\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tlogMessage(msg);\n\t\t\t}\n\t\t}\n\t\tcatch (Exception e)\n\t\t{\n\t\t\tLogger.log.error(\"\", e);\n\t\t}\n\t}\n\n\tprivate static void logMessage(Message msg)\n\t{\n\t\tString userName = msg.getAuthor().get().getUsername();\n\t\tString userId = msg.getAuthor().get().getId().asString();\n\t\tString channelId = msg.getChannelId().asString();\n\t\tString messageID = msg.getId().asString();\n\t\tString logMsg;\n\n\t\tif (!(msg.getChannel().block() instanceof PrivateChannel))\n\t\t{\n\t\t\tString channelName = ((GuildChannel) msg.getChannel().block()).getName();\n\t\t\tString guildName = msg.getGuild().block().getName();\n\t\t\tString guildId = msg.getGuild().block().getId().asString();\n\n\t\t\tlogMsg = messageID + \" | \" + userName + \" (\" + userId + \") | \" + guildName + \" (\" + guildId + \") | #\" + channelName + \" (\" + channelId + \") |\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tPrivateChannel channel = (PrivateChannel) msg.getChannel().block();\n\t\t\tString recipientName = channel.getRecipients().iterator().next().getUsername();\n\t\t\tString recipientId = channel.getRecipients().iterator().next().getId().asString();\n\n\t\t\tif (recipientId.equals(userId))\n\t\t\t{\n\t\t\t\tlogMsg = messageID + \" | \" + userName + \" (\" + userId + \") | PM (\" + channelId + \") |\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tlogMsg = messageID + \" | \" + userName + \" (\" + userId + \") | \" + recipientName + \" (\" + recipientId + \") | PM (\" + channelId + \") |\";\n\t\t\t}\n\t\t}\n\n\t\tif (!msg.getContent().isEmpty())\n\t\t{\n\t\t\tlogMsg += \" \" + msg.getContent();\n\t\t}\n\n\t\tfor (Attachment attachment : msg.getAttachments())\n\t\t{\n\t\t\tlogMsg += \" [Attachment \" + attachment.getUrl() + \"]\";\n\t\t}\n\t\tfor (Embed embed : msg.getEmbeds())\n\t\t{\n\t\t\tlogMsg += \" [Embed]\";\n\t\t}\n\n\t\tLogger.log.debug(logMsg);\n\t}\n\n\tpublic static void onReactionAdd(ReactionAddEvent event)\n\t{\n\t\ttry\n\t\t{\n\t\t\tMessage message;\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tmessage = event.getMessage().block();\n\t\t\t}\n\t\t\tcatch (ClientException e)\n\t\t\t{\n\t\t\t\t//this means we can't see the message reacted to because of missing READ_MESSAGE_HISTORY permission\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tString userName = event.getUser().block().getUsername();\n\t\t\tString userId = event.getUser().block().getId().asString();\n\t\t\tString messageID = message.getId().asString();\n\t\t\tString reaction = \"null\";\n\n\t\t\tif (event.getEmoji().asUnicodeEmoji().isPresent())\n\t\t\t{\n\t\t\t\treaction = event.getEmoji().asUnicodeEmoji().get().getRaw();\n\t\t\t}\n\t\t\telse if (event.getEmoji().asCustomEmoji().isPresent())\n\t\t\t{\n\t\t\t\treaction = \":\" + event.getEmoji().asCustomEmoji().get().getName() + \":\";\n\t\t\t}\n\n\t\t\tLogger.log.debug(userName + \" (\" + userId + \") added the reaction \" + reaction + \" to the message ID \" + messageID);\n\t\t}\n\t\tcatch (Exception e)\n\t\t{\n\t\t\tLogger.log.error(\"\", e);\n\t\t}\n\t}\n\n\tpublic static void onReactionRemove(ReactionRemoveEvent event)\n\t{\n\t\ttry\n\t\t{\n\t\t\tMessage message;\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tmessage = event.getMessage().block();\n\t\t\t}\n\t\t\tcatch (ClientException e)\n\t\t\t{\n\t\t\t\t//this means we can't see the message reacted to because of missing READ_MESSAGE_HISTORY permission\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tString userName = event.getUser().block().getUsername();\n\t\t\tString userId = event.getUser().block().getId().asString();\n\t\t\tString messageID = message.getId().asString();\n\t\t\tString reaction = \"null\";\n\n\t\t\tif (event.getEmoji().asUnicodeEmoji().isPresent())\n\t\t\t{\n\t\t\t\treaction = event.getEmoji().asUnicodeEmoji().get().getRaw();\n\t\t\t}\n\t\t\telse if (event.getEmoji().asCustomEmoji().isPresent())\n\t\t\t{\n\t\t\t\treaction = \":\" + event.getEmoji().asCustomEmoji().get().getName() + \":\";\n\t\t\t}\n\n\t\t\tLogger.log.debug(userName + \" (\" + userId + \") removed the reaction \" + reaction + \" from the message ID \" + messageID);\n\t\t}\n\t\tcatch (Exception e)\n\t\t{\n\t\t\tLogger.log.error(\"\", e);\n\t\t}\n\t}\n\n\tpublic static void onGuildCreate(GuildCreateEvent event)\n\t{\n\t\ttry\n\t\t{\n\t\t\tLogger.log.debug(\"Joined guild \" + event.getGuild().getName() + \" (\" + event.getGuild().getId().asString() + \")\");\n\t\t}\n\t\tcatch (Exception e)\n\t\t{\n\t\t\tLogger.log.error(\"\", e);\n\t\t}\n\t}\n\n\tpublic static void onGuildDelete(GuildDeleteEvent event)\n\t{\n\t\ttry\n\t\t{\n\t\t\tif (!event.isUnavailable())\n\t\t\t{\n\t\t\t\tLogger.log.debug(\"Left guild \" + event.getGuild().get().getName() + \" (\" + event.getGuildId().asString() + \")\");\n\t\t\t}\n\t\t}\n\t\tcatch (Exception e)\n\t\t{\n\t\t\tLogger.log.error(\"\", e);\n\t\t}\n\t}\n\n\t/**\n\t * Recursive method for parsing all slash command options into plain text\n\t *\n\t * @param options List of options\n\t * @return Plain text representation of options\n\t */\n\tprivate static String getArguments(List<ApplicationCommandInteractionOption> options)\n\t{\n\t\tString arguments = \"\";\n\n\t\tfor (ApplicationCommandInteractionOption option : options)\n\t\t{\n\t\t\tif (option.getValue().isPresent())\n\t\t\t{\n\t\t\t\tswitch (option.getType())\n\t\t\t\t{\n\t\t\t\t\tcase BOOLEAN:\n\t\t\t\t\t\targuments += \" \" + option.getValue().get().asBoolean();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase CHANNEL:\n\t\t\t\t\t\targuments += \" #\" + ((GuildChannel) option.getValue().get().asChannel().block()).getName();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase INTEGER:\n\t\t\t\t\t\targuments += \" \" + option.getValue().get().asLong();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase NUMBER:\n\t\t\t\t\t\targuments += \" \" + option.getValue().get().asDouble();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase ROLE:\n\t\t\t\t\t\targuments += \" @\" + option.getValue().get().asRole().block().getName();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase STRING:\n\t\t\t\t\t\targuments += \" \" + option.getValue().get().asString();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase USER:\n\t\t\t\t\t\targuments += \" @\" + option.getValue().get().asUser().block().getTag();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tLogger.log.error(\"New command option type needs implementing in Logger#getArguments()\");\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\targuments += \" \" + option.getName();\n\t\t\t}\n\n\t\t\targuments += getArguments(option.getOptions());\n\t\t}\n\n\t\treturn arguments;\n\t}\n}", "public class Util\n{\n\t/**\n\t * @return The path at which the running jar file is located\n\t * @throws Exception\n\t */\n\tpublic static String getJarLocation() throws Exception\n\t{\n\t\tString path = Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();\n\n\t\tif (path.endsWith(\".jar\"))\n\t\t{\n\t\t\tpath = path.substring(0, path.lastIndexOf(\"/\"));\n\t\t}\n\n\t\tif (!path.endsWith(\"/\"))\n\t\t{\n\t\t\tpath += \"/\";\n\t\t}\n\n\t\treturn path;\n\t}\n\n\t/**\n\t * Gets the contents of a file as a string\n\t *\n\t * @param arg The path of the file to read, relative to {@link Util#getJarLocation()}\n\t * @return The content of the file\n\t * @throws Exception\n\t */\n\tpublic static String getFileContents(String arg) throws Exception\n\t{\n\t\tFile file = new File(getJarLocation() + arg);\n\n\t\treturn FileUtils.readFileToString(file, \"UTF-8\");\n\t}\n\n\t/**\n\t * Gets the contents of a file as a string\n\t *\n\t * @param arg The File object to read\n\t * @return The content of the file, or an empty string if an exception has been caught\n\t * @throws Exception\n\t */\n\tpublic static String getFileContents(File arg) throws Exception\n\t{\n\t\treturn FileUtils.readFileToString(arg, \"UTF-8\");\n\t}\n\n\t/**\n\t * Concatenates a string array from a given start index\n\t *\n\t * @param args The array to concatenate\n\t * @param startIndex The index to start concatenating the array\n\t * @return The concatenated array\n\t */\n\tpublic static String addArgs(String[] args, int startIndex)\n\t{\n\t\tString s = \"\";\n\n\t\tfor (int i = startIndex; i < args.length; i++)\n\t\t{\n\t\t\ts += args[i] + \" \";\n\t\t}\n\n\t\treturn s.substring(0, s.lastIndexOf(\" \"));\n\t}\n\n\t/**\n\t * Gets the ordinal of a number\n\t *\n\t * @param n The number\n\t * @return st for 1, 21, 31 etc; nd for 2, 22, 32, etc; rd for 3, 23, 33, etc; th for everything else\n\t */\n\tpublic static String getOrdinal(int n)\n\t{\n\t\tif (n >= 11 && n <= 13)\n\t\t{\n\t\t\treturn \"th\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tswitch (n % 10)\n\t\t\t{\n\t\t\t\tcase 1:\n\t\t\t\t\treturn \"st\";\n\t\t\t\tcase 2:\n\t\t\t\t\treturn \"nd\";\n\t\t\t\tcase 3:\n\t\t\t\t\treturn \"rd\";\n\t\t\t\tdefault:\n\t\t\t\t\treturn \"th\";\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Checks if a user is a bot administrator\n\t *\n\t * @param user The user to check\n\t * @return true if user is a bot administrator, false otherwise\n\t * @throws Exception\n\t */\n\tpublic static boolean hasPermission(User user)\n\t{\n\t\tfor (int i = 0; i < Main.cfg.getOwners().length; i++)\n\t\t{\n\t\t\tif (user.getId().asLong() == Main.cfg.getOwners()[i])\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if a user is a bot or guild administrator\n\t *\n\t * @param user The user to check\n\t * @param guild The guild to check for permissions in\n\t * @return true if the user is a bot or guild administrator, false otherwise\n\t * @throws Exception\n\t */\n\tpublic static boolean hasPermission(User user, Guild guild) throws Exception\n\t{\n\t\tif (hasPermission(user))\n\t\t\treturn true;\n\n\t\t// Always PM, i think?\n\t\tif (Objects.isNull(guild))\n\t\t\treturn false;\n\n\t\treturn (user.asMember(guild.getId()).block().getBasePermissions().block().contains(Permission.ADMINISTRATOR) || user.asMember(guild.getId()).block().getBasePermissions().block().contains(Permission.MANAGE_GUILD) ? true : false);\n\t}\n\n\t/**\n\t * Sends a message to a channel\n\t *\n\t * @param channel The channel\n\t * @param permissionExHandling Whether to handle missing permissions exceptions (403)\n\t * @param allowUserMentions Whether to allow users to be mentioned in this message\n\t * @param message The string message (null for none)\n\t * @param embed The embed (null for none)\n\t * @return The message object\n\t */\n\tpublic static Message msg(MessageChannel channel, boolean permissionExHandling, boolean allowUserMentions, String message, EmbedCreateSpec embed)\n\t{\n\t\ttry\n\t\t{\n\t\t\tMessageCreateMono msg;\n\t\t\tAllowedMentions mentions;\n\n\t\t\tif (!Objects.isNull(message))\n\t\t\t\tmsg = channel.createMessage(message);\n\t\t\telse\n\t\t\t\tmsg = channel.createMessage();\n\n\t\t\tif (!Objects.isNull(embed))\n\t\t\t\tmsg = msg.withEmbeds(embed);\n\n\t\t\tif (allowUserMentions)\n\t\t\t\tmentions = AllowedMentions.builder().parseType(AllowedMentions.Type.USER).build();\n\t\t\telse\n\t\t\t\tmentions = AllowedMentions.suppressAll();\n\n\t\t\treturn msg.withAllowedMentions(mentions).block();\n\t\t}\n\t\tcatch (ClientException e)\n\t\t{\n\t\t\tif (permissionExHandling && e.getStatus().code() == 403)\n\t\t\t{\n\t\t\t\tif (!(channel instanceof PrivateChannel))\n\t\t\t\t{\n\t\t\t\t\tLogger.log.warn(\"Missing permissions to send message to channel #\" + ((GuildChannel) channel).getName() + \" (\" + channel.getId().asString() + \") in guild \" + ((GuildChannel) channel).getGuild().block().getName() + \" (\" + ((GuildChannel) channel).getGuild().block().getId().asString() + \")\");\n\t\t\t\t}\n\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Sends a message to a channel with mentions disabled\n\t *\n\t * @param channel The channel\n\t * @param permissionExHandling Whether to handle missing permissions exceptions (403)\n\t * @param message The string message\n\t * @return The message object\n\t */\n\tpublic static Message msg(MessageChannel channel, boolean permissionExHandling, String message)\n\t{\n\t\treturn msg(channel, permissionExHandling, false, message, null);\n\t}\n\n\t/**\n\t * Sends a message to a channel with mentions disabled\n\t *\n\t * @param channel The channel\n\t * @param permissionExHandling Whether to handle missing permissions exceptions (403)\n\t * @param embed The embed\n\t * @return The message object\n\t */\n\tpublic static Message msg(MessageChannel channel, boolean permissionExHandling, EmbedCreateSpec embed)\n\t{\n\t\treturn msg(channel, permissionExHandling, false, null, embed);\n\t}\n\n\t/**\n\t * Sends a message to a channel with permission exception handling and mentions disabled\n\t *\n\t * @param channel The channel\n\t * @param message The string message\n\t * @return The message object\n\t */\n\tpublic static Message msg(MessageChannel channel, String message)\n\t{\n\t\treturn msg(channel, false, false, message, null);\n\t}\n\n\t/**\n\t * Sends a message to a channel with permission exception handling and mentions disabled\n\t *\n\t * @param channel The channel\n\t * @param embed The embed\n\t * @return The message object\n\t */\n\tpublic static Message msg(MessageChannel channel, EmbedCreateSpec embed)\n\t{\n\t\treturn msg(channel, false, false, null, embed);\n\t}\n\n\t/**\n\t * Gets the average color from the picture found at a URL\n\t *\n\t * @param url The URL leading to the picture\n\t * @param handleExceptions Whether to return (0, 154, 255) when an exception happens\n\t * @return The average color of the picture, null or (0, 154, 255) on error\n\t */\n\tpublic static Color averageColorFromURL(URL url, boolean handleExceptions)\n\t{\n\t\tBufferedImage image;\n\n\t\ttry\n\t\t{\n\t\t\tHttpURLConnection connection = (HttpURLConnection) url.openConnection();\n\t\t\tconnection.setRequestProperty(\"User-Agent\", Main.cfg.getUserAgent());\n\t\t\tconnection.setConnectTimeout(5000);\n\t\t\tconnection.setReadTimeout(5000);\n\t\t\timage = ImageIO.read(connection.getInputStream());\n\n\t\t\tfinal int pixels = image.getWidth() * image.getHeight();\n\t\t\tint red = 0;\n\t\t\tint green = 0;\n\t\t\tint blue = 0;\n\n\t\t\tfor (int x = 0; x < image.getWidth(); x++)\n\t\t\t{\n\t\t\t\tfor (int y = 0; y < image.getHeight(); y++)\n\t\t\t\t{\n\t\t\t\t\tColor pixel = Color.of(image.getRGB(x, y));\n\n\t\t\t\t\tred += pixel.getRed();\n\t\t\t\t\tgreen += pixel.getGreen();\n\t\t\t\t\tblue += pixel.getBlue();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn Color.of(red / pixels, green / pixels, blue / pixels);\n\t\t}\n\t\tcatch (Exception e)\n\t\t{\n\t\t\tif (handleExceptions)\n\t\t\t{\n\t\t\t\treturn Color.of(0, 154, 255);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Generic method for adding a reaction to a message, used so a no permission message can be sent if required\n\t *\n\t * @param m The message to add the reaction to\n\t * @param reaction The reaction to add\n\t * @return true if the reaction was added successfully, false otherwise\n\t */\n\tpublic static boolean addReaction(Message m, String reaction)\n\t{\n\t\ttry\n\t\t{\n\t\t\tm.addReaction(ReactionEmoji.unicode(reaction)).block();\n\t\t\treturn true;\n\t\t}\n\t\tcatch (ClientException e)\n\t\t{\n\t\t\tif (e.getStatus().code() == 403)\n\t\t\t{\n\t\t\t\tmsg(m.getChannel().block(), \":exclamation: | **Missing permissions!**\" + System.lineSeparator() + System.lineSeparator() + \"The bot wasn't able to add one or more reactions because it's lacking permissions.\" + System.lineSeparator() + System.lineSeparator() + \"Please have a guild administrator confirm role/channel permissions are correctly set and try again.\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\telse if (e.getStatus().code() == 404)\n\t\t\t{\n\t\t\t\t//means m was deleted before this reaction could be added, likely because the user selected an earlier reaction in a menu before all reactions had been added\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Generic method for adding reactions to a message, used so a no permission message can be sent if required\n\t *\n\t * @param m The message to add the reactions to\n\t * @param reactions An ArrayList<String> that contains a list of reactions to add\n\t */\n\tpublic static void addReactions(Message m, ArrayList<String> reactions)\n\t{\n\t\tfor (String reaction : reactions)\n\t\t{\n\t\t\tif (!addReaction(m, reaction))\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Adds keycap reactions, increasing by value, starting at one and ending at nine. Used for menu selection\n\t *\n\t * @param m The message to add the reactions to\n\t * @param cancellable Whether an x reaction should be added at the end or not\n\t * @param i The amount of reactions to add\n\t */\n\tpublic static void addNumberedReactions(Message m, boolean cancellable, int i)\n\t{\n\t\tArrayList<String> finalReactions = new ArrayList<>();\n\t\tString[] reactions = {\n\t\t\t\"\\u0031\\u20E3\",\n\t\t\t\"\\u0032\\u20E3\",\n\t\t\t\"\\u0033\\u20E3\",\n\t\t\t\"\\u0034\\u20E3\",\n\t\t\t\"\\u0035\\u20E3\",\n\t\t\t\"\\u0036\\u20E3\",\n\t\t\t\"\\u0037\\u20E3\",\n\t\t\t\"\\u0038\\u20E3\",\n\t\t\t\"\\u0039\\u20E3\"\n\t\t};\n\n\t\tfor (int j = 0; j < i; j++)\n\t\t{\n\t\t\tfinalReactions.add(reactions[j]);\n\t\t}\n\n\t\tif (cancellable)\n\t\t{\n\t\t\tfinalReactions.add(\"\\u274C\");\n\t\t}\n\n\t\taddReactions(m, finalReactions);\n\t}\n\n\t/**\n\t * Builds a modular page message in response to an interaction for the given parameters\n\t *\n\t * @param entries An ArrayList<String> that contains all the entries that should be in the page builder\n\t * @param title The title to give all the pages\n\t * @param pageSize How many entries should be in a specific page\n\t * @param pageNumber Which page the method should build and send to the provided channel\n\t * @param numberStyle Which style to use for numbered entries, 0 = none, 1 = standard, 2 = code block surrounded & unique per page\n\t * @param codeBlock Whether to surround all the entries in a code block or not\n\t * @param numberedReactions Whether to add numbered reactions for each entry\n\t * @param cancellable Whether to add an X emoji to close the page\n\t * @param event The ChatInputInteractionEvent that is being responded to\n\t * @return The Message object for the sent page message if an exception isn't thrown, null otherwise\n\t */\n\tpublic static Message buildPage(List<String> entries, String title, int pageSize, int pageNumber, int numberStyle, boolean codeBlock, boolean numberedReactions, boolean cancellable, ChatInputInteractionEvent event)\n\t{\n\t\treturn buildPage(entries, title, pageSize, pageNumber, numberStyle, codeBlock, numberedReactions, cancellable, null, null, event);\n\t}\n\n\t/**\n\t * Builds a modular page message for the given parameters\n\t *\n\t * @param entries An ArrayList<String> that contains all the entries that should be in the page builder\n\t * @param title The title to give all the pages\n\t * @param pageSize How many entries should be in a specific page\n\t * @param pageNumber Which page the method should build and send to the provided channel\n\t * @param numberStyle Which style to use for numbered entries, 0 = none, 1 = standard, 2 = code block surrounded & unique per page\n\t * @param codeBlock Whether to surround all the entries in a code block or not\n\t * @param numberedReactions Whether to add numbered reactions for each entry\n\t * @param cancellable Whether to add an X emoji to close the page\n\t * @param channel The MessageChannel that the page message should be sent to (if legacy command)\n\t * @param user The User that triggered the command's execution in the first place (if legacy command)\n\t * @return The Message object for the sent page message if an exception isn't thrown, null otherwise\n\t */\n\tpublic static Message buildPage(List<String> entries, String title, int pageSize, int pageNumber, int numberStyle, boolean codeBlock, boolean numberedReactions, boolean cancellable, MessageChannel channel, User user)\n\t{\n\t\treturn buildPage(entries, title, pageSize, pageNumber, numberStyle, codeBlock, numberedReactions, cancellable, channel, user, null);\n\t}\n\n\tprivate static Message buildPage(List<String> entries, String title, int pageSize, int pageNumber, int numberStyle, boolean codeBlock, boolean numberedReactions, boolean cancellable, MessageChannel channel, User user, ChatInputInteractionEvent event)\n\t{\n\t\tif (pageNumber > (int) Math.ceil((float) entries.size() / (float) pageSize))\n\t\t{\n\t\t\tif (Objects.isNull(event))\n\t\t\t\treturn msg(channel, \"That page doesn't exist!\");\n\t\t\telse\n\t\t\t\treturn Main.gateway.getMessageById(event.getInteraction().getChannelId(), Snowflake.of(event.getInteractionResponse().createFollowupMessage(\"That page doesn't exist!\").block().id())).block();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tStringBuilder list = new StringBuilder();\n\n\t\t\tif (codeBlock)\n\t\t\t{\n\t\t\t\tlist.append(\"```\" + System.lineSeparator());\n\t\t\t}\n\n\t\t\tint usedEntries = 0;\n\n\t\t\tfor (int i = (int) (entries.size() - ((((float) entries.size() / (float) pageSize) - (pageNumber - 1)) * pageSize)); entries.size() - ((((float) entries.size() / (float) pageSize) - pageNumber) * pageSize) > i; i++)\n\t\t\t{\n\t\t\t\tif (i > entries.size() - 1)\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tusedEntries++;\n\n\t\t\t\t\tif (numberStyle == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tlist.append(entries.get(i) + System.lineSeparator());\n\t\t\t\t\t}\n\t\t\t\t\telse if (numberStyle == 1)\n\t\t\t\t\t{\n\t\t\t\t\t\tlist.append((i + 1) + \" - \" + entries.get(i) + System.lineSeparator());\n\t\t\t\t\t}\n\t\t\t\t\telse if (numberStyle == 2)\n\t\t\t\t\t{\n\t\t\t\t\t\tlist.append(\"**`[\" + ((i + 1) - (pageSize * (pageNumber - 1))) + \"]`** | \" + entries.get(i) + System.lineSeparator());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (codeBlock)\n\t\t\t{\n\t\t\t\tlist.append(\"```\");\n\t\t\t}\n\n\t\t\tMessage m;\n\t\t\tString msg;\n\n\t\t\tif (pageNumber == 1 && (int) Math.ceil((float) entries.size() / (float) pageSize) == 1)\n\t\t\t\tmsg = \"--- **\" + title + \"** ---\" + System.lineSeparator() + list.toString();\n\t\t\telse\n\t\t\t\tmsg = \"--- **\" + title + \"** --- **Page \" + pageNumber + \"/\" + (int) Math.ceil((float) entries.size() / (float) pageSize) + \"** ---\" + System.lineSeparator() + list.toString();\n\n\t\t\tif (Objects.isNull(event))\n\t\t\t\tm = msg(channel, msg);\n\t\t\telse\n\t\t\t\tm = Main.gateway.getMessageById(event.getInteraction().getChannelId(), Snowflake.of(event.getInteractionResponse().createFollowupMessage(msg).block().id())).block();\n\n\t\t\tfinal int finalUsedEntries = usedEntries;\n\t\t\tScheduledExecutorService reactionAddPool = Executors.newScheduledThreadPool(1);\n\n\t\t\treactionAddPool.schedule(() ->\n\t\t\t{\n\t\t\t\treactionAddPool.shutdown();\n\n\t\t\t\tif (pageNumber != 1)\n\t\t\t\t{\n\t\t\t\t\taddReaction(m, \"◀\");\n\t\t\t\t}\n\t\t\t\tif (numberedReactions)\n\t\t\t\t{\n\t\t\t\t\taddNumberedReactions(m, false, finalUsedEntries);\n\t\t\t\t}\n\t\t\t\tif (pageNumber != (int) Math.ceil((float) entries.size() / (float) pageSize))\n\t\t\t\t{\n\t\t\t\t\taddReaction(m, \"▶\");\n\t\t\t\t}\n\t\t\t\tif (cancellable)\n\t\t\t\t{\n\t\t\t\t\taddReaction(m, \"\\u274C\");\n\t\t\t\t}\n\t\t\t}, 250, TimeUnit.MILLISECONDS);\n\n\t\t\treturn m;\n\t\t}\n\t}\n\n\t/**\n\t * Converts an emoji into an integer\n\t *\n\t * @param emoji The string value of the emoji\n\t * @return The integer value of the emoji\n\t */\n\tpublic static int emojiToInt(String emoji)\n\t{\n\t\tif (emoji.equals(\"1⃣\"))\n\t\t{\n\t\t\treturn 1;\n\t\t}\n\t\telse if (emoji.equals(\"2⃣\"))\n\t\t{\n\t\t\treturn 2;\n\t\t}\n\t\telse if (emoji.equals(\"3⃣\"))\n\t\t{\n\t\t\treturn 3;\n\t\t}\n\t\telse if (emoji.equals(\"4⃣\"))\n\t\t{\n\t\t\treturn 4;\n\t\t}\n\t\telse if (emoji.equals(\"5⃣\"))\n\t\t{\n\t\t\treturn 5;\n\t\t}\n\t\telse if (emoji.equals(\"6⃣\"))\n\t\t{\n\t\t\treturn 6;\n\t\t}\n\t\telse if (emoji.equals(\"7⃣\"))\n\t\t{\n\t\t\treturn 7;\n\t\t}\n\t\telse if (emoji.equals(\"8⃣\"))\n\t\t{\n\t\t\treturn 8;\n\t\t}\n\t\telse if (emoji.equals(\"9⃣\"))\n\t\t{\n\t\t\treturn 9;\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\t/**\n\t * Checks if a given channel has multiple servers being tracked in it\n\t *\n\t * @param guildID The guild to check inside of\n\t * @param channelID The channel to check\n\t * @return True if channel tracking multiple servers, false otherwise\n\t */\n\tpublic static boolean isMultiTrackingChannel(long guildID, long channelID)\n\t{\n\t\tint matches = 0;\n\n\t\tfor (Document doc : Main.mongoDatabase.getCollection(\"services\").find(eq(\"guildID\", guildID)))\n\t\t{\n\t\t\tif (!doc.getBoolean(\"enabled\"))\n\t\t\t\tcontinue;\n\n\t\t\tif (doc.getLong(\"channelID\") == channelID)\n\t\t\t\tmatches++;\n\t\t}\n\n\t\treturn matches >= 2;\n\t}\n}", "public class Await\n{\n\tprivate Snowflake id;\n\tprivate AbstractCommand command;\n\tprivate ChatInputInteractionEvent event;\n\n\t/**\n\t * @param id An ID of a user who triggered the message or a message to be removed later on\n\t * @param command The command with which to continue execution upon adding a reaction\n\t * @param event The ChatInputInteractionEvent that triggered the execution of {@link Await#command}\n\t */\n\tpublic Await(Snowflake id, AbstractCommand command, ChatInputInteractionEvent event)\n\t{\n\t\tthis.id = id;\n\t\tthis.command = command;\n\t\tthis.event = event;\n\t}\n\n\t/**\n\t * @param id An ID of a user who triggered the message or a message to be removed later on\n\t * @param command The command with which to continue execution upon adding a reaction\n\t */\n\tpublic Await(Snowflake id, AbstractCommand command)\n\t{\n\t\tthis(id, command, null);\n\t}\n\n\t/**\n\t * @return The ID of the user who triggered the message or of the message to be removed later on\n\t */\n\tpublic Snowflake getID()\n\t{\n\t\treturn id;\n\t}\n\n\t/**\n\t * @return The command with which to continue execution upon adding a reaction\n\t */\n\tpublic AbstractCommand getCommand()\n\t{\n\t\treturn command;\n\t}\n\n\t/**\n\t * @return The ChatInputInteractionEvent that triggered the execution of {@link Await#command}, only present if instance of {@link AbstractSlashCommand}\n\t */\n\tpublic ChatInputInteractionEvent getInteractionEvent()\n\t{\n\t\treturn event;\n\t}\n}" ]
import com.vauff.maunzdiscord.commands.templates.AbstractCommand; import com.vauff.maunzdiscord.commands.templates.AbstractLegacyCommand; import com.vauff.maunzdiscord.commands.templates.AbstractSlashCommand; import com.vauff.maunzdiscord.core.Logger; import com.vauff.maunzdiscord.core.Util; import com.vauff.maunzdiscord.objects.Await; import discord4j.core.event.domain.message.ReactionAddEvent; import discord4j.core.object.entity.Message; import discord4j.rest.http.client.ClientException; import java.util.Random;
package com.vauff.maunzdiscord.threads; public class ReactionAddThread implements Runnable { private ReactionAddEvent event; private Message message; private Thread thread; private String name; public ReactionAddThread(ReactionAddEvent passedEvent, Message passedMessage, String passedName) { event = passedEvent; message = passedMessage; name = passedName; } public void start() { if (thread == null) { thread = new Thread(this, name); thread.start(); } } public void run() { try {
if (AbstractCommand.AWAITED.containsKey(message.getId()) && event.getUser().block().getId().equals(AbstractCommand.AWAITED.get(message.getId()).getID()) && event.getEmoji().asUnicodeEmoji().isPresent())
0
edouardhue/comeon
src/main/java/comeon/ui/media/MediaMetadataPanel.java
[ "public interface Core {\n\n String EXTERNAL_METADATA_KEY = \"external\";\n\n String[] PICTURE_EXTENSIONS = { \"jpg\", \"jpeg\" };\n\n String[] AUDIO_EXTENSIONS = { \"ogg\", \"flac\", \"wav\" };\n\n void addMedia(final File[] files, final Template defautTemplate, final ExternalMetadataSource<?> externalMetadataSource) throws IOException;\n\n void removeMedia(Media media);\n\n void removeAllMedia();\n\n Set<Media> getMedia();\n\n int countMediaToBeUploaded();\n\n void uploadMedia();\n\n void abort();\n}", "@Singleton\r\npublic final class UI extends JFrame {\r\n private static final long serialVersionUID = 1L;\r\n\r\n private static final Logger LOGGER = LoggerFactory.getLogger(UI.class);\r\n\r\n public static final ResourceBundle BUNDLE = ResourceBundle.getBundle(\"comeon.ui.comeon\");\r\n\r\n public static final Color NEUTRAL_GREY = Color.DARK_GRAY;\r\n\r\n public static final int PREVIEW_PANEL_HEIGHT = 90;\r\n\r\n public static final int METADATA_PANEL_WIDTH = 280;\r\n\r\n public static final List<? extends Image> ICON_IMAGES = loadIcons();\r\n\r\n private final Box previews;\r\n\r\n private final Component previewsGlue;\r\n\r\n private final JPanel editContainer;\r\n\r\n private final Core core;\r\n\r\n @Inject\r\n public UI(final Core core, final Templates templates, final MenuBar menuBar, final Toolbar toolbar) {\r\n super(BUNDLE.getString(\"comeon\"));\r\n\r\n this.core = core;\r\n\r\n this.setIconImages(ICON_IMAGES);\r\n this.setJMenuBar(menuBar);\r\n this.setLayout(new BorderLayout());\r\n this.setExtendedState(Frame.MAXIMIZED_BOTH);\r\n this.setMinimumSize(new Dimension(800, 600));\r\n this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\r\n\r\n this.previews = new Box(BoxLayout.X_AXIS);\r\n this.previews.setMinimumSize(new Dimension(0, PREVIEW_PANEL_HEIGHT));\r\n this.previews.setBackground(NEUTRAL_GREY);\r\n this.previews.setOpaque(true);\r\n this.previewsGlue = Box.createHorizontalGlue();\r\n this.previews.add(previewsGlue);\r\n final JScrollPane scrollablePreviews = new JScrollPane(previews, ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER,\r\n ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);\r\n this.add(scrollablePreviews, BorderLayout.SOUTH);\r\n\r\n this.editContainer = new JPanel(new CardLayout());\r\n this.add(editContainer, BorderLayout.CENTER);\r\n\r\n this.add(toolbar, BorderLayout.NORTH);\r\n\r\n final MediaTransferHandler transferHandler = new MediaTransferHandler(templates);\r\n this.setTransferHandler(transferHandler);\r\n }\r\n\r\n public static Window findInstance() {\r\n return Arrays.stream(getWindows()).filter(w -> UI.class.equals(w.getClass())).findFirst().orElseThrow(NoSuchElementException::new);\r\n }\r\n\r\n private static List<? extends Image> loadIcons() {\r\n try {\r\n return ImmutableList.of(\r\n ImageIO.read(Resources.getResource(\"comeon_1024_1024.png\")),\r\n ImageIO.read(Resources.getResource(\"comeon_512_512.png\")),\r\n ImageIO.read(Resources.getResource(\"comeon_128_128.png\")),\r\n ImageIO.read(Resources.getResource(\"comeon_256_256.png\")),\r\n ImageIO.read(Resources.getResource(\"comeon_48_48.png\")),\r\n ImageIO.read(Resources.getResource(\"comeon_16_16.png\"))\r\n );\r\n } catch (final IOException e) {\r\n return Collections.emptyList();\r\n }\r\n }\r\n\r\n @Subscribe\r\n public void handleMediaAddedEvent(final MediaAddedEvent event) {\r\n this.refreshMedia();\r\n }\r\n\r\n @Subscribe\r\n public void handleMediaRemovedEvent(final MediaRemovedEvent event) {\r\n this.refreshMedia();\r\n }\r\n\r\n private void refreshMedia() {\r\n SwingUtilities.invokeLater(() -> {\r\n previews.removeAll();\r\n editContainer.removeAll();\r\n validate();\r\n core.getMedia().forEach(this::add);\r\n validate();\r\n });\r\n }\r\n\r\n private void add(final Media media) {\r\n final MediaPanels panels = new MediaPanels(media);\r\n final JComponent previewPanel = panels.getPreviewPanel();\r\n\r\n this.previews.remove(previewsGlue);\r\n this.previews.add(previewPanel);\r\n this.previews.add(previewsGlue);\r\n\r\n this.editContainer.add(panels.getEditPanel(), media.getFileName());\r\n\r\n previewPanel.addMouseListener(new PreviewPanelMouseAdapter(media));\r\n }\r\n\r\n private final class PreviewPanelMouseAdapter extends MouseAdapter {\r\n private final Media media;\r\n\r\n private PreviewPanelMouseAdapter(Media media) {\r\n this.media = media;\r\n }\r\n\r\n @Override\r\n public void mouseClicked(final MouseEvent e) {\r\n if (e.getButton() == MouseEvent.BUTTON1) {\r\n SwingUtilities.invokeLater(() -> {\r\n if (e.isControlDown()) {\r\n core.removeMedia(media);\r\n } else {\r\n ((CardLayout) editContainer.getLayout()).show(editContainer, media.getFileName());\r\n }\r\n });\r\n }\r\n }\r\n }\r\n\r\n private final class MediaTransferHandler extends TransferHandler {\r\n private static final long serialVersionUID = 1L;\r\n\r\n private final Templates templates;\r\n\r\n public MediaTransferHandler(final Templates templates) {\r\n this.templates = templates;\r\n }\r\n\r\n @Override\r\n public boolean canImport(final TransferSupport support) {\r\n return support.isDataFlavorSupported(DataFlavor.javaFileListFlavor);\r\n }\r\n\r\n @Override\r\n public boolean importData(TransferSupport support) {\r\n\r\n try {\r\n @SuppressWarnings(\"unchecked\")\r\n final List<File> transferData = (List<File>) support.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);\r\n final File[] preselectedFiles = transferData\r\n .parallelStream()\r\n .filter(file -> file.getName().endsWith(\".jpg\") || file.getName().endsWith(\".jpeg\"))\r\n .toArray(File[]::new);\r\n\r\n SwingUtilities.invokeLater(() -> {\r\n final AddMediaDialog dialog = new AddMediaDialog(templates, preselectedFiles);\r\n final int value = dialog.showDialog();\r\n if (value == JOptionPane.OK_OPTION) {\r\n new AdderWorker(dialog.getModel(), core).execute();\r\n }\r\n });\r\n return true;\r\n } catch (final UnsupportedFlavorException | IOException e) {\r\n LOGGER.warn(\"Failed drag & drop transfer\", e);\r\n return false;\r\n }\r\n }\r\n }\r\n\r\n}", "public final class ExternalMetadataTable extends AbstractMetadataTable<Object> {\n\n private static final long serialVersionUID = 1L;\n\n public ExternalMetadataTable(final String title, final Object content) {\n super(title, content);\n }\n\n @Override\n protected TableModel getTableModel(final Object content) {\n return new ExternalMetadataTableModel(content);\n }\n\n private static final class ExternalMetadataTableModel extends SimpleMetadataTableModel<Object> {\n\n private static final long serialVersionUID = 1L;\n\n private static final Logger LOGGER = LoggerFactory.getLogger(ExternalMetadataTableModel.class);\n\n private static final String CLASS_PROPERTY_NAME = \"class\";\n\n public ExternalMetadataTableModel(final Object content) {\n super(content);\n }\n\n @Override\n protected List<Entry> getValues(Object content) {\n List<Entry> values;\n try {\n final Map<String, String> properties = BeanUtils.describe(content);\n properties.remove(CLASS_PROPERTY_NAME);\n values = new ArrayList<>(properties.size());\n for (final Map.Entry<String, String> property : properties.entrySet()) {\n final String propertyName = property.getKey();\n final String propertyValue = BeanUtils.getProperty(content, propertyName);\n values.add(new Entry(propertyName, propertyValue));\n }\n } catch (final IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {\n LOGGER.warn(\"Could not extract properties\", e);\n values = Collections.emptyList();\n }\n return values;\n }\n\n }\n}", "public final class MediaMetadataTable extends AbstractMetadataTable<DynaBean> {\n private static final long serialVersionUID = 1L;\n\n public MediaMetadataTable(final String directoryName, final DynaBean directoryContent) {\n super(directoryName, directoryContent);\n }\n\n @Override\n protected TableModel getTableModel(final DynaBean content) {\n return new MediaMetadataTableModel(content);\n }\n\n private static final class MediaMetadataTableModel extends AbstractMetadataTableModel {\n private static final long serialVersionUID = 1L;\n\n private final DynaProperty[] properties;\n\n private final DynaBean content;\n\n private MediaMetadataTableModel(final DynaBean directoryContent) {\n this.properties = directoryContent.getDynaClass().getDynaProperties();\n this.content = directoryContent;\n }\n\n @Override\n public int getRowCount() {\n return properties.length;\n }\n\n @Override\n public Object getValueAt(final int rowIndex, final int columnIndex) {\n final Object value;\n final DynaProperty property = this.properties[rowIndex];\n switch (columnIndex) {\n case 0:\n value = property.getName();\n break;\n case 1:\n value = content.get(property.getName());\n break;\n default:\n throw new IndexOutOfBoundsException(\"No such column: \" + columnIndex);\n }\n return value;\n }\n\n }\n}", "public final class OtherMetadataTable extends AbstractMetadataTable<Map<String, Object>> {\n\n private static final long serialVersionUID = 1L;\n\n public OtherMetadataTable(final String title, final Map<String, Object> content) {\n super(title, content);\n }\n\n @Override\n protected TableModel getTableModel(final Map<String, Object> content) {\n return new OtherMetadataTableModel(content);\n }\n\n private static final class OtherMetadataTableModel extends SimpleMetadataTableModel<Map<String, Object>> {\n\n private static final long serialVersionUID = 1L;\n\n public OtherMetadataTableModel(final Map<String, Object> content) {\n super(content);\n }\n\n @Override\n protected List<Entry> getValues(final Map<String, Object> content) {\n final List<Entry> values = new ArrayList<>(content.size());\n for (final Map.Entry<String, Object> entry : content.entrySet()) {\n final String value;\n if (entry.getValue() == null) {\n value = \"\";\n } else if (entry.getValue().getClass().isArray()) {\n value = Arrays.toString((Object[]) entry.getValue());\n } else {\n value = String.valueOf(entry.getValue());\n }\n values.add(new Entry(entry.getKey(), value));\n }\n return values;\n }\n\n }\n}" ]
import comeon.core.Core; import comeon.ui.UI; import comeon.ui.media.metadata.ExternalMetadataTable; import comeon.ui.media.metadata.MediaMetadataTable; import comeon.ui.media.metadata.OtherMetadataTable; import org.apache.commons.beanutils.DynaBean; import javax.swing.*; import java.awt.*; import java.util.HashMap; import java.util.Map;
package comeon.ui.media; final class MediaMetadataPanel extends JPanel { private static final long serialVersionUID = 1L; public static final int PREVIEW_WIDTH = (int) (UI.METADATA_PANEL_WIDTH * 0.9); public MediaMetadataPanel(final MediaPanels panels) { super(new BorderLayout()); this.setMinimumSize(new Dimension(UI.METADATA_PANEL_WIDTH, 0)); this.setMaximumSize(new Dimension(UI.METADATA_PANEL_WIDTH, Integer.MAX_VALUE)); this.setBackground(UI.NEUTRAL_GREY); this.setOpaque(true); final Dimension previewPanelDimension = new Dimension(UI.METADATA_PANEL_WIDTH, UI.METADATA_PANEL_WIDTH); final Dimension previewDimension; if (panels.getThumbnail().getWidth() >= panels.getThumbnail().getHeight()) { previewDimension = ConstrainedAxis.HORIZONTAL.getPreviewPanelDimension(panels.getThumbnail(), PREVIEW_WIDTH); } else { previewDimension = ConstrainedAxis.VERTICAL.getPreviewPanelDimension(panels.getThumbnail(), PREVIEW_WIDTH); } final MediaPreviewPanel previewPanel = new MediaPreviewPanel(panels, previewPanelDimension, (previewPanelDimension.width - previewDimension.width) / 2, (previewPanelDimension.height - previewDimension.height) / 2); this.add(previewPanel, BorderLayout.NORTH); final Box metadataBox = new Box(BoxLayout.Y_AXIS); final Map<String, Object> otherMetadata = new HashMap<>(); for (final Map.Entry<String, Object> dir : panels.getMedia().getMetadata().entrySet()) { if (dir.getValue() instanceof DynaBean) { final MediaMetadataTable table = new MediaMetadataTable(dir.getKey(), (DynaBean) dir.getValue()); metadataBox.add(table, 0);
} else if (Core.EXTERNAL_METADATA_KEY.equals(dir.getKey())) {
0
douo/ActivityBuilder
library/src/main/java/info/dourok/esactivity/BaseResultConsumer.java
[ "@FunctionalInterface\npublic interface BiConsumer<T, U> {\n\n /**\n * Performs this operation on the given arguments.\n *\n * @param t the first input argument\n * @param u the second input argument\n */\n void accept(T t, U u);\n\n}", "@FunctionalInterface\npublic interface Consumer<T> {\n\n /**\n * Performs this operation on the given argument.\n *\n * @param t the input argument\n */\n void accept(T t);\n}", "@FunctionalInterface\npublic interface TriConsumer<T, U, V> {\n\n /**\n * Performs this operation on the given arguments.\n *\n * @param t the first input argument\n * @param u the second input argument\n * @param v the third input argument\n */\n void accept(T t, U u, V v);\n}", "public class ActivityReferenceUpdater extends AbstractActivityReferenceUpdater {\n @Override\n protected Object findNewObject(Activity activity, Field field, Object lambda, Object oldObject) {\n return activity;\n }\n\n @Override\n protected boolean isMatch(Field field) {\n return Activity.class.isAssignableFrom(field.getType());\n }\n}", "public class FragmentReferenceUpdater extends AbstractActivityReferenceUpdater {\n private Map<Field, Function<Activity, Object>> map = new HashMap<>(4);\n\n /** 缓存 Fragment Finder. fragment makeInactive 之后状态会被清空,所以得提前对 Fragment 的 id 或 tag 进行保存。 */\n @Override\n public void beforeAdd(Object lambda) {\n Class zlass = lambda.getClass();\n for (Field field : zlass.getDeclaredFields()) {\n field.setAccessible(true);\n try {\n Function<Activity, Object> fragmentFinder = null;\n if (Fragment.class.isAssignableFrom(field.getType())) {\n Fragment fragment = (Fragment) field.get(lambda);\n if (fragment.getId() != NO_ID) {\n int id = fragment.getId();\n fragmentFinder =\n (Activity activity) -> activity.getFragmentManager().findFragmentById(id);\n } else if (fragment.getTag() != null) {\n String tag = fragment.getTag();\n fragmentFinder =\n (Activity activity) -> activity.getFragmentManager().findFragmentByTag(tag);\n }\n // Support Fragment\n } else if (android.support.v4.app.Fragment.class.isAssignableFrom(field.getType())) {\n android.support.v4.app.Fragment fragment =\n (android.support.v4.app.Fragment) field.get(lambda);\n if (fragment.getId() != NO_ID) {\n int id = fragment.getId();\n fragmentFinder =\n (Activity activity) ->\n ((FragmentActivity) activity).getSupportFragmentManager().findFragmentById(id);\n } else if (fragment.getTag() != null) {\n String tag = fragment.getTag();\n fragmentFinder =\n (Activity activity) ->\n ((FragmentActivity) activity)\n .getSupportFragmentManager()\n .findFragmentByTag(tag);\n }\n }\n if (fragmentFinder != null) {\n map.put(field, fragmentFinder);\n }\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n }\n }\n }\n\n @Override\n protected Object findNewObject(Activity activity, Field field, Object lambda, Object oldObject) {\n final boolean fragmentNeedUpdate =\n oldObject instanceof Fragment\n // Fragment detach 之后 Activity 应该为空\n && (((Fragment) oldObject).getActivity() == null\n || ((Fragment) oldObject).getActivity() != activity);\n final boolean supportFragmentNeedUpdate =\n oldObject instanceof android.support.v4.app.Fragment\n && (((android.support.v4.app.Fragment) oldObject).getActivity() == null\n || ((android.support.v4.app.Fragment) oldObject).getActivity() != activity);\n if (fragmentNeedUpdate || supportFragmentNeedUpdate) {\n // isMatch 已经确保了 map.get(field) 不为空\n return map.get(field).apply(activity);\n } else {\n return null;\n }\n }\n\n @Override\n protected boolean isMatch(Field field) {\n // XXX 一个 Lambda 表达式只有一个实例(断言)\n // 所以用 field 就能够确保唯一性\n return map.containsKey(field);\n }\n}", "public class ViewReferenceUpdater extends AbstractActivityReferenceUpdater {\n @Override\n protected Object findNewObject(Activity activity, Field field, Object lambda, Object oldObject) {\n View view = (View) oldObject;\n if (view.getContext() != activity) {\n View newView = null;\n if (view.getId() != View.NO_ID) {\n newView = activity.findViewById(view.getId());\n }\n return newView;\n }\n return null;\n }\n\n @Override\n protected boolean isMatch(Field field) {\n return View.class.isAssignableFrom(field.getType());\n }\n}" ]
import android.app.Activity; import android.content.Intent; import android.support.annotation.Nullable; import info.dourok.esactivity.function.BiConsumer; import info.dourok.esactivity.function.Consumer; import info.dourok.esactivity.function.TriConsumer; import info.dourok.esactivity.reference.ActivityReferenceUpdater; import info.dourok.esactivity.reference.FragmentReferenceUpdater; import info.dourok.esactivity.reference.ViewReferenceUpdater; import java.util.ArrayList; import java.util.List;
package info.dourok.esactivity; /** * @author tiaolins * @param <A> the starter activity * @date 2017/8/6 */ public class BaseResultConsumer<A extends Activity> implements TriConsumer<Activity, Integer, Intent>, LambdaStateCallback { private BiConsumer<Integer, Intent> biConsumer; private Consumer<Intent> okConsumer; private Consumer<Intent> cancelConsumer; private List<LambdaStateCallback> callbackList = new ArrayList<>(4); {
callbackList.add(new ActivityReferenceUpdater());
3
mojohaus/jaxb2-maven-plugin
src/test/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/JavaDocExtractorTest.java
[ "public class ClassLocation extends PackageLocation {\n\n // Internal state\n private String className;\n private String classXmlName;\n\n /**\n * Creates a new ClassLocation with the supplied package and class names.\n *\n * @param packageName The name of the package for a class potentially holding JavaDoc. Cannot be {@code null}.\n * @param classXmlName The name given as the {@link XmlType#name()} value of an annotation placed on the Class,\n * or {@code null} if none is provided.\n * @param className The (simple) name of a class. Cannot be null or empty.\n */\n public ClassLocation(final String packageName, final String className, final String classXmlName) {\n\n super(packageName);\n\n // Check sanity\n Validate.notEmpty(className, \"className\");\n\n // Assign internal state\n this.className = className;\n this.classXmlName = classXmlName;\n }\n\n /**\n * Retrieves the simple class name for the class potentially holding JavaDoc. Never {@code null} or empty.\n *\n * @return The simple class name for the class potentially holding JavaDoc. Never {@code null} or empty.\n */\n public String getClassName() {\n return classXmlName == null ? className : classXmlName;\n }\n\n /**\n * Always appends the <strong>effective className</strong> to the path from the superclass {@link PackageLocation}.\n * If the {@link #getAnnotationRenamedTo()} method returns a non-null value, that value is the effective className.\n * Otherwise, the {@link #getClassName()} method is used as the effective className.\n *\n * This is to handle renames such as provided in a {@link jakarta.xml.bind.annotation.XmlType} annotation's\n * {@link XmlType#name()} attribute value.\n *\n * @return the path of the PackageLocation superclass, appended with the effective className.\n * @see XmlType\n * @see XmlAttribute#name()\n * @see XmlElement#name()\n */\n @Override\n public String getPath() {\n return super.toString() + \".\" + getClassName();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String getAnnotationRenamedTo() {\n return classXmlName;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public int hashCode() {\n return this.toString().hashCode();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String toString() {\n\n final String xmlOverriddenFrom = classXmlName != null && !className.equals(classXmlName)\n ? \" (from: \" + className + \")\"\n : \"\";\n\n return super.toString() + \".\" + getClassName() + xmlOverriddenFrom;\n }\n}", "public class FieldLocation extends ClassLocation {\n\n // Internal state\n private String memberName;\n private String memberXmlName;\n\n /**\n * Creates a new FieldLocation with the supplied package, class and member names.\n *\n * @param packageName The name of the package for a class potentially holding JavaDoc. Cannot be {@code null}.\n * @param className The (simple) name of a class. Cannot be null or empty.\n * @param memberName The name of a (method or) field. Cannot be null or empty.\n * @param classXmlName The name given as the {@link XmlType#name()} value of an annotation placed on the Class,\n * or {@code null} if none is provided.\n * @param memberXmlName The name given as the {@link XmlElement#name()} or {@link XmlAttribute#name()} value of\n * an annotation placed on this Field, or {@code null} if none is provided.\n */\n public FieldLocation(final String packageName,\n final String className,\n final String classXmlName,\n final String memberName,\n final String memberXmlName) {\n\n // Delegate\n super(packageName, className, classXmlName);\n\n // Check sanity\n Validate.notEmpty(memberName, \"memberName\");\n\n // Assign internal state\n this.memberName = memberName;\n this.memberXmlName = memberXmlName;\n }\n\n /**\n * Retrieves the name of the member (i.e. method or field), potentially holding JavaDoc.\n *\n * @return The name of the member (i.e. method or field), potentially holding JavaDoc.\n * Never null or empty.\n */\n public String getMemberName() {\n return memberXmlName == null ? memberName : memberXmlName;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String getAnnotationRenamedTo() {\n return memberXmlName;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String getPath() {\n return super.getPath() + \"#\" + getMemberName();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String toString() {\n\n final String xmlOverriddenFrom = memberXmlName != null && !memberName.equals(memberXmlName)\n ? \" (from: \" + memberName + \")\"\n : \"\";\n\n return super.toString() + \"#\" + getMemberName() + xmlOverriddenFrom;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public int hashCode() {\n return this.toString().hashCode();\n }\n}", "public class MethodLocation extends FieldLocation {\n\n /**\n * Signature for a method without any parameters.\n */\n public static final String NO_PARAMETERS = \"()\";\n\n /**\n * Separator for a method's parameters.\n */\n public static final String PARAMETER_SEPARATOR = \",\";\n\n // Internal state\n private String parameters = NO_PARAMETERS;\n\n /**\n * Creates a new MethodLocation with the supplied package, class and member names.\n *\n * @param packageName The name of the package for a class potentially holding JavaDoc. Cannot be {@code null}.\n * @param className The (simple) name of a class. Cannot be null or empty.\n * @param classXmlName The name given as the {@link XmlType#name()} value of an annotation placed on the Class,\n * or {@code null} if none is provided.\n * @param memberName The name of a (method or) field. Cannot be null or empty.\n * @param memberXmlName The name given as the {@link XmlElement#name()} or {@link XmlAttribute#name()} value of\n * an annotation placed on this Field, or {@code null} if none is provided.\n * @param parameters The names of the types which are parameters to this method.\n */\n public MethodLocation(final String packageName,\n final String className,\n final String classXmlName,\n final String memberName,\n final String memberXmlName,\n final List<JavaParameter> parameters) {\n\n super(packageName, className, classXmlName, memberName, memberXmlName);\n\n // Check sanity\n Validate.notNull(parameters, \"parameters\");\n\n // Stringify the parameter types\n if (parameters.size() > 0) {\n final StringBuilder builder = new StringBuilder();\n\n for (JavaParameter current : parameters) {\n builder.append(current.getType().getFullyQualifiedName()).append(PARAMETER_SEPARATOR);\n }\n this.parameters = \"(\" + builder.substring(0, builder.lastIndexOf(PARAMETER_SEPARATOR)) + \")\";\n }\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String getPath() {\n return super.getPath() + parameters;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String toString() {\n return super.toString() + parameters;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public int hashCode() {\n return this.toString().hashCode();\n }\n\n /**\n * @return The parameters, concatenated into a String.\n */\n public String getParametersAsString() {\n return parameters;\n }\n\n /**\n * @return True if this MethodLocation has no parameters.\n */\n public boolean hasNoParameters() {\n return NO_PARAMETERS.equals(parameters);\n }\n}", "public class PackageLocation implements SortableLocation {\n\n // Internal state\n private String packageName;\n\n /**\n * Creates a new PackageLocation with the supplied package name.\n *\n * @param packageName The name of the package potentially holding JavaDoc. Cannot be {@code null}.\n */\n public PackageLocation(final String packageName) {\n\n // Check sanity\n Validate.notNull(packageName, \"packageName\");\n\n // Assign internal state\n this.packageName = packageName;\n }\n\n /**\n * Retrieves the name of the package potentially holding JavaDoc.\n *\n * @return The name of the package potentially holding JavaDoc. Can be empty, but never {@code null}.\n */\n public String getPackageName() {\n return packageName;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean equals(final Object obj) {\n\n // Check sanity\n if (obj == this) {\n return true;\n }\n\n // Delegate\n return obj instanceof PackageLocation\n && toString().equals(obj.toString());\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public int hashCode() {\n return toString().hashCode();\n }\n\n /**\n * <strong>Note:</strong> Packages cannot be renamed from a JAXB annotation.\n * {@inheritDoc}\n */\n @Override\n public String getAnnotationRenamedTo() {\n return null;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String getPath() {\n return toString();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String toString() {\n return packageName;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean isEqualToPath(final String path) {\n\n // Check sanity\n Validate.notNull(path, \"path\");\n\n // All done.\n return toString().equals(path);\n }\n\n /**\n * <p>Compares the string representations of this PackageLocation and the supplied SortableLocation.</p>\n * {@inheritDoc}\n */\n @Override\n public int compareTo(final SortableLocation that) {\n\n // Check sanity\n Validate.notNull(that, \"that\");\n if (this == that) {\n return 0;\n }\n\n // Delegate\n return this.toString().compareTo(that.toString());\n }\n}", "public final class FileSystemUtilities {\n\n /*\n * Hide the constructor for utility classes.\n */\n private FileSystemUtilities() {\n // Do nothing\n }\n\n /**\n * FileFilter which accepts Files that exist and for which {@code File.isFile() } is {@code true}.\n */\n public static final FileFilter EXISTING_FILE = new FileFilter() {\n @Override\n public boolean accept(final File candidate) {\n return candidate != null && candidate.exists() && candidate.isFile();\n }\n };\n\n /**\n * FileFilter which accepts Files that exist and for which {@code File.isDirectory() } is {@code true}.\n */\n public static final FileFilter EXISTING_DIRECTORY = new FileFilter() {\n @Override\n public boolean accept(final File candidate) {\n return candidate != null && candidate.exists() && candidate.isDirectory();\n }\n };\n\n /**\n * Acquires the canonical path for the supplied file.\n *\n * @param file A non-null File for which the canonical path should be retrieved.\n * @return The canonical path of the supplied file.\n */\n public static String getCanonicalPath(final File file) {\n return getCanonicalFile(file).getPath();\n }\n\n /**\n * Non-valid Characters for naming files, folders under Windows: <code>\":\", \"*\", \"?\", \"\\\"\", \"<\", \">\", \"|\"</code>\n *\n * @see <a href=\"http://support.microsoft.com/?scid=kb%3Ben-us%3B177506&x=12&y=13\">\n * http://support.microsoft.com/?scid=kb%3Ben-us%3B177506&x=12&y=13</a>\n * @see org.codehaus.plexus.util.FileUtils\n */\n private static final String[] INVALID_CHARACTERS_FOR_WINDOWS_FILE_NAME = {\":\", \"*\", \"?\", \"\\\"\", \"<\", \">\", \"|\"};\n\n /**\n * Acquires the canonical File for the supplied file.\n *\n * @param file A non-null File for which the canonical File should be retrieved.\n * @return The canonical File of the supplied file.\n */\n public static File getCanonicalFile(final File file) {\n\n // Check sanity\n Validate.notNull(file, \"file\");\n\n // All done\n try {\n return file.getCanonicalFile();\n } catch (IOException e) {\n throw new IllegalArgumentException(\"Could not acquire the canonical file for [\"\n + file.getAbsolutePath() + \"]\", e);\n }\n }\n\n /**\n * <p>Retrieves the canonical File matching the supplied path in the following order or priority:</p>\n * <ol>\n * <li><strong>Absolute path:</strong> The path is used by itself (i.e. {@code new File(path);}). If an\n * existing file or directory matches the provided path argument, its canonical path will be returned.</li>\n * <li><strong>Relative path:</strong> The path is appended to the baseDir (i.e.\n * {@code new File(baseDir, path);}). If an existing file or directory matches the provided path argument,\n * its canonical path will be returned. Only in this case will be baseDir argument be considered.</li>\n * </ol>\n * <p>If no file or directory could be derived from the supplied path and baseDir, {@code null} is returned.</p>\n *\n * @param path A non-null path which will be used to find an existing file or directory.\n * @param baseDir A directory to which the path will be appended to search for the existing file or directory in\n * case the file was nonexistent when interpreted as an absolute path.\n * @return either a canonical File for the path, or {@code null} if no file or directory matched\n * the supplied path and baseDir.\n */\n public static File getExistingFile(final String path, final File baseDir) {\n\n // Check sanity\n Validate.notEmpty(path, \"path\");\n final File theFile = new File(path);\n File toReturn = null;\n\n // Is 'path' absolute?\n if (theFile.isAbsolute() && (EXISTING_FILE.accept(theFile) || EXISTING_DIRECTORY.accept(theFile))) {\n toReturn = getCanonicalFile(theFile);\n }\n\n // Is 'path' relative?\n if (!theFile.isAbsolute()) {\n\n // In this case, baseDir cannot be null.\n Validate.notNull(baseDir, \"baseDir\");\n final File relativeFile = new File(baseDir, path);\n\n if (EXISTING_FILE.accept(relativeFile) || EXISTING_DIRECTORY.accept(relativeFile)) {\n toReturn = getCanonicalFile(relativeFile);\n }\n }\n\n // The path provided did not point to an existing File or Directory.\n return toReturn;\n }\n\n /**\n * Retrieves the URL for the supplied File. Convenience method which hides exception handling\n * for the operation in question.\n *\n * @param aFile A File for which the URL should be retrieved.\n * @return The URL for the supplied aFile.\n * @throws java.lang.IllegalArgumentException if getting the URL yielded a MalformedURLException.\n */\n public static URL getUrlFor(final File aFile) throws IllegalArgumentException {\n\n // Check sanity\n Validate.notNull(aFile, \"aFile\");\n\n try {\n return aFile.toURI().normalize().toURL();\n } catch (MalformedURLException e) {\n throw new IllegalArgumentException(\"Could not retrieve the URL from file [\"\n + getCanonicalPath(aFile) + \"]\", e);\n }\n }\n\n /**\n * Acquires the file for a supplied URL, provided that its protocol is is either a file or a jar.\n *\n * @param anURL a non-null URL.\n * @param encoding The encoding to be used by the URLDecoder to decode the path found.\n * @return The File pointing to the supplied URL, for file or jar protocol URLs and null otherwise.\n */\n public static File getFileFor(final URL anURL, final String encoding) {\n\n // Check sanity\n Validate.notNull(anURL, \"anURL\");\n Validate.notNull(encoding, \"encoding\");\n\n final String protocol = anURL.getProtocol();\n File toReturn = null;\n if (\"file\".equalsIgnoreCase(protocol)) {\n try {\n final String decodedPath = URLDecoder.decode(anURL.getPath(), encoding);\n toReturn = new File(decodedPath);\n } catch (Exception e) {\n throw new IllegalArgumentException(\"Could not get the File for [\" + anURL + \"]\", e);\n }\n } else if (\"jar\".equalsIgnoreCase(protocol)) {\n\n try {\n\n // Decode the JAR\n final String tmp = URLDecoder.decode(anURL.getFile(), encoding);\n\n // JAR URLs generally contain layered protocols, such as:\n // jar:file:/some/path/to/nazgul-tools-validation-aspect-4.0.2.jar!/the/package/ValidationAspect.class\n final URL innerURL = new URL(tmp);\n\n // We can handle File protocol URLs here.\n if (\"file\".equalsIgnoreCase(innerURL.getProtocol())) {\n\n // Peel off the inner protocol\n final String innerUrlPath = innerURL.getPath();\n final String filePath = innerUrlPath.contains(\"!\")\n ? innerUrlPath.substring(0, innerUrlPath.indexOf(\"!\"))\n : innerUrlPath;\n toReturn = new File(URLDecoder.decode(filePath, encoding));\n }\n } catch (Exception e) {\n throw new IllegalArgumentException(\"Could not get the File for [\" + anURL + \"]\", e);\n }\n }\n\n // All done.\n return toReturn;\n }\n\n\n /**\n * Filters files found either in the sources paths (or in the standardDirectory if no explicit sources are given),\n * and retrieves a List holding those files that do not match any of the supplied Java Regular Expression\n * excludePatterns.\n *\n * @param baseDir The non-null basedir Directory.\n * @param sources The sources which should be either absolute or relative (to the given baseDir)\n * paths to files or to directories that should be searched recursively for files.\n * @param standardDirectories If no sources are given, revert to searching all files under these standard\n * directories. Each path is {@code relativize()}-d to the supplied baseDir to\n * reach a directory path.\n * @param log A non-null Maven Log for logging any operations performed.\n * @param fileTypeDescription A human-readable short description of what kind of files are searched for, such as\n * \"xsdSources\" or \"xjbSources\".\n * @param excludePatterns An optional List of patterns used to construct an ExclusionRegExpFileFilter used to\n * identify files which should be excluded from the result.\n * @return URLs to all Files under the supplied sources (or standardDirectories, if no explicit sources\n * are given) which do not match the supplied Java Regular excludePatterns.\n */\n @SuppressWarnings(\"all\")\n public static List<URL> filterFiles(final File baseDir,\n final List<String> sources,\n final List<String> standardDirectories,\n final Log log,\n final String fileTypeDescription,\n final List<Filter<File>> excludePatterns) {\n\n final SortedMap<String, File> pathToResolvedSourceMap = new TreeMap<String, File>();\n\n for (String current : standardDirectories) {\n for (File currentResolvedSource : FileSystemUtilities.filterFiles(\n baseDir,\n sources,\n FileSystemUtilities.relativize(current, baseDir, true),\n log,\n fileTypeDescription,\n excludePatterns)) {\n\n // Add the source\n pathToResolvedSourceMap.put(\n FileSystemUtilities.getCanonicalPath(currentResolvedSource),\n currentResolvedSource);\n }\n }\n\n final List<URL> toReturn = new ArrayList<URL>();\n\n // Extract the URLs for all resolved Java sources.\n for (Map.Entry<String, File> current : pathToResolvedSourceMap.entrySet()) {\n toReturn.add(FileSystemUtilities.getUrlFor(current.getValue()));\n }\n\n if (log.isDebugEnabled()) {\n\n final StringBuilder builder = new StringBuilder();\n builder.append(\"\\n+=================== [Filtered \" + fileTypeDescription + \"]\\n\");\n\n builder.append(\"|\\n\");\n builder.append(\"| \" + excludePatterns.size() + \" Exclude patterns:\\n\");\n for (int i = 0; i < excludePatterns.size(); i++) {\n builder.append(\"| [\" + (i + 1) + \"/\" + excludePatterns.size() + \"]: \" + excludePatterns.get(i) + \"\\n\");\n }\n\n builder.append(\"|\\n\");\n builder.append(\"| \" + standardDirectories.size() + \" Standard Directories:\\n\");\n for (int i = 0; i < standardDirectories.size(); i++) {\n builder.append(\"| [\" + (i + 1) + \"/\" + standardDirectories.size() + \"]: \"\n + standardDirectories.get(i) + \"\\n\");\n }\n\n builder.append(\"|\\n\");\n builder.append(\"| \" + toReturn.size() + \" Results:\\n\");\n for (int i = 0; i < toReturn.size(); i++) {\n builder.append(\"| [\" + (i + 1) + \"/\" + toReturn.size() + \"]: \" + toReturn.get(i) + \"\\n\");\n }\n builder.append(\"|\\n\");\n builder.append(\"+=================== [End Filtered \" + fileTypeDescription + \"]\\n\\n\");\n\n // Log all.\n log.debug(builder.toString().replace(\"\\n\", AbstractJaxbMojo.NEWLINE));\n }\n\n // All done.\n return toReturn;\n }\n\n /**\n * Filters files found either in the sources paths (or in the standardDirectory if no explicit sources are given),\n * and retrieves a List holding those files that do not match any of the supplied Java Regular Expression\n * excludePatterns.\n *\n * @param baseDir The non-null basedir Directory.\n * @param sources The sources which should be either absolute or relative (to the given baseDir)\n * paths to files or to directories that should be searched recursively for files.\n * @param standardDirectory If no sources are given, revert to searching all files under this standard directory.\n * This is the path appended to the baseDir to reach a directory.\n * @param log A non-null Maven Log for logging any operations performed.\n * @param fileTypeDescription A human-readable short description of what kind of files are searched for, such as\n * \"xsdSources\" or \"xjbSources\".\n * @param excludeFilters An optional List of Filters used to identify files which should be excluded from\n * the result.\n * @return All files under the supplied sources (or standardDirectory, if no explicit sources are given) which\n * do not match the supplied Java Regular excludePatterns.\n */\n @SuppressWarnings(\"CheckStyle\")\n public static List<File> filterFiles(final File baseDir,\n final List<String> sources,\n final String standardDirectory,\n final Log log,\n final String fileTypeDescription,\n final List<Filter<File>> excludeFilters) {\n\n // Check sanity\n Validate.notNull(baseDir, \"baseDir\");\n Validate.notNull(log, \"log\");\n Validate.notEmpty(standardDirectory, \"standardDirectory\");\n Validate.notEmpty(fileTypeDescription, \"fileTypeDescription\");\n\n // No sources provided? Fallback to the standard (which should be a relative path).\n List<String> effectiveSources = sources;\n if (sources == null || sources.isEmpty()) {\n effectiveSources = new ArrayList<String>();\n\n final File tmp = new File(standardDirectory);\n final File rootDirectory = tmp.isAbsolute() ? tmp : new File(baseDir, standardDirectory);\n effectiveSources.add(FileSystemUtilities.getCanonicalPath(rootDirectory));\n }\n\n // First, remove the non-existent sources.\n List<File> existingSources = new ArrayList<File>();\n for (String current : effectiveSources) {\n\n final File existingFile = FileSystemUtilities.getExistingFile(current, baseDir);\n if (existingFile != null) {\n existingSources.add(existingFile);\n\n if (log.isDebugEnabled()) {\n log.debug(\"Accepted configured \" + fileTypeDescription + \" [\"\n + FileSystemUtilities.getCanonicalFile(existingFile) + \"]\");\n }\n } else {\n if (log.isInfoEnabled()) {\n log.info(\"Ignored given or default \" + fileTypeDescription + \" [\" + current\n + \"], since it is not an existent file or directory.\");\n }\n }\n }\n\n if (log.isDebugEnabled() && existingSources.size() > 0) {\n\n final int size = existingSources.size();\n\n log.debug(\" [\" + size + \" existing \" + fileTypeDescription + \"] ...\");\n for (int i = 0; i < size; i++) {\n log.debug(\" \" + (i + 1) + \"/\" + size + \": \" + existingSources.get(i));\n }\n log.debug(\" ... End [\" + size + \" existing \" + fileTypeDescription + \"]\");\n }\n\n // All Done.\n return FileSystemUtilities.resolveRecursively(existingSources, excludeFilters, log);\n }\n\n /**\n * Filters all supplied files using the provided {@code acceptFilter}.\n *\n * @param files The list of files to resolve, filter and return. If the {@code files} List\n * contains directories, they are searched for Files recursively. Any found Files in such\n * a search are included in the resulting File List if they match the acceptFilter supplied.\n * @param acceptFilter A filter matched to all files in the given List. If the acceptFilter matches a file, it is\n * included in the result.\n * @param log The active Maven Log.\n * @return All files in (or files in subdirectories of directories provided in) the files List, provided that each\n * file is accepted by an ExclusionRegExpFileFilter.\n */\n public static List<File> filterFiles(final List<File> files, final Filter<File> acceptFilter, final Log log) {\n\n // Check sanity\n Validate.notNull(files, \"files\");\n\n final List<File> toReturn = new ArrayList<File>();\n\n if (files.size() > 0) {\n for (File current : files) {\n\n final boolean isAcceptedFile = EXISTING_FILE.accept(current) && acceptFilter.accept(current);\n final boolean isAcceptedDirectory = EXISTING_DIRECTORY.accept(current) && acceptFilter.accept(current);\n\n if (isAcceptedFile) {\n toReturn.add(current);\n } else if (isAcceptedDirectory) {\n recurseAndPopulate(toReturn, Collections.singletonList(acceptFilter), current, false, log);\n }\n }\n }\n\n // All done\n return toReturn;\n }\n\n /**\n * Retrieves a List of Files containing all the existing files within the supplied files List, including all\n * files found in directories recursive to any directories provided in the files list. Each file included in the\n * result must pass an ExclusionRegExpFileFilter synthesized from the supplied exclusions pattern(s).\n *\n * @param files The list of files to resolve, filter and return. If the {@code files} List\n * contains directories, they are searched for Files recursively. Any found Files in such\n * a search are included in the resulting File List if they do not match any of the\n * exclusionFilters supplied.\n * @param exclusionFilters A List of Filters which identify files to remove from the result - implying that any\n * File matched by any of these exclusionFilters will not be included in the result.\n * @param log The active Maven Log.\n * @return All files in (or files in subdirectories of directories provided in) the files List, provided that each\n * file is accepted by an ExclusionRegExpFileFilter.\n */\n public static List<File> resolveRecursively(final List<File> files,\n final List<Filter<File>> exclusionFilters,\n final Log log) {\n\n // Check sanity\n Validate.notNull(files, \"files\");\n\n final List<Filter<File>> effectiveExclusions = exclusionFilters == null\n ? new ArrayList<Filter<File>>()\n : exclusionFilters;\n\n final List<File> toReturn = new ArrayList<File>();\n\n if (files.size() > 0) {\n for (File current : files) {\n\n final boolean isAcceptedFile = EXISTING_FILE.accept(current)\n && Filters.noFilterMatches(current, effectiveExclusions);\n final boolean isAcceptedDirectory = EXISTING_DIRECTORY.accept(current)\n && Filters.noFilterMatches(current, effectiveExclusions);\n\n if (isAcceptedFile) {\n toReturn.add(current);\n } else if (isAcceptedDirectory) {\n recurseAndPopulate(toReturn, effectiveExclusions, current, true, log);\n }\n }\n }\n\n // All done\n return toReturn;\n }\n\n /**\n * Convenience method to successfully create a directory - or throw an exception if failing to create it.\n *\n * @param aDirectory The directory to create.\n * @param cleanBeforeCreate if {@code true}, the directory and all its content will be deleted before being\n * re-created. This will ensure that the created directory is really clean.\n * @throws MojoExecutionException if the aDirectory could not be created (and/or cleaned).\n */\n public static void createDirectory(final File aDirectory, final boolean cleanBeforeCreate)\n throws MojoExecutionException {\n\n // Check sanity\n Validate.notNull(aDirectory, \"aDirectory\");\n validateFileOrDirectoryName(aDirectory);\n\n // Clean an existing directory?\n if (cleanBeforeCreate) {\n try {\n FileUtils.deleteDirectory(aDirectory);\n } catch (IOException e) {\n throw new MojoExecutionException(\"Could not clean directory [\" + getCanonicalPath(aDirectory) + \"]\", e);\n }\n }\n\n // Now, make the required directory, if it does not already exist as a directory.\n final boolean existsAsFile = aDirectory.exists() && aDirectory.isFile();\n if (existsAsFile) {\n throw new MojoExecutionException(\"[\" + getCanonicalPath(aDirectory) + \"] exists and is a file. \"\n + \"Cannot make directory\");\n } else if (!aDirectory.exists() && !aDirectory.mkdirs()) {\n throw new MojoExecutionException(\"Could not create directory [\" + getCanonicalPath(aDirectory) + \"]\");\n }\n }\n\n /**\n * If the supplied path refers to a file or directory below the supplied basedir, the returned\n * path is identical to the part below the basedir.\n *\n * @param path The path to strip off basedir path from, and return.\n * @param parentDir The maven project basedir.\n * @param removeInitialFileSep If true, an initial {@code File#separator} is removed before returning.\n * @return The path relative to basedir, if it is situated below the basedir. Otherwise the supplied path.\n */\n public static String relativize(final String path,\n final File parentDir,\n final boolean removeInitialFileSep) {\n\n // Check sanity\n Validate.notNull(path, \"path\");\n Validate.notNull(parentDir, \"parentDir\");\n\n final Path p = Paths.get(path);\n final Path pd = parentDir.toPath();\n\n String platformSpecificPath;\n if (p.normalize().startsWith(pd.normalize().toString())) {\n platformSpecificPath = pd.relativize(p).toString();\n } else {\n platformSpecificPath = p.toString();\n }\n\n if (removeInitialFileSep && platformSpecificPath.startsWith(File.separator)) {\n platformSpecificPath = platformSpecificPath.substring(File.separator.length());\n }\n\n // NOTE: it appears this function is meant to preserve the file separator that was passed in the path\n if (path.indexOf('\\\\') == -1) {\n platformSpecificPath = platformSpecificPath.replace('\\\\', '/');\n }\n\n return platformSpecificPath;\n }\n\n /**\n * If the supplied fileOrDir is a File, it is added to the returned List if any of the filters Match.\n * If the supplied fileOrDir is a Directory, it is listed and any of the files immediately within the fileOrDir\n * directory are returned within the resulting List provided that they match any of the supplied filters.\n *\n * @param fileOrDir A File or Directory.\n * @param fileFilters A List of filter of which at least one must match to add the File\n * (or child Files, in case of a directory) to the resulting List.\n * @param log The active Maven Log\n * @return A List holding the supplied File (or child Files, in case fileOrDir is a Directory) given that at\n * least one Filter accepts them.\n */\n @SuppressWarnings(\"all\")\n public static List<File> listFiles(final File fileOrDir,\n final List<Filter<File>> fileFilters,\n final Log log) {\n return listFiles(fileOrDir, fileFilters, false, log);\n }\n\n /**\n * If the supplied fileOrDir is a File, it is added to the returned List if any of the filters Match.\n * If the supplied fileOrDir is a Directory, it is listed and any of the files immediately within the fileOrDir\n * directory are returned within the resulting List provided that they match any of the supplied filters.\n *\n * @param fileOrDir A File or Directory.\n * @param fileFilters A List of filter of which at least one must match to add the File (or child Files, in case\n * of a directory) to the resulting List.\n * @param excludeFilterOperation if {@code true}, all fileFilters are considered exclude filter, i.e. if\n * any of the Filters match the fileOrDir, that fileOrDir will be excluded from the\n * result.\n * @param log The active Maven Log\n * @return A List holding the supplied File (or child Files, in case fileOrDir is a Directory) given that at\n * least one Filter accepts them.\n */\n @SuppressWarnings(\"all\")\n public static List<File> listFiles(final File fileOrDir,\n final List<Filter<File>> fileFilters,\n final boolean excludeFilterOperation,\n final Log log) {\n\n // Check sanity\n Validate.notNull(log, \"log\");\n Validate.notNull(fileFilters, \"fileFilters\");\n final List<File> toReturn = new ArrayList<File>();\n\n if (EXISTING_FILE.accept(fileOrDir)) {\n checkAndAdd(toReturn, fileOrDir, fileFilters, excludeFilterOperation, log);\n } else if (EXISTING_DIRECTORY.accept(fileOrDir)) {\n\n final File[] listedFiles = fileOrDir.listFiles();\n\n if (listedFiles != null) {\n for (File current : listedFiles) {\n\n // Typically, hidden directories start with '.'\n // Except them from automagic filtering.\n if (current.getName().charAt(0) != '.') {\n checkAndAdd(toReturn, current, fileFilters, excludeFilterOperation, log);\n }\n }\n }\n }\n\n // All done.\n return toReturn;\n }\n\n //\n // Private helpers\n //\n\n private static void checkAndAdd(final List<File> toPopulate,\n final File current,\n final List<Filter<File>> fileFilters,\n final boolean excludeFilterOperation,\n final Log log) {\n\n //\n // When no filters are supplied...\n // [Include Operation]: all files will be rejected\n // [Exclude Operation]: all files will be included\n //\n final boolean noFilters = fileFilters == null || fileFilters.isEmpty();\n final boolean addFile = excludeFilterOperation\n ? noFilters || Filters.rejectAtLeastOnce(current, fileFilters)\n : noFilters || Filters.matchAtLeastOnce(current, fileFilters);\n final String logPrefix = (addFile ? \"Accepted \" : \"Rejected \")\n + (current.isDirectory() ? \"directory\" : \"file\") + \" [\";\n\n if (addFile) {\n toPopulate.add(current);\n }\n\n if (log.isDebugEnabled()) {\n log.debug(logPrefix + getCanonicalPath(current) + \"]\");\n }\n }\n\n private static void validateFileOrDirectoryName(final File fileOrDir) {\n\n if (Os.isFamily(Os.FAMILY_WINDOWS) && !FileUtils.isValidWindowsFileName(fileOrDir)) {\n throw new IllegalArgumentException(\n \"The file (\" + fileOrDir + \") cannot contain any of the following characters: \\n\"\n + StringUtils.join(INVALID_CHARACTERS_FOR_WINDOWS_FILE_NAME, \" \"));\n }\n }\n\n private static void recurseAndPopulate(final List<File> toPopulate,\n final List<Filter<File>> fileFilters,\n final File aDirectory,\n final boolean excludeOperation,\n final Log log) {\n\n final List<File> files = listFiles(aDirectory, fileFilters, excludeOperation, log);\n for (File current : files) {\n if (EXISTING_FILE.accept(current)) {\n toPopulate.add(current);\n }\n\n if (EXISTING_DIRECTORY.accept(current)) {\n recurseAndPopulate(toPopulate, fileFilters, current, excludeOperation, log);\n }\n }\n }\n}", "public interface Filter<T> {\n\n /**\n * Initializes this Filter, and assigns the supplied Log for use by this Filter.\n *\n * @param log The non-null Log which should be used by this Filter to emit log messages.\n */\n void initialize(Log log);\n\n /**\n * @return {@code true} if this Filter has been properly initialized (by a call to the {@code initialize} method).\n */\n boolean isInitialized();\n\n /**\n * <p>Method that is invoked to determine if a candidate instance should be accepted or not.\n * Implementing classes should be prepared to handle {@code null} candidate objects.</p>\n *\n * @param candidate The candidate that should be tested for acceptance by this Filter.\n * @return {@code true} if the candidate is accepted by this Filter and {@code false} otherwise.\n * @throws java.lang.IllegalStateException if this Filter is not initialized by a call to the\n * initialize method before calling this matchAtLeastOnce method.\n */\n boolean accept(T candidate) throws IllegalStateException;\n}", "@SuppressWarnings(\"all\")\npublic final class Filters {\n\n /**\n * Algorithms for accepting the supplied object if at least one of the supplied Filters accepts it.\n *\n * @param object The object to accept (or not).\n * @param filters The non-null list of Filters to examine the supplied object.\n * @param <T> The Filter type.\n * @return {@code true} if at least one of the filters return true from its accept method.\n * @see Filter#accept(Object)\n */\n public static <T> boolean matchAtLeastOnce(final T object, final List<Filter<T>> filters) {\n\n // Check sanity\n Validate.notNull(filters, \"filters\");\n\n boolean acceptedByAtLeastOneFilter = false;\n for (Filter<T> current : filters) {\n if (current.accept(object)) {\n acceptedByAtLeastOneFilter = true;\n break;\n }\n }\n\n // All done.\n return acceptedByAtLeastOneFilter;\n }\n\n /**\n * Algorithms for rejecting the supplied object if at least one of the supplied Filters does not accept it.\n *\n * @param object The object to reject (or not).\n * @param filters The non-null list of Filters to examine the supplied object.\n * @param <T> The Filter type.\n * @return {@code true} if at least one of the filters returns false from its accept method.\n * @see Filter#accept(Object)\n */\n public static <T> boolean rejectAtLeastOnce(final T object, final List<Filter<T>> filters) {\n\n // Check sanity\n Validate.notNull(filters, \"filters\");\n\n boolean rejectedByAtLeastOneFilter = false;\n for (Filter<T> current : filters) {\n if (!current.accept(object)) {\n rejectedByAtLeastOneFilter = true;\n break;\n }\n }\n\n // All done.\n return rejectedByAtLeastOneFilter;\n }\n\n /**\n * Algorithms for rejecting the supplied object if at least one of the supplied Filters rejects it.\n *\n * @param object The object to accept (or not).\n * @param filters The non-null list of Filters to examine the supplied object.\n * @param <T> The Filter type.\n * @return {@code true} if at least one of the filters return false from its accept method.\n * @see Filter#accept(Object)\n */\n public static <T> boolean noFilterMatches(final T object, final List<Filter<T>> filters) {\n\n // Check sanity\n Validate.notNull(filters, \"filters\");\n\n boolean matchedAtLeastOnce = false;\n for (Filter<T> current : filters) {\n if (current.accept(object)) {\n matchedAtLeastOnce = true;\n }\n }\n\n // All done.\n return !matchedAtLeastOnce;\n }\n\n /**\n * Adapts the Filter specification to the FileFilter interface, to enable immediate use\n * for filtering File lists.\n *\n * @param toAdapt The non-null Filter which should be adapted to a FileFilter interface.\n * @return If the {@code toAdapt} instance already implements the FileFilter interface, simply return the toAdapt\n * instance. Otherwise, returns a FileFilter interface which delegates its execution to the wrapped Filter.\n */\n public static FileFilter adapt(final Filter<File> toAdapt) {\n\n // Check sanity\n Validate.notNull(toAdapt, \"toAdapt\");\n\n // Already a FileFilter?\n if (toAdapt instanceof FileFilter) {\n return (FileFilter) toAdapt;\n }\n\n // Wrap and return.\n return new FileFilter() {\n @Override\n public boolean accept(final File candidate) {\n return toAdapt.accept(candidate);\n }\n };\n }\n\n /**\n * Adapts the supplied List of Filter specifications to a List of FileFilters.\n *\n * @param toAdapt The List of Filters to adapts.\n * @return A List holding FileFilter instances. If {@code toAdapt} is {@code null} or empty, an empty list is\n * returned from this method. Thus, this method will never return a {@code null} value.\n */\n public static List<FileFilter> adapt(final List<Filter<File>> toAdapt) {\n\n final List<FileFilter> toReturn = new ArrayList<FileFilter>();\n if (toAdapt != null) {\n for (Filter<File> current : toAdapt) {\n toReturn.add(adapt(current));\n }\n }\n\n // All done.\n return toReturn;\n }\n\n /**\n * Initializes the supplied Filters by assigning the given Log.\n *\n * @param log The active Maven Log.\n * @param filters The List of Filters to initialize.\n * @param <T> The Filter type.\n */\n public static <T> void initialize(final Log log, final List<Filter<T>> filters) {\n\n // Check sanity\n Validate.notNull(log, \"log\");\n Validate.notNull(filters, \"filters\");\n\n for (Filter<T> current : filters) {\n current.initialize(log);\n }\n }\n\n /**\n * Initializes the supplied Filters by assigning the given Log.\n *\n * @param log The active Maven Log.\n * @param filters The List of Filters to initialize.\n * @param <T> The Filter type.\n */\n public static <T> void initialize(final Log log, final Filter<T>... filters) {\n\n // Check sanity\n Validate.notNull(log, \"log\");\n\n if (filters != null) {\n for (Filter<T> current : filters) {\n current.initialize(log);\n }\n }\n }\n}", "public class PatternFileFilter extends AbstractPatternFilter<File> implements FileFilter {\n\n /**\n * Java RegExp pattern matching one or more letters/digits/punctuation characters.\n * It can be flexibly used to separate normative text in a pattern:\n * <ol>\n * <li>Pattern matching <strong>ends of strings</strong>. <code>PATTERN_LETTER_DIGIT_PUNCT + \"txt\"</code>\n * matches all file paths ending in \"txt\", such as \"some/foobar.txt\"</li>\n * <li>Pattern matching <strong>strings containing patterns</strong>. <code>PATTERN_LETTER_DIGIT_PUNCT +\n * \"foobar\" + PATTERN_LETTER_DIGIT_PUNCT</code> matches all file paths containing \"foobar\" such as\n * \"the/file/in/directory/foobar/blah.java\"</li>\n * <li>Pattern matching <strong>start of strings</strong>. <code>\"/some/prefix\"\n * + PATTERN_LETTER_DIGIT_PUNCT</code> matches all file paths starting in \"/some/prefix\", such as\n * \"some/prefix/another/specification.xsd\"</li>\n * </ol>\n */\n public static final String PATTERN_LETTER_DIGIT_PUNCT = \"(\\\\p{javaLetterOrDigit}|\\\\p{Punct})+\";\n\n /**\n * Converter returning the canonical and absolute path for a File.\n */\n public static final StringConverter<File> FILE_PATH_CONVERTER = new StringConverter<File>() {\n @Override\n public String convert(final File toConvert) {\n return FileSystemUtilities.getCanonicalPath(toConvert.getAbsoluteFile());\n }\n };\n\n /**\n * Compound constructor creating an PatternFileFilter from the supplied parameters.\n *\n * @param processNullValues if {@code true}, this PatternFileFilter process null candidate values.\n * @param patternPrefix a prefix to be prepended to any patterns submitted to\n * this PatternFileFilter\n * @param patterns The non-null list of Patters which should be applied within this\n * PatternFileFilter.\n * @param converter The StringConverter which converts Files to Strings for Pattern matching.\n * @param acceptCandidateOnPatternMatch if {@code true}, this PatternFileFilter will matchAtLeastOnce\n * candidate objects that match at least one of the supplied patterns.\n * if {@code false}, this PatternFileFilter will noFilterMatches\n * candidates that match at least one of the supplied patterns.\n */\n public PatternFileFilter(final boolean processNullValues,\n final String patternPrefix,\n final List<String> patterns,\n final StringConverter<File> converter,\n final boolean acceptCandidateOnPatternMatch) {\n super();\n\n // Assign internal state\n setProcessNullValues(processNullValues);\n setAcceptCandidateOnPatternMatch(acceptCandidateOnPatternMatch);\n setPatternPrefix(patternPrefix);\n setPatterns(patterns);\n setConverter(converter);\n }\n\n /**\n * Creates a new PatternFileFilter using the supplied patternStrings which are interpreted as file suffixes.\n * (I.e. prepended with {@code PATTERN_LETTER_DIGIT_PUNCT} and compiled to Patterns).\n * The {@code FILE_PATH_CONVERTER} is used to convert Files to strings.\n * The supplied {@code acceptCandidateOnPatternMatch} parameter indicates if this\n * PatternFileFilter accepts or rejects candidates that match any of the supplied patternStrings.\n *\n * @param patternStrings The list of patternStrings to be used as file path suffixes.\n * @param acceptCandidateOnPatternMatch if {@code true}, this PatternFileFilter will matchAtLeastOnce\n * candidate objects that match at least one of the supplied patterns.\n * if {@code false}, this PatternFileFilter will noFilterMatches\n * candidates that match at least one of the supplied patterns.\n * @see #FILE_PATH_CONVERTER\n * @see #PATTERN_LETTER_DIGIT_PUNCT\n * @see #convert(java.util.List, String)\n */\n public PatternFileFilter(final List<String> patternStrings, final boolean acceptCandidateOnPatternMatch) {\n this(false, PATTERN_LETTER_DIGIT_PUNCT, patternStrings, FILE_PATH_CONVERTER, acceptCandidateOnPatternMatch);\n }\n\n /**\n * Creates a new PatternFileFilter using the supplied patternStrings which are interpreted as file suffixes.\n * (I.e. prepended with {@code PATTERN_LETTER_DIGIT_PUNCT} and compiled to Patterns).\n * The {@code FILE_PATH_CONVERTER} is used to convert Files to strings.\n * The retrieved PatternFileFilter accepts candidates that match any of the supplied patternStrings.\n *\n * @param patterns The list of patternStrings to be used as file path suffixes.\n */\n public PatternFileFilter(final List<String> patterns) {\n this(false, PATTERN_LETTER_DIGIT_PUNCT, patterns, FILE_PATH_CONVERTER, true);\n }\n\n /**\n * <p>Creates a new PatternFileFilter with no patternStrings List, implying that calling this constructor must be\n * followed by a call to the {@code #setPatterns} method.</p>\n * <p>The default prefix is {@code PATTERN_LETTER_DIGIT_PUNCT}, the default StringConverter is\n * {@code FILE_PATH_CONVERTER} and this PatternFileFilter does by default accept candidates that match any of\n * the supplied PatternStrings (i.e. an include-mode filter)</p>\n */\n public PatternFileFilter() {\n this(false, PATTERN_LETTER_DIGIT_PUNCT, new ArrayList<String>(), FILE_PATH_CONVERTER, true);\n }\n\n /**\n * Creates a new List containing an exclude-mode PatternFileFilter using the supplied patternStrings which\n * are interpreted as file suffixes. (I.e. prepended with {@code PATTERN_LETTER_DIGIT_PUNCT} and compiled to\n * Patterns). The {@code FILE_PATH_CONVERTER} is used to convert Files to strings.\n *\n * @param patterns A List of suffix patterns to be used in creating a new ExclusionRegularExpressionFileFilter.\n * @param log The active Maven Log.\n * @return A List containing a PatternFileFilter using the supplied suffix patterns to match Files.\n * @see PatternFileFilter\n */\n public static List<Filter<File>> createExcludeFilterList(final Log log,\n final String... patterns) {\n return createFilterList(log, false, patterns);\n }\n\n /**\n * Creates a new List containing an include-mode PatternFileFilter using the supplied patternStrings which\n * are interpreted as file suffixes. (I.e. prepended with {@code PATTERN_LETTER_DIGIT_PUNCT} and compiled to\n * Patterns). The {@code FILE_PATH_CONVERTER} is used to convert Files to strings.\n *\n * @param patterns A List of suffix patterns to be used in creating a new ExclusionRegularExpressionFileFilter.\n * @param log The active Maven Log.\n * @return A List containing a PatternFileFilter using the supplied suffix patterns to match Files.\n * @see PatternFileFilter\n */\n public static List<Filter<File>> createIncludeFilterList(final Log log,\n final String... patterns) {\n return createFilterList(log, true, patterns);\n }\n\n //\n // Private helpers\n //\n\n private static List<Filter<File>> createFilterList(final Log log,\n final boolean includeOperation,\n final String... patterns) {\n\n // Check sanity\n Validate.notNull(patterns, \"patterns\");\n Validate.notNull(log, \"log\");\n\n // Convert and return.\n final List<Filter<File>> toReturn = new ArrayList<Filter<File>>();\n final List<String> patternStrings = Arrays.asList(patterns);\n toReturn.add(new PatternFileFilter(patternStrings, includeOperation));\n\n // Initialize the filters.\n Filters.initialize(log, toReturn);\n return toReturn;\n }\n}" ]
import org.codehaus.mojo.jaxb2.BufferingLog; import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.location.ClassLocation; import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.location.FieldLocation; import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.location.MethodLocation; import org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc.location.PackageLocation; import org.codehaus.mojo.jaxb2.shared.FileSystemUtilities; import org.codehaus.mojo.jaxb2.shared.Validate; import org.codehaus.mojo.jaxb2.shared.filters.Filter; import org.codehaus.mojo.jaxb2.shared.filters.Filters; import org.codehaus.mojo.jaxb2.shared.filters.pattern.PatternFileFilter; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import org.junit.Ignore;
package org.codehaus.mojo.jaxb2.schemageneration.postprocessing.javadoc; /** * @author <a href="mailto:[email protected]">Lennart J&ouml;relid</a>, jGuru Europe AB */ public class JavaDocExtractorTest { // Shared state private File javaDocBasicDir; private File javaDocAnnotatedDir; private File javaDocEnumsDir; private File javaDocXmlWrappersDir; private BufferingLog log; @Before public void setupSharedState() { log = new BufferingLog(BufferingLog.LogLevel.DEBUG); // Find the desired directory final URL dirURL = getClass() .getClassLoader() .getResource("testdata/schemageneration/javadoc/basic"); this.javaDocBasicDir = new File(dirURL.getPath()); Assert.assertTrue(javaDocBasicDir.exists() && javaDocBasicDir.isDirectory()); final URL annotatedDirURL = getClass() .getClassLoader() .getResource("testdata/schemageneration/javadoc/annotated"); this.javaDocAnnotatedDir = new File(annotatedDirURL.getPath()); Assert.assertTrue(javaDocAnnotatedDir.exists() && javaDocAnnotatedDir.isDirectory()); final URL enumsDirURL = getClass() .getClassLoader() .getResource("testdata/schemageneration/javadoc/enums"); this.javaDocEnumsDir = new File(enumsDirURL.getPath()); Assert.assertTrue(javaDocEnumsDir.exists() && javaDocEnumsDir.isDirectory()); final URL wrappersDirURL = getClass() .getClassLoader() .getResource("testdata/schemageneration/javadoc/xmlwrappers"); this.javaDocXmlWrappersDir = new File(wrappersDirURL.getPath()); Assert.assertTrue(javaDocXmlWrappersDir.exists() && javaDocXmlWrappersDir.isDirectory()); } @Test public void validateLogStatementsDuringProcessing() { // Assemble final JavaDocExtractor unitUnderTest = new JavaDocExtractor(log); final List<File> sourceDirs = Arrays.<File>asList(javaDocBasicDir); final List<File> sourceFiles = FileSystemUtilities.resolveRecursively(sourceDirs, null, log); // Act unitUnderTest.addSourceFiles(sourceFiles); final SearchableDocumentation ignoredResult = unitUnderTest.process(); // Assert final SortedMap<String, Throwable> logBuffer = log.getLogBuffer(); final List<String> keys = new ArrayList<String>(logBuffer.keySet()); /* * 000: (DEBUG) Accepted file [/Users/lj/Development/Projects/Codehaus/github_jaxb2_plugin/target/test-classes/testdata/schemageneration/javadoc/basic/NodeProcessor.java], * 001: (INFO) Processing [1] java sources., * 002: (DEBUG) Added package-level JavaDoc for [basic], * 003: (DEBUG) Added class-level JavaDoc for [basic.NodeProcessor], * 004: (DEBUG) Added method-level JavaDoc for [basic.NodeProcessor#accept(org.w3c.dom.Node)], * 005: (DEBUG) Added method-level JavaDoc for [basic.NodeProcessor#process(org.w3c.dom.Node)]] */ Assert.assertEquals(6, keys.size()); Assert.assertEquals("001: (INFO) Processing [1] java sources.", keys.get(1)); Assert.assertEquals("002: (DEBUG) Added package-level JavaDoc for [basic]", keys.get(2)); Assert.assertEquals("003: (DEBUG) Added class-level JavaDoc for [basic.NodeProcessor]", keys.get(3)); Assert.assertEquals("004: (DEBUG) Added method-level JavaDoc for [basic.NodeProcessor#accept(org.w3c.dom.Node)]", keys.get(4)); Assert.assertEquals("005: (DEBUG) Added method-level JavaDoc for [basic.NodeProcessor#process(org.w3c.dom.Node)]", keys.get(5)); } @Test @Ignore public void validateExtractingXmlAnnotatedName() throws Exception { // Assemble final JavaDocExtractor unitUnderTest = new JavaDocExtractor(log); // Act final SearchableDocumentation result = getSearchableDocumentationFor(unitUnderTest, 2, javaDocAnnotatedDir); // Assert final String prefix = "testdata.schemageneration.javadoc.annotated."; final String fieldAccessPrefix = prefix + "AnnotatedXmlNameAnnotatedClassWithFieldAccessTypeName#"; final String methodAccessPrefix = prefix + "AnnotatedXmlNameAnnotatedClassWithMethodAccessTypeName#"; // First, check the field-annotated class. final SortableLocation stringFieldLocation = result.getLocation(fieldAccessPrefix + "annotatedStringField"); final SortableLocation integerFieldLocation = result.getLocation(fieldAccessPrefix + "annotatedIntegerField"); final SortableLocation stringMethodLocation = result.getLocation(fieldAccessPrefix + "getStringField()"); final SortableLocation integerMethodLocation = result.getLocation(fieldAccessPrefix + "getIntegerField()"); Assert.assertTrue(stringFieldLocation instanceof FieldLocation); Assert.assertTrue(integerFieldLocation instanceof FieldLocation);
Assert.assertTrue(stringMethodLocation instanceof MethodLocation);
2
EpicEricEE/ShopChest
src/main/java/de/epiceric/shopchest/config/Config.java
[ "public class ShopChest extends JavaPlugin {\n\n private static ShopChest instance;\n\n private Config config;\n private HologramFormat hologramFormat;\n private ShopCommand shopCommand;\n private Economy econ = null;\n private Database database;\n private boolean isUpdateNeeded = false;\n private String latestVersion = \"\";\n private String downloadLink = \"\";\n private ShopUtils shopUtils;\n private FileWriter fw;\n private Plugin worldGuard;\n private Towny towny;\n private AuthMe authMe;\n private uSkyBlockAPI uSkyBlock;\n private ASkyBlock aSkyBlock;\n private IslandWorld islandWorld;\n private GriefPrevention griefPrevention;\n private AreaShop areaShop;\n private BentoBox bentoBox;\n private ShopUpdater updater;\n private ExecutorService shopCreationThreadPool;\n\n /**\n * @return An instance of ShopChest\n */\n public static ShopChest getInstance() {\n return instance;\n }\n\n /**\n * Sets up the economy of Vault\n * @return Whether an economy plugin has been registered\n */\n private boolean setupEconomy() {\n RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class);\n if (rsp == null) {\n return false;\n }\n econ = rsp.getProvider();\n return econ != null;\n }\n\n @Override\n public void onLoad() {\n instance = this;\n\n config = new Config(this);\n\n if (Config.enableDebugLog) {\n File debugLogFile = new File(getDataFolder(), \"debug.txt\");\n\n try {\n if (!debugLogFile.exists()) {\n debugLogFile.createNewFile();\n }\n\n new PrintWriter(debugLogFile).close();\n\n fw = new FileWriter(debugLogFile, true);\n } catch (IOException e) {\n getLogger().info(\"Failed to instantiate FileWriter\");\n e.printStackTrace();\n }\n }\n\n debug(\"Loading ShopChest version \" + getDescription().getVersion());\n\n worldGuard = Bukkit.getServer().getPluginManager().getPlugin(\"WorldGuard\");\n if (worldGuard != null) {\n WorldGuardShopFlag.register(this);\n }\n }\n\n @Override\n public void onEnable() {\n debug(\"Enabling ShopChest version \" + getDescription().getVersion());\n\n if (!getServer().getPluginManager().isPluginEnabled(\"Vault\")) {\n debug(\"Could not find plugin \\\"Vault\\\"\");\n getLogger().severe(\"Could not find plugin \\\"Vault\\\"\");\n getServer().getPluginManager().disablePlugin(this);\n return;\n }\n\n if (!setupEconomy()) {\n debug(\"Could not find any Vault economy dependency!\");\n getLogger().severe(\"Could not find any Vault economy dependency!\");\n getServer().getPluginManager().disablePlugin(this);\n return;\n }\n\n switch (Utils.getServerVersion()) {\n case \"v1_8_R1\":\n case \"v1_8_R2\":\n case \"v1_8_R3\":\n case \"v1_9_R1\":\n case \"v1_9_R2\":\n case \"v1_10_R1\":\n case \"v1_11_R1\":\n case \"v1_12_R1\":\n case \"v1_13_R1\":\n case \"v1_13_R2\":\n case \"v1_14_R1\":\n case \"v1_15_R1\":\n case \"v1_16_R1\":\n case \"v1_16_R2\":\n case \"v1_16_R3\":\n break;\n default:\n debug(\"Server version not officially supported: \" + Utils.getServerVersion() + \"!\");\n debug(\"Plugin may still work, but more errors are expected!\");\n getLogger().warning(\"Server version not officially supported: \" + Utils.getServerVersion() + \"!\");\n getLogger().warning(\"Plugin may still work, but more errors are expected!\");\n }\n\n shopUtils = new ShopUtils(this);\n saveResource(\"item_names.txt\", true);\n LanguageUtils.load();\n\n File hologramFormatFile = new File(getDataFolder(), \"hologram-format.yml\");\n if (!hologramFormatFile.exists()) {\n saveResource(\"hologram-format.yml\", false);\n }\n\n hologramFormat = new HologramFormat(this);\n shopCommand = new ShopCommand(this);\n shopCreationThreadPool = new ThreadPoolExecutor(0, 8,\n 5L, TimeUnit.SECONDS, new LinkedBlockingQueue<>());\n \n loadExternalPlugins();\n loadMetrics();\n initDatabase();\n checkForUpdates();\n registerListeners();\n registerExternalListeners();\n initializeShops();\n\n getServer().getMessenger().registerOutgoingPluginChannel(this, \"BungeeCord\");\n\n updater = new ShopUpdater(this);\n updater.start();\n }\n\n @Override\n public void onDisable() {\n debug(\"Disabling ShopChest...\");\n\n if (shopUtils == null) {\n // Plugin has not been fully enabled (probably due to errors),\n // so only close file writer.\n if (fw != null && Config.enableDebugLog) {\n try {\n fw.close();\n } catch (IOException e) {\n getLogger().severe(\"Failed to close FileWriter\");\n e.printStackTrace();\n }\n }\n return;\n }\n\n if (getShopCommand() != null) {\n getShopCommand().unregister();\n }\n\n ClickType.clear();\n\n if (updater != null) {\n debug(\"Stopping updater\");\n updater.stop();\n }\n\n if (shopCreationThreadPool != null) {\n shopCreationThreadPool.shutdown();\n }\n\n shopUtils.removeShops();\n debug(\"Removed shops\");\n\n if (database != null && database.isInitialized()) {\n if (database instanceof SQLite) {\n ((SQLite) database).vacuum();\n }\n\n database.disconnect();\n }\n\n if (fw != null && Config.enableDebugLog) {\n try {\n fw.close();\n } catch (IOException e) {\n getLogger().severe(\"Failed to close FileWriter\");\n e.printStackTrace();\n }\n }\n }\n\n private void loadExternalPlugins() {\n Plugin townyPlugin = Bukkit.getServer().getPluginManager().getPlugin(\"Towny\");\n if (townyPlugin instanceof Towny) {\n towny = (Towny) townyPlugin;\n }\n\n Plugin authMePlugin = Bukkit.getServer().getPluginManager().getPlugin(\"AuthMe\");\n if (authMePlugin instanceof AuthMe) {\n authMe = (AuthMe) authMePlugin;\n }\n\n Plugin uSkyBlockPlugin = Bukkit.getServer().getPluginManager().getPlugin(\"uSkyBlock\");\n if (uSkyBlockPlugin instanceof uSkyBlockAPI) {\n uSkyBlock = (uSkyBlockAPI) uSkyBlockPlugin;\n }\n\n Plugin aSkyBlockPlugin = Bukkit.getServer().getPluginManager().getPlugin(\"ASkyBlock\");\n if (aSkyBlockPlugin instanceof ASkyBlock) {\n aSkyBlock = (ASkyBlock) aSkyBlockPlugin;\n }\n\n Plugin islandWorldPlugin = Bukkit.getServer().getPluginManager().getPlugin(\"IslandWorld\");\n if (islandWorldPlugin instanceof IslandWorld) {\n islandWorld = (IslandWorld) islandWorldPlugin;\n }\n\n Plugin griefPreventionPlugin = Bukkit.getServer().getPluginManager().getPlugin(\"GriefPrevention\");\n if (griefPreventionPlugin instanceof GriefPrevention) {\n griefPrevention = (GriefPrevention) griefPreventionPlugin;\n }\n\n Plugin areaShopPlugin = Bukkit.getServer().getPluginManager().getPlugin(\"AreaShop\");\n if (areaShopPlugin instanceof AreaShop) {\n areaShop = (AreaShop) areaShopPlugin;\n }\n\n Plugin bentoBoxPlugin = getServer().getPluginManager().getPlugin(\"BentoBox\");\n if (bentoBoxPlugin instanceof BentoBox) {\n bentoBox = (BentoBox) bentoBoxPlugin;\n }\n\n if (hasWorldGuard()) {\n WorldGuardWrapper.getInstance().registerEvents(this);\n }\n\n if (hasPlotSquared()) {\n try {\n Class.forName(\"com.plotsquared.core.PlotSquared\");\n PlotSquaredShopFlag.register(this);\n } catch (ClassNotFoundException ex) {\n PlotSquaredOldShopFlag.register(this);\n }\n }\n\n if (hasBentoBox()) {\n BentoBoxShopFlag.register(this);\n }\n }\n\n private void loadMetrics() {\n debug(\"Initializing Metrics...\");\n\n Metrics metrics = new Metrics(this, 1726);\n metrics.addCustomChart(new SimplePie(\"creative_setting\", () -> Config.creativeSelectItem ? \"Enabled\" : \"Disabled\"));\n metrics.addCustomChart(new SimplePie(\"database_type\", () -> Config.databaseType.toString()));\n metrics.addCustomChart(new AdvancedPie(\"shop_type\", () -> {\n int normal = 0;\n int admin = 0;\n\n for (Shop shop : shopUtils.getShops()) {\n if (shop.getShopType() == ShopType.NORMAL) normal++;\n else if (shop.getShopType() == ShopType.ADMIN) admin++;\n }\n\n Map<String, Integer> result = new HashMap<>();\n\n result.put(\"Admin\", admin);\n result.put(\"Normal\", normal);\n\n return result;\n }));\n }\n\n private void initDatabase() {\n if (Config.databaseType == Database.DatabaseType.SQLite) {\n debug(\"Using database type: SQLite\");\n getLogger().info(\"Using SQLite\");\n database = new SQLite(this);\n } else {\n debug(\"Using database type: MySQL\");\n getLogger().info(\"Using MySQL\");\n database = new MySQL(this);\n if (Config.databaseMySqlPingInterval > 0) {\n Bukkit.getScheduler().runTaskTimer(this, new Runnable() {\n @Override\n public void run() {\n if (database instanceof MySQL) {\n ((MySQL) database).ping();\n }\n }\n }, Config.databaseMySqlPingInterval * 20L, Config.databaseMySqlPingInterval * 20L);\n }\n }\n }\n\n private void checkForUpdates() {\n if (!Config.enableUpdateChecker) {\n return;\n }\n \n new BukkitRunnable() {\n @Override\n public void run() {\n UpdateChecker uc = new UpdateChecker(ShopChest.this);\n UpdateCheckerResult result = uc.check();\n\n switch (result) {\n case TRUE:\n latestVersion = uc.getVersion();\n downloadLink = uc.getLink();\n isUpdateNeeded = true;\n\n getLogger().warning(String.format(\"Version %s is available! You are running version %s.\",\n latestVersion, getDescription().getVersion()));\n\n for (Player p : getServer().getOnlinePlayers()) {\n if (p.hasPermission(Permissions.UPDATE_NOTIFICATION)) {\n Utils.sendUpdateMessage(ShopChest.this, p);\n }\n }\n break;\n \n case FALSE:\n latestVersion = \"\";\n downloadLink = \"\";\n isUpdateNeeded = false;\n break;\n\n case ERROR:\n latestVersion = \"\";\n downloadLink = \"\";\n isUpdateNeeded = false;\n getLogger().severe(\"An error occurred while checking for updates.\");\n break;\n }\n }\n }.runTaskAsynchronously(this);\n }\n\n private void registerListeners() {\n debug(\"Registering listeners...\");\n getServer().getPluginManager().registerEvents(new ShopUpdateListener(this), this);\n getServer().getPluginManager().registerEvents(new ShopItemListener(this), this);\n getServer().getPluginManager().registerEvents(new ShopInteractListener(this), this);\n getServer().getPluginManager().registerEvents(new NotifyPlayerOnJoinListener(this), this);\n getServer().getPluginManager().registerEvents(new ChestProtectListener(this), this);\n getServer().getPluginManager().registerEvents(new CreativeModeListener(this), this);\n\n if (!Utils.getServerVersion().equals(\"v1_8_R1\")) {\n getServer().getPluginManager().registerEvents(new BlockExplodeListener(this), this);\n }\n\n if (hasWorldGuard()) {\n getServer().getPluginManager().registerEvents(new WorldGuardListener(this), this);\n\n if (hasAreaShop()) {\n getServer().getPluginManager().registerEvents(new AreaShopListener(this), this);\n }\n }\n\n if (hasBentoBox()) {\n getServer().getPluginManager().registerEvents(new BentoBoxListener(this), this);\n }\n }\n\n private void registerExternalListeners() {\n if (hasASkyBlock())\n getServer().getPluginManager().registerEvents(new ASkyBlockListener(this), this);\n if (hasGriefPrevention())\n getServer().getPluginManager().registerEvents(new GriefPreventionListener(this), this);\n if (hasIslandWorld())\n getServer().getPluginManager().registerEvents(new IslandWorldListener(this), this);\n if (hasPlotSquared())\n getServer().getPluginManager().registerEvents(new PlotSquaredListener(this), this);\n if (hasTowny())\n getServer().getPluginManager().registerEvents(new TownyListener(this), this);\n if (hasUSkyBlock())\n getServer().getPluginManager().registerEvents(new USkyBlockListener(this), this);\n if (hasWorldGuard())\n getServer().getPluginManager().registerEvents(new de.epiceric.shopchest.external.listeners.WorldGuardListener(this), this);\n if (hasBentoBox())\n getServer().getPluginManager().registerEvents(new de.epiceric.shopchest.external.listeners.BentoBoxListener(this), this);\n }\n\n /**\n * Initializes the shops\n */\n private void initializeShops() {\n getShopDatabase().connect(new Callback<Integer>(this) {\n @Override\n public void onResult(Integer result) {\n Chunk[] loadedChunks = getServer().getWorlds().stream().map(World::getLoadedChunks)\n .flatMap(Stream::of).toArray(Chunk[]::new);\n\n shopUtils.loadShopAmounts(new Callback<Map<UUID,Integer>>(ShopChest.this) {\n @Override\n public void onResult(Map<UUID, Integer> result) {\n getLogger().info(\"Loaded shop amounts\");\n debug(\"Loaded shop amounts\");\n }\n \n @Override\n public void onError(Throwable throwable) {\n getLogger().severe(\"Failed to load shop amounts. Shop limits will not be working correctly!\");\n if (throwable != null) getLogger().severe(throwable.getMessage());\n }\n });\n\n shopUtils.loadShops(loadedChunks, new Callback<Integer>(ShopChest.this) {\n @Override\n public void onResult(Integer result) {\n getServer().getPluginManager().callEvent(new ShopInitializedEvent(result));\n getLogger().info(\"Loaded \" + result + \" shops in already loaded chunks\");\n debug(\"Loaded \" + result + \" shops in already loaded chunks\");\n }\n\n @Override\n public void onError(Throwable throwable) {\n getLogger().severe(\"Failed to load shops in already loaded chunks\");\n if (throwable != null) getLogger().severe(throwable.getMessage());\n }\n });\n }\n\n @Override\n public void onError(Throwable throwable) {\n // Database connection probably failed => disable plugin to prevent more errors\n getLogger().severe(\"No database access. Disabling ShopChest\");\n if (throwable != null) getLogger().severe(throwable.getMessage());\n getServer().getPluginManager().disablePlugin(ShopChest.this);\n }\n });\n }\n\n /**\n * Print a message to the <i>/plugins/ShopChest/debug.txt</i> file\n * @param message Message to print\n */\n public void debug(String message) {\n if (Config.enableDebugLog && fw != null) {\n try {\n Calendar c = Calendar.getInstance();\n String timestamp = new SimpleDateFormat(\"dd/MM/yyyy HH:mm:ss\").format(c.getTime());\n fw.write(String.format(\"[%s] %s\\r\\n\", timestamp, message));\n fw.flush();\n } catch (IOException e) {\n getLogger().severe(\"Failed to print debug message.\");\n e.printStackTrace();\n }\n }\n }\n\n /**\n * Print a {@link Throwable}'s stacktrace to the <i>/plugins/ShopChest/debug.txt</i> file\n * @param throwable {@link Throwable} whose stacktrace will be printed\n */\n public void debug(Throwable throwable) {\n if (Config.enableDebugLog && fw != null) {\n PrintWriter pw = new PrintWriter(fw);\n throwable.printStackTrace(pw);\n pw.flush();\n }\n }\n\n /**\n * @return A thread pool for executing shop creation tasks\n */\n public ExecutorService getShopCreationThreadPool() {\n return shopCreationThreadPool;\n }\n\n public HologramFormat getHologramFormat() {\n return hologramFormat;\n }\n\n public ShopCommand getShopCommand() {\n return shopCommand;\n }\n\n /**\n * @return The {@link ShopUpdater} that schedules hologram and item updates\n */\n public ShopUpdater getUpdater() {\n return updater;\n }\n\n /**\n * @return Whether the plugin 'AreaShop' is enabled\n */\n public boolean hasAreaShop() {\n return Config.enableAreaShopIntegration && areaShop != null && areaShop.isEnabled();\n }\n\n /**\n * @return Whether the plugin 'GriefPrevention' is enabled\n */\n public boolean hasGriefPrevention() {\n return Config.enableGriefPreventionIntegration && griefPrevention != null && griefPrevention.isEnabled();\n }\n\n /**\n * @return An instance of {@link GriefPrevention} or {@code null} if GriefPrevention is not enabled\n */\n public GriefPrevention getGriefPrevention() {\n return griefPrevention;\n }\n\n /**\n * @return Whether the plugin 'IslandWorld' is enabled\n */\n public boolean hasIslandWorld() {\n return Config.enableIslandWorldIntegration && islandWorld != null && islandWorld.isEnabled();\n }\n /**\n * @return Whether the plugin 'ASkyBlock' is enabled\n */\n public boolean hasASkyBlock() {\n return Config.enableASkyblockIntegration && aSkyBlock != null && aSkyBlock.isEnabled();\n }\n\n /**\n * @return Whether the plugin 'uSkyBlock' is enabled\n */\n public boolean hasUSkyBlock() {\n return Config.enableUSkyblockIntegration && uSkyBlock != null && uSkyBlock.isEnabled();\n }\n\n /**\n * @return An instance of {@link uSkyBlockAPI} or {@code null} if uSkyBlock is not enabled\n */\n public uSkyBlockAPI getUSkyBlock() {\n return uSkyBlock;\n }\n\n /**\n * @return Whether the plugin 'PlotSquared' is enabled\n */\n public boolean hasPlotSquared() {\n if (!Config.enablePlotsquaredIntegration) {\n return false;\n }\n\n if (Utils.getMajorVersion() < 13) {\n // Supported PlotSquared versions don't support versions below 1.13\n return false;\n }\n Plugin p = getServer().getPluginManager().getPlugin(\"PlotSquared\");\n return p != null && p.isEnabled();\n }\n\n /**\n * @return Whether the plugin 'AuthMe' is enabled\n */\n public boolean hasAuthMe() {\n return Config.enableAuthMeIntegration && authMe != null && authMe.isEnabled();\n }\n /**\n * @return Whether the plugin 'Towny' is enabled\n */\n public boolean hasTowny() {\n return Config.enableTownyIntegration && towny != null && towny.isEnabled();\n }\n\n /**\n * @return Whether the plugin 'WorldGuard' is enabled\n */\n public boolean hasWorldGuard() {\n return Config.enableWorldGuardIntegration && worldGuard != null && worldGuard.isEnabled();\n }\n\n /**\n * @return Whether the plugin 'WorldGuard' is enabled\n */\n public boolean hasBentoBox() {\n return Config.enableBentoBoxIntegration && bentoBox != null && bentoBox.isEnabled();\n }\n\n /**\n * @return ShopChest's {@link ShopUtils} containing some important methods\n */\n public ShopUtils getShopUtils() {\n return shopUtils;\n }\n\n /**\n * @return Registered Economy of Vault\n */\n public Economy getEconomy() {\n return econ;\n }\n\n /**\n * @return ShopChest's shop database\n */\n public Database getShopDatabase() {\n return database;\n }\n\n /**\n * @return Whether an update is needed (will return false if not checked)\n */\n public boolean isUpdateNeeded() {\n return isUpdateNeeded;\n }\n\n /**\n * Set whether an update is needed\n * @param isUpdateNeeded Whether an update should be needed\n */\n public void setUpdateNeeded(boolean isUpdateNeeded) {\n this.isUpdateNeeded = isUpdateNeeded;\n }\n\n /**\n * @return The latest version of ShopChest (will return null if not checked or if no update is available)\n */\n public String getLatestVersion() {\n return latestVersion;\n }\n\n /**\n * Set the latest version\n * @param latestVersion Version to set as latest version\n */\n public void setLatestVersion(String latestVersion) {\n this.latestVersion = latestVersion;\n }\n\n /**\n * @return The download link of the latest version (will return null if not checked or if no update is available)\n */\n public String getDownloadLink() {\n return downloadLink;\n }\n\n /**\n * Set the download Link of the latest version (will return null if not checked or if no update is available)\n * @param downloadLink Link to set as Download Link\n */\n public void setDownloadLink(String downloadLink) {\n this.downloadLink = downloadLink;\n }\n\n /**\n * @return The {@link Config} of ShopChest\n */\n public Config getShopChestConfig() {\n return config;\n }\n}", "public class LanguageUtils {\n\n private static ShopChest plugin = ShopChest.getInstance();\n private static LanguageConfiguration langConfig;\n\n private static ArrayList<ItemName> itemNames = new ArrayList<>();\n private static ArrayList<EnchantmentName> enchantmentNames = new ArrayList<>();\n private static ArrayList<EnchantmentName.EnchantmentLevelName> enchantmentLevelNames = new ArrayList<>();\n private static ArrayList<PotionEffectName> potionEffectNames = new ArrayList<>();\n private static ArrayList<EntityName> entityNames = new ArrayList<>();\n private static ArrayList<PotionName> potionNames = new ArrayList<>();\n private static ArrayList<MusicDiscName> musicDiscNames = new ArrayList<>();\n private static ArrayList<BannerPatternName> bannerPatternNames = new ArrayList<>();\n private static ArrayList<BookGenerationName> generationNames = new ArrayList<>();\n private static ArrayList<LocalizedMessage> messages = new ArrayList<>();\n\n\n private static void loadLegacy() {\n // Add Block Names\n itemNames.add(new ItemName(Material.valueOf(\"STONE\"), langConfig.getString(\"tile.stone.stone.name\", \"Stone\")));\n itemNames.add(new ItemName(Material.valueOf(\"STONE\"), 1, langConfig.getString(\"tile.stone.granite.name\", \"Granite\")));\n itemNames.add(new ItemName(Material.valueOf(\"STONE\"), 2, langConfig.getString(\"tile.stone.graniteSmooth.name\", \"Polished Granite\")));\n itemNames.add(new ItemName(Material.valueOf(\"STONE\"), 3, langConfig.getString(\"tile.stone.diorite.name\", \"Diorite\")));\n itemNames.add(new ItemName(Material.valueOf(\"STONE\"), 4, langConfig.getString(\"tile.stone.dioriteSmooth.name\", \"Polished Diorite\")));\n itemNames.add(new ItemName(Material.valueOf(\"STONE\"), 5, langConfig.getString(\"tile.stone.andesite.name\", \"Andesite\")));\n itemNames.add(new ItemName(Material.valueOf(\"STONE\"), 6, langConfig.getString(\"tile.stone.andesiteSmooth.name\", \"Polished Andesite\")));\n itemNames.add(new ItemName(Material.valueOf(\"GRASS\"), langConfig.getString(\"tile.grass.name\", \"Grass Block\")));\n itemNames.add(new ItemName(Material.valueOf(\"DIRT\"), langConfig.getString(\"tile.dirt.default.name\", \"Dirt\")));\n itemNames.add(new ItemName(Material.valueOf(\"DIRT\"), 1, langConfig.getString(\"tile.dirt.coarse.name\", \"Coarse Dirt\")));\n itemNames.add(new ItemName(Material.valueOf(\"DIRT\"), 2, langConfig.getString(\"tile.dirt.podzol.name\", \"Podzol\")));\n itemNames.add(new ItemName(Material.valueOf(\"COBBLESTONE\"), langConfig.getString(\"tile.stonebrick.name\", \"Cobblestone\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOD\"), langConfig.getString(\"tile.wood.oak.name\", \"Oak Wood Planks\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOD\"), 1, langConfig.getString(\"tile.wood.spruce.name\", \"Spruce Wood Planks\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOD\"), 2, langConfig.getString(\"tile.wood.birch.name\", \"Birch Wood Planks\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOD\"), 3, langConfig.getString(\"tile.wood.jungle.name\", \"Jungle Wood Planks\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOD\"), 4, langConfig.getString(\"tile.wood.acacia.name\", \"Acacia Wood Planks\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOD\"), 5, langConfig.getString(\"tile.wood.big_oak.name\", \"Dark Oak Wood Planks\")));\n itemNames.add(new ItemName(Material.valueOf(\"SAPLING\"), langConfig.getString(\"tile.sapling.oak.name\", \"Oak Sapling\")));\n itemNames.add(new ItemName(Material.valueOf(\"SAPLING\"), 1, langConfig.getString(\"tile.sapling.spruce.name\", \"Spruce Sapling\")));\n itemNames.add(new ItemName(Material.valueOf(\"SAPLING\"), 2, langConfig.getString(\"tile.sapling.birch.name\", \"Birch Sapling\")));\n itemNames.add(new ItemName(Material.valueOf(\"SAPLING\"), 3, langConfig.getString(\"tile.sapling.jungle.name\", \"Jungle Sapling\")));\n itemNames.add(new ItemName(Material.valueOf(\"SAPLING\"), 4, langConfig.getString(\"tile.sapling.acacia.name\", \"Acacia Sapling\")));\n itemNames.add(new ItemName(Material.valueOf(\"SAPLING\"), 5, langConfig.getString(\"tile.sapling.big_oak.name\", \"Dark Oak Sapling\")));\n itemNames.add(new ItemName(Material.valueOf(\"BEDROCK\"), langConfig.getString(\"tile.bedrock.name\", \"Bedrock\")));\n itemNames.add(new ItemName(Material.valueOf(\"WATER\"), langConfig.getString(\"tile.water.name\", \"Water\")));\n itemNames.add(new ItemName(Material.valueOf(\"LAVA\"), langConfig.getString(\"tile.lava.name\", \"Lava\")));\n itemNames.add(new ItemName(Material.valueOf(\"SAND\"), langConfig.getString(\"tile.sand.default.name\", \"Sand\")));\n itemNames.add(new ItemName(Material.valueOf(\"SAND\"), 1, langConfig.getString(\"tile.sand.red.name\", \"Red Sand\")));\n itemNames.add(new ItemName(Material.valueOf(\"GRAVEL\"), langConfig.getString(\"tile.gravel.name\", \"Gravel\")));\n itemNames.add(new ItemName(Material.valueOf(\"GOLD_ORE\"), langConfig.getString(\"tile.oreGold.name\", \"Gold Ore\")));\n itemNames.add(new ItemName(Material.valueOf(\"IRON_ORE\"), langConfig.getString(\"tile.oreIron.name\", \"Iron Ore\")));\n itemNames.add(new ItemName(Material.valueOf(\"COAL_ORE\"), langConfig.getString(\"tile.oreCoal.name\", \"Coal Ore\")));\n itemNames.add(new ItemName(Material.valueOf(\"LOG\"), langConfig.getString(\"tile.log.oak.name\", \"Oak Wood\")));\n itemNames.add(new ItemName(Material.valueOf(\"LOG\"), 1, langConfig.getString(\"tile.log.spruce.name\", \"Spruce Wood\")));\n itemNames.add(new ItemName(Material.valueOf(\"LOG\"), 2, langConfig.getString(\"tile.log.birch.name\", \"Birch Wood\")));\n itemNames.add(new ItemName(Material.valueOf(\"LOG\"), 3, langConfig.getString(\"tile.log.jungle.name\", \"Jungle Wood\")));\n itemNames.add(new ItemName(Material.valueOf(\"LEAVES\"), langConfig.getString(\"tile.leaves.oak.name\", \"Oak Leaves\")));\n itemNames.add(new ItemName(Material.valueOf(\"LEAVES\"), 1, langConfig.getString(\"tile.leaves.spruce.name\", \"Spruce Leaves\")));\n itemNames.add(new ItemName(Material.valueOf(\"LEAVES\"), 2, langConfig.getString(\"tile.leaves.birch.name\", \"Birch Leaves\")));\n itemNames.add(new ItemName(Material.valueOf(\"LEAVES\"), 3, langConfig.getString(\"tile.leaves.jungle.name\", \"Jungle Leaves\")));\n itemNames.add(new ItemName(Material.valueOf(\"SPONGE\"), langConfig.getString(\"tile.sponge.dry.name\", \"Sponge\")));\n itemNames.add(new ItemName(Material.valueOf(\"SPONGE\"), 1, langConfig.getString(\"tile.sponge.wet.name\", \"Wet Sponge\")));\n itemNames.add(new ItemName(Material.valueOf(\"GLASS\"), langConfig.getString(\"tile.glass.name\", \"Glass\")));\n itemNames.add(new ItemName(Material.valueOf(\"LAPIS_ORE\"), langConfig.getString(\"tile.oreLapis.name\", \"Lapis Lazuli Ore\")));\n itemNames.add(new ItemName(Material.valueOf(\"LAPIS_BLOCK\"), langConfig.getString(\"tile.blockLapis.name\", \"Lapis Lazuli Block\")));\n itemNames.add(new ItemName(Material.valueOf(\"DISPENSER\"), langConfig.getString(\"tile.dispenser.name\", \"Dispenser\")));\n itemNames.add(new ItemName(Material.valueOf(\"SANDSTONE\"), langConfig.getString(\"tile.sandStone.default.name\", \"Sandstone\")));\n itemNames.add(new ItemName(Material.valueOf(\"SANDSTONE\"), 1, langConfig.getString(\"tile.sandStone.chiseled.name\", \"Chiseled Sandstone\")));\n itemNames.add(new ItemName(Material.valueOf(\"SANDSTONE\"), 2, langConfig.getString(\"tile.sandStone.smooth.name\", \"Smooth Sandstone\")));\n itemNames.add(new ItemName(Material.valueOf(\"NOTE_BLOCK\"), langConfig.getString(\"tile.musicBlock.name\", \"Note Block\")));\n itemNames.add(new ItemName(Material.valueOf(\"POWERED_RAIL\"), langConfig.getString(\"tile.goldenRail.name\", \"Powered Rail\")));\n itemNames.add(new ItemName(Material.valueOf(\"DETECTOR_RAIL\"), langConfig.getString(\"tile.detectorRail.name\", \"Detector Rail\")));\n itemNames.add(new ItemName(Material.valueOf(\"PISTON_STICKY_BASE\"), langConfig.getString(\"tile.pistonStickyBase.name\", \"Sticky Piston\")));\n itemNames.add(new ItemName(Material.valueOf(\"WEB\"), langConfig.getString(\"tile.web.name\", \"Web\")));\n itemNames.add(new ItemName(Material.valueOf(\"LONG_GRASS\"), langConfig.getString(\"tile.tallgrass.shrub.name\", \"Shrub\")));\n itemNames.add(new ItemName(Material.valueOf(\"LONG_GRASS\"), 1, langConfig.getString(\"tile.tallgrass.grass.name\", \"Grass\")));\n itemNames.add(new ItemName(Material.valueOf(\"LONG_GRASS\"), 2, langConfig.getString(\"tile.tallgrass.fern.name\", \"Fern\")));\n itemNames.add(new ItemName(Material.valueOf(\"DEAD_BUSH\"), langConfig.getString(\"tile.deadbush.name\", \"Dead Bush\")));\n itemNames.add(new ItemName(Material.valueOf(\"PISTON_BASE\"), langConfig.getString(\"tile.pistonBase.name\", \"Piston\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOL\"), langConfig.getString(\"tile.cloth.white.name\", \"White Wool\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOL\"), 1, langConfig.getString(\"tile.cloth.orange.name\", \"Orange Wool\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOL\"), 2, langConfig.getString(\"tile.cloth.magenta.name\", \"Magenta Wool\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOL\"), 3, langConfig.getString(\"tile.cloth.lightBlue.name\", \"Light Blue Wool\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOL\"), 4, langConfig.getString(\"tile.cloth.yellow.name\", \"Yellow Wool\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOL\"), 5, langConfig.getString(\"tile.cloth.lime.name\", \"Lime Wool\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOL\"), 6, langConfig.getString(\"tile.cloth.pink.name\", \"Pink Wool\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOL\"), 7, langConfig.getString(\"tile.cloth.gray.name\", \"Gray Wool\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOL\"), 8, langConfig.getString(\"tile.cloth.silver.name\", \"Light Gray Wool\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOL\"), 9, langConfig.getString(\"tile.cloth.cyan.name\", \"Cyan Wool\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOL\"), 10, langConfig.getString(\"tile.cloth.purple.name\", \"Purple Wool\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOL\"), 11, langConfig.getString(\"tile.cloth.blue.name\", \"Blue Wool\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOL\"), 12, langConfig.getString(\"tile.cloth.brown.name\", \"Brown Wool\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOL\"), 13, langConfig.getString(\"tile.cloth.green.name\", \"Green Wool\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOL\"), 14, langConfig.getString(\"tile.cloth.red.name\", \"Red Wool\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOL\"), 15, langConfig.getString(\"tile.cloth.black.name\", \"Black Wool\")));\n itemNames.add(new ItemName(Material.valueOf(\"YELLOW_FLOWER\"), langConfig.getString(\"tile.flower1.dandelion.name\", \"Dandelion\")));\n itemNames.add(new ItemName(Material.valueOf(\"RED_ROSE\"), langConfig.getString(\"tile.flower2.poppy.name\", \"Poppy\")));\n itemNames.add(new ItemName(Material.valueOf(\"RED_ROSE\"), 1, langConfig.getString(\"tile.flower2.blueOrchid.name\", \"Blue Orchid\")));\n itemNames.add(new ItemName(Material.valueOf(\"RED_ROSE\"), 2, langConfig.getString(\"tile.flower2.allium.name\", \"Allium\")));\n itemNames.add(new ItemName(Material.valueOf(\"RED_ROSE\"), 3, langConfig.getString(\"tile.flower2.houstonia.name\", \"Azure Bluet\")));\n itemNames.add(new ItemName(Material.valueOf(\"RED_ROSE\"), 4, langConfig.getString(\"tile.flower2.tulipRed.name\", \"Red Tulip\")));\n itemNames.add(new ItemName(Material.valueOf(\"RED_ROSE\"), 5, langConfig.getString(\"tile.flower2.tulipOrange.name\", \"Orange Tulip\")));\n itemNames.add(new ItemName(Material.valueOf(\"RED_ROSE\"), 6, langConfig.getString(\"tile.flower2.tulipWhite.name\", \"White Tulip\")));\n itemNames.add(new ItemName(Material.valueOf(\"RED_ROSE\"), 7, langConfig.getString(\"tile.flower2.tulipPink.name\", \"Pink Tulip\")));\n itemNames.add(new ItemName(Material.valueOf(\"RED_ROSE\"), 8, langConfig.getString(\"tile.flower2.oxeyeDaisy.name\", \"Oxeye Daisy\")));\n itemNames.add(new ItemName(Material.valueOf(\"BROWN_MUSHROOM\"), langConfig.getString(\"tile.mushroom.name\", \"Mushroom\")));\n itemNames.add(new ItemName(Material.valueOf(\"RED_MUSHROOM\"), langConfig.getString(\"tile.mushroom.name\", \"Mushroom\")));\n itemNames.add(new ItemName(Material.valueOf(\"GOLD_BLOCK\"), langConfig.getString(\"tile.blockGold.name\", \"Block of Gold\")));\n itemNames.add(new ItemName(Material.valueOf(\"IRON_BLOCK\"), langConfig.getString(\"tile.blockIron.name\", \"Block of Iron\")));\n itemNames.add(new ItemName(Material.valueOf(\"STEP\"), langConfig.getString(\"tile.stoneSlab.stone.name\", \"Stone Slab\")));\n itemNames.add(new ItemName(Material.valueOf(\"STEP\"), 1, langConfig.getString(\"tile.stoneSlab.sand.name\", \"Sandstone Slab\")));\n itemNames.add(new ItemName(Material.valueOf(\"STEP\"), 2, langConfig.getString(\"tile.stoneSlab.wood.name\", \"Wooden Slab\")));\n itemNames.add(new ItemName(Material.valueOf(\"STEP\"), 3, langConfig.getString(\"tile.stoneSlab.cobble.name\", \"Cobblestone Slab\")));\n itemNames.add(new ItemName(Material.valueOf(\"STEP\"), 4, langConfig.getString(\"tile.stoneSlab.brick.name\", \"Brick Slab\")));\n itemNames.add(new ItemName(Material.valueOf(\"STEP\"), 5, langConfig.getString(\"tile.stoneSlab.smoothStoneBrick.name\", \"Stone Brick Slab\")));\n itemNames.add(new ItemName(Material.valueOf(\"STEP\"), 6, langConfig.getString(\"tile.stoneSlab.netherBrick.name\", \"Nether Brick Slab\")));\n itemNames.add(new ItemName(Material.valueOf(\"STEP\"), 7, langConfig.getString(\"tile.stoneSlab.quartz.name\", \"Quartz Slab\")));\n itemNames.add(new ItemName(Material.valueOf(\"BRICK\"), langConfig.getString(\"tile.brick.name\", \"Brick\")));\n itemNames.add(new ItemName(Material.valueOf(\"TNT\"), langConfig.getString(\"tile.tnt.name\", \"TNT\")));\n itemNames.add(new ItemName(Material.valueOf(\"BOOKSHELF\"), langConfig.getString(\"tile.bookshelf.name\", \"Bookshelf\")));\n itemNames.add(new ItemName(Material.valueOf(\"MOSSY_COBBLESTONE\"), langConfig.getString(\"tile.stoneMoss.name\", \"Moss Stone\")));\n itemNames.add(new ItemName(Material.valueOf(\"OBSIDIAN\"), langConfig.getString(\"tile.obsidian.name\", \"Obsidian\")));\n itemNames.add(new ItemName(Material.valueOf(\"TORCH\"), langConfig.getString(\"tile.torch.name\", \"Torch\")));\n itemNames.add(new ItemName(Material.valueOf(\"FIRE\"), langConfig.getString(\"tile.fire.name\", \"Fire\")));\n itemNames.add(new ItemName(Material.valueOf(\"MOB_SPAWNER\"), langConfig.getString(\"tile.mobSpawner.name\", \"Mob Spawner\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOD_STAIRS\"), langConfig.getString(\"tile.stairsWood.name\", \"Oak Wood Stairs\")));\n itemNames.add(new ItemName(Material.valueOf(\"CHEST\"), langConfig.getString(\"tile.chest.name\", \"Chest\")));\n itemNames.add(new ItemName(Material.valueOf(\"DIAMOND_ORE\"), langConfig.getString(\"tile.oreDiamond.name\", \"Diamond Ore\")));\n itemNames.add(new ItemName(Material.valueOf(\"DIAMOND_BLOCK\"), langConfig.getString(\"tile.blockDiamond.name\", \"Block of Diamond\")));\n itemNames.add(new ItemName(Material.valueOf(\"WORKBENCH\"), langConfig.getString(\"tile.workbench.name\", \"Crafting Table\")));\n itemNames.add(new ItemName(Material.valueOf(\"SOIL\"), langConfig.getString(\"tile.farmland.name\", \"Farmland\")));\n itemNames.add(new ItemName(Material.valueOf(\"FURNACE\"), langConfig.getString(\"tile.furnace.name\", \"Furnace\")));\n itemNames.add(new ItemName(Material.valueOf(\"LADDER\"), langConfig.getString(\"tile.ladder.name\", \"Ladder\")));\n itemNames.add(new ItemName(Material.valueOf(\"RAILS\"), langConfig.getString(\"tile.rail.name\", \"Rail\")));\n itemNames.add(new ItemName(Material.valueOf(\"COBBLESTONE_STAIRS\"), langConfig.getString(\"tile.stairsStone.name\", \"Stone Stairs\")));\n itemNames.add(new ItemName(Material.valueOf(\"LEVER\"), langConfig.getString(\"tile.lever.name\", \"Lever\")));\n itemNames.add(new ItemName(Material.valueOf(\"STONE_PLATE\"), langConfig.getString(\"tile.pressurePlateStone.name\", \"Stone Pressure Plate\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOD_PLATE\"), langConfig.getString(\"tile.pressurePlateWood.name\", \"Wooden Pressure Plate\")));\n itemNames.add(new ItemName(Material.valueOf(\"REDSTONE_ORE\"), langConfig.getString(\"tile.oreRedstone.name\", \"Redstone Ore\")));\n itemNames.add(new ItemName(Material.valueOf(\"REDSTONE_TORCH_ON\"), langConfig.getString(\"tile.notGate.name\", \"Redstone Torch\")));\n itemNames.add(new ItemName(Material.valueOf(\"SNOW\"), langConfig.getString(\"tile.snow.name\", \"Snow\")));\n itemNames.add(new ItemName(Material.valueOf(\"ICE\"), langConfig.getString(\"tile.ice.name\", \"Ice\")));\n itemNames.add(new ItemName(Material.valueOf(\"SNOW_BLOCK\"), langConfig.getString(\"tile.snow.name\", \"Snow\")));\n itemNames.add(new ItemName(Material.valueOf(\"CACTUS\"), langConfig.getString(\"tile.cactus.name\", \"Cactus\")));\n itemNames.add(new ItemName(Material.valueOf(\"CLAY\"), langConfig.getString(\"tile.clay.name\", \"Clay\")));\n itemNames.add(new ItemName(Material.valueOf(\"JUKEBOX\"), langConfig.getString(\"tile.jukebox.name\", \"Jukebox\")));\n itemNames.add(new ItemName(Material.valueOf(\"FENCE\"), langConfig.getString(\"tile.fence.name\", \"Oak Fence\")));\n itemNames.add(new ItemName(Material.valueOf(\"PUMPKIN\"), langConfig.getString(\"tile.pumpkin.name\", \"Pumpkin\")));\n itemNames.add(new ItemName(Material.valueOf(\"NETHERRACK\"), langConfig.getString(\"tile.hellrock.name\", \"Netherrack\")));\n itemNames.add(new ItemName(Material.valueOf(\"SOUL_SAND\"), langConfig.getString(\"tile.hellsand.name\", \"Soul Sand\")));\n itemNames.add(new ItemName(Material.valueOf(\"GLOWSTONE\"), langConfig.getString(\"tile.lightgem.name\", \"Glowstone\")));\n itemNames.add(new ItemName(Material.valueOf(\"PORTAL\"), langConfig.getString(\"tile.portal.name\", \"Portal\")));\n itemNames.add(new ItemName(Material.valueOf(\"JACK_O_LANTERN\"), langConfig.getString(\"tile.litpumpkin.name\", \"Jack o'Lantern\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS\"), langConfig.getString(\"tile.stainedGlass.white.name\", \"White Stained Glass\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS\"), 1, langConfig.getString(\"tile.stainedGlass.orange.name\", \"Orange Stained Glass\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS\"), 2, langConfig.getString(\"tile.stainedGlass.magenta.name\", \"Magenta Stained Glass\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS\"), 3, langConfig.getString(\"tile.stainedGlass.lightBlue.name\", \"Light Blue Stained Glass\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS\"), 4, langConfig.getString(\"tile.stainedGlass.yellow.name\", \"Yellow Stained Glass\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS\"), 5, langConfig.getString(\"tile.stainedGlass.lime.name\", \"Lime Stained Glass\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS\"), 6, langConfig.getString(\"tile.stainedGlass.pink.name\", \"Pink Stained Glass\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS\"), 7, langConfig.getString(\"tile.stainedGlass.gray.name\", \"Gray Stained Glass\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS\"), 8, langConfig.getString(\"tile.stainedGlass.silver.name\", \"Light Gray Stained Glass\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS\"), 9, langConfig.getString(\"tile.stainedGlass.cyan.name\", \"Cyan Stained Glass\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS\"), 10, langConfig.getString(\"tile.stainedGlass.purple.name\", \"Purple Stained Glass\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS\"), 11, langConfig.getString(\"tile.stainedGlass.blue.name\", \"Blue Stained Glass\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS\"), 12, langConfig.getString(\"tile.stainedGlass.brown.name\", \"Brown Stained Glass\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS\"), 13, langConfig.getString(\"tile.stainedGlass.green.name\", \"Green Stained Glass\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS\"), 14, langConfig.getString(\"tile.stainedGlass.red.name\", \"Red Stained Glass\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS\"), 15, langConfig.getString(\"tile.stainedGlass.black.name\", \"Black Stained Glass\")));\n itemNames.add(new ItemName(Material.valueOf(\"TRAP_DOOR\"), langConfig.getString(\"tile.trapdoor.name\", \"Wooden Trapdoor\")));\n itemNames.add(new ItemName(Material.valueOf(\"MONSTER_EGGS\"), langConfig.getString(\"tile.monsterStoneEgg.stone.name\", \"Stone Monster Egg\")));\n itemNames.add(new ItemName(Material.valueOf(\"MONSTER_EGGS\"), 1, langConfig.getString(\"tile.monsterStoneEgg.cobble.name\", \"Cobblestone Monster Egg\")));\n itemNames.add(new ItemName(Material.valueOf(\"MONSTER_EGGS\"), 2, langConfig.getString(\"tile.monsterStoneEgg.brick.name\", \"Stone Brick Monster Egg\")));\n itemNames.add(new ItemName(Material.valueOf(\"MONSTER_EGGS\"), 3, langConfig.getString(\"tile.monsterStoneEgg.mossybrick.name\", \"Mossy Stone Brick Monster Egg\")));\n itemNames.add(new ItemName(Material.valueOf(\"MONSTER_EGGS\"), 4, langConfig.getString(\"tile.monsterStoneEgg.crackedbrick.name\", \"Cracked Stone Brick Monster Egg\")));\n itemNames.add(new ItemName(Material.valueOf(\"MONSTER_EGGS\"), 5, langConfig.getString(\"tile.monsterStoneEgg.chiseledbrick.name\", \"Chiseled Stone Brick Monster Egg\")));\n itemNames.add(new ItemName(Material.valueOf(\"SMOOTH_BRICK\"), langConfig.getString(\"tile.stonebricksmooth.default.name\", \"Stone Bricks\")));\n itemNames.add(new ItemName(Material.valueOf(\"SMOOTH_BRICK\"), 1, langConfig.getString(\"tile.stonebricksmooth.mossy.name\", \"Mossy Stone Bricks\")));\n itemNames.add(new ItemName(Material.valueOf(\"SMOOTH_BRICK\"), 2, langConfig.getString(\"tile.stonebricksmooth.cracked.name\", \"Cracked Stone Bricks\")));\n itemNames.add(new ItemName(Material.valueOf(\"SMOOTH_BRICK\"), 3, langConfig.getString(\"tile.stonebricksmooth.chiseled.name\", \"Chiseled Stone Bricks\")));\n itemNames.add(new ItemName(Material.valueOf(\"HUGE_MUSHROOM_1\"), langConfig.getString(\"tile.mushroom.name\", \"Mushroom\")));\n itemNames.add(new ItemName(Material.valueOf(\"HUGE_MUSHROOM_2\"), langConfig.getString(\"tile.mushroom.name\", \"Mushroom\")));\n itemNames.add(new ItemName(Material.valueOf(\"IRON_FENCE\"), langConfig.getString(\"tile.fenceIron.name\", \"Iron Bars\")));\n itemNames.add(new ItemName(Material.valueOf(\"THIN_GLASS\"), langConfig.getString(\"tile.thinGlass.name\", \"Glass Pane\")));\n itemNames.add(new ItemName(Material.valueOf(\"MELON_BLOCK\"), langConfig.getString(\"tile.melon.name\", \"Melon\")));\n itemNames.add(new ItemName(Material.valueOf(\"VINE\"), langConfig.getString(\"tile.vine.name\", \"Vines\")));\n itemNames.add(new ItemName(Material.valueOf(\"FENCE_GATE\"), langConfig.getString(\"tile.fenceGate.name\", \"Oak Fence Gate\")));\n itemNames.add(new ItemName(Material.valueOf(\"BRICK_STAIRS\"), langConfig.getString(\"tile.stairsBrick.name\", \"Brick Stairs\")));\n itemNames.add(new ItemName(Material.valueOf(\"SMOOTH_STAIRS\"), langConfig.getString(\"tile.stairsStoneBrickSmooth.name\", \"Stone Brick Stairs\")));\n itemNames.add(new ItemName(Material.valueOf(\"MYCEL\"), langConfig.getString(\"tile.mycel.name\", \"Mycelium\")));\n itemNames.add(new ItemName(Material.valueOf(\"WATER_LILY\"), langConfig.getString(\"tile.waterlily.name\", \"Lily Pad\")));\n itemNames.add(new ItemName(Material.valueOf(\"NETHER_BRICK\"), langConfig.getString(\"tile.netherBrick.name\", \"Nether Brick\")));\n itemNames.add(new ItemName(Material.valueOf(\"NETHER_FENCE\"), langConfig.getString(\"tile.netherFence.name\", \"Nether Brick Fence\")));\n itemNames.add(new ItemName(Material.valueOf(\"NETHER_BRICK_STAIRS\"), langConfig.getString(\"tile.stairsNetherBrick.name\", \"Nether Brick Stairs\")));\n itemNames.add(new ItemName(Material.valueOf(\"ENCHANTMENT_TABLE\"), langConfig.getString(\"tile.enchantmentTable.name\", \"Enchantment Table\")));\n itemNames.add(new ItemName(Material.valueOf(\"ENDER_PORTAL_FRAME\"), langConfig.getString(\"tile.endPortalFrame.name\", \"End Portal Frame\")));\n itemNames.add(new ItemName(Material.valueOf(\"ENDER_STONE\"), langConfig.getString(\"tile.whiteStone.name\", \"End Stone\")));\n itemNames.add(new ItemName(Material.valueOf(\"DRAGON_EGG\"), langConfig.getString(\"tile.dragonEgg.name\", \"Dragon Egg\")));\n itemNames.add(new ItemName(Material.valueOf(\"REDSTONE_LAMP_OFF\"), langConfig.getString(\"tile.redstoneLight.name\", \"Redstone Lamp\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOD_STEP\"), langConfig.getString(\"tile.woodSlab.oak.name\", \"Oak Wood Slab\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOD_STEP\"), 1, langConfig.getString(\"tile.woodSlab.spruce.name\", \"Spruce Wood Slab\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOD_STEP\"), 2, langConfig.getString(\"tile.woodSlab.birch.name\", \"Birch Wood Slab\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOD_STEP\"), 3, langConfig.getString(\"tile.woodSlab.jungle.name\", \"Jungle Wood Slab\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOD_STEP\"), 4, langConfig.getString(\"tile.woodSlab.acacia.name\", \"Acacia Wood Slab\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOD_STEP\"), 5, langConfig.getString(\"tile.woodSlab.big_oak.name\", \"Dark Oak Wood Slab\")));\n itemNames.add(new ItemName(Material.valueOf(\"SANDSTONE_STAIRS\"), langConfig.getString(\"tile.stairsSandStone.name\", \"Mycelium\")));\n itemNames.add(new ItemName(Material.valueOf(\"EMERALD_ORE\"), langConfig.getString(\"tile.oreEmerald.name\", \"Emerald Ore\")));\n itemNames.add(new ItemName(Material.valueOf(\"ENDER_CHEST\"), langConfig.getString(\"tile.enderChest.name\", \"Ender Chest\")));\n itemNames.add(new ItemName(Material.valueOf(\"TRIPWIRE_HOOK\"), langConfig.getString(\"tile.tripWireSource.name\", \"Tripwire Hook\")));\n itemNames.add(new ItemName(Material.valueOf(\"EMERALD_BLOCK\"), langConfig.getString(\"tile.blockEmerald.name\", \"Block of Emerald\")));\n itemNames.add(new ItemName(Material.valueOf(\"SPRUCE_WOOD_STAIRS\"), langConfig.getString(\"tile.stairsWoodSpruce.name\", \"Spruce Wood Stairs\")));\n itemNames.add(new ItemName(Material.valueOf(\"BIRCH_WOOD_STAIRS\"), langConfig.getString(\"tile.stairsWoodBirch.name\", \"Birch Wood Stairs\")));\n itemNames.add(new ItemName(Material.valueOf(\"JUNGLE_WOOD_STAIRS\"), langConfig.getString(\"tile.stairsWoodJungle.name\", \"Jungle Wood Stairs\")));\n itemNames.add(new ItemName(Material.valueOf(\"COMMAND\"), langConfig.getString(\"tile.commandBlock.name\", \"Command Block\")));\n itemNames.add(new ItemName(Material.valueOf(\"BEACON\"), langConfig.getString(\"tile.beacon.name\", \"Beacon\")));\n itemNames.add(new ItemName(Material.valueOf(\"COBBLE_WALL\"), langConfig.getString(\"tile.cobbleWall.normal.name\", \"Cobblestone Wall\")));\n itemNames.add(new ItemName(Material.valueOf(\"COBBLE_WALL\"), 1, langConfig.getString(\"tile.cobbleWall.mossy.name\", \"Mossy Cobblestone Wall\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOD_BUTTON\"), langConfig.getString(\"tile.button.name\", \"Button\")));\n itemNames.add(new ItemName(Material.valueOf(\"NETHER_STALK\"), langConfig.getString(\"tile.netherStalk.name\", \"Nether Wart\")));\n itemNames.add(new ItemName(Material.valueOf(\"ANVIL\"), langConfig.getString(\"tile.anvil.intact.name\", \"Anvil\")));\n itemNames.add(new ItemName(Material.valueOf(\"ANVIL\"), 1, langConfig.getString(\"tile.anvil.slightlyDamaged.name\", \"Slightly Damaged Anvil\")));\n itemNames.add(new ItemName(Material.valueOf(\"ANVIL\"), 2, langConfig.getString(\"tile.anvil.veryDamaged.name\", \"Very Damaged Anvil\")));\n itemNames.add(new ItemName(Material.valueOf(\"TRAPPED_CHEST\"), langConfig.getString(\"tile.chestTrap.name\", \"Trapped Chest\")));\n itemNames.add(new ItemName(Material.valueOf(\"GOLD_PLATE\"), langConfig.getString(\"tile.weightedPlate_light.name\", \"Weighted Pressure Plate (Light)\")));\n itemNames.add(new ItemName(Material.valueOf(\"IRON_PLATE\"), langConfig.getString(\"tile.weightedPlate_heavy.name\", \"Weighted Pressure Plate (Heavy)\")));\n itemNames.add(new ItemName(Material.valueOf(\"DAYLIGHT_DETECTOR\"), langConfig.getString(\"tile.daylightDetector.name\", \"Daylight Sensor\")));\n itemNames.add(new ItemName(Material.valueOf(\"REDSTONE_BLOCK\"), langConfig.getString(\"tile.blockRedstone.name\", \"Block of Redstone\")));\n itemNames.add(new ItemName(Material.valueOf(\"QUARTZ_ORE\"), langConfig.getString(\"tile.netherquartz.name\", \"Nether Quartz Ore\")));\n itemNames.add(new ItemName(Material.valueOf(\"HOPPER\"), langConfig.getString(\"tile.hopper.name\", \"Hopper\")));\n itemNames.add(new ItemName(Material.valueOf(\"QUARTZ_BLOCK\"), langConfig.getString(\"tile.quartzBlock.default.name\", \"Block of Quartz\")));\n itemNames.add(new ItemName(Material.valueOf(\"QUARTZ_BLOCK\"), langConfig.getString(\"tile.quartzBlock.chiseled.name\", \"Chiseled Quartz Block\")));\n itemNames.add(new ItemName(Material.valueOf(\"QUARTZ_BLOCK\"), langConfig.getString(\"tile.quartzBlock.lines.name\", \"Pillar Quartz Block\")));\n itemNames.add(new ItemName(Material.valueOf(\"QUARTZ_STAIRS\"), langConfig.getString(\"tile.stairsQuartz.name\", \"Quartz Stairs\")));\n itemNames.add(new ItemName(Material.valueOf(\"ACTIVATOR_RAIL\"), langConfig.getString(\"tile.activatorRail.name\", \"Activator Rail\")));\n itemNames.add(new ItemName(Material.valueOf(\"DROPPER\"), langConfig.getString(\"tile.dropper.name\", \"Dropper\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_CLAY\"), langConfig.getString(\"tile.clayHardenedStained.white.name\", \"White Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_CLAY\"), 1, langConfig.getString(\"tile.clayHardenedStained.orange.name\", \"Orange Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_CLAY\"), 2, langConfig.getString(\"tile.clayHardenedStained.magenta.name\", \"Magenta Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_CLAY\"), 3, langConfig.getString(\"tile.clayHardenedStained.lightBlue.name\", \"Light Blue Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_CLAY\"), 4, langConfig.getString(\"tile.clayHardenedStained.yellow.name\", \"Yellow Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_CLAY\"), 5, langConfig.getString(\"tile.clayHardenedStained.lime.name\", \"Lime Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_CLAY\"), 6, langConfig.getString(\"tile.clayHardenedStained.pink.name\", \"Pink Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_CLAY\"), 7, langConfig.getString(\"tile.clayHardenedStained.gray.name\", \"Gray Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_CLAY\"), 8, langConfig.getString(\"tile.clayHardenedStained.silver.name\", \"Light Gray Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_CLAY\"), 9, langConfig.getString(\"tile.clayHardenedStained.cyan.name\", \"Cyan Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_CLAY\"), 10, langConfig.getString(\"tile.clayHardenedStained.purple.name\", \"Purple Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_CLAY\"), 11, langConfig.getString(\"tile.clayHardenedStained.blue.name\", \"Blue Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_CLAY\"), 12, langConfig.getString(\"tile.clayHardenedStained.brown.name\", \"Brown Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_CLAY\"), 13, langConfig.getString(\"tile.clayHardenedStained.green.name\", \"Green Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_CLAY\"), 14, langConfig.getString(\"tile.clayHardenedStained.red.name\", \"Red Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_CLAY\"), 15, langConfig.getString(\"tile.clayHardenedStained.black.name\", \"Black Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS_PANE\"), langConfig.getString(\"tile.thinStainedGlass.white.name\", \"White Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS_PANE\"), 1, langConfig.getString(\"tile.thinStainedGlass.orange.name\", \"Orange Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS_PANE\"), 2, langConfig.getString(\"tile.thinStainedGlass.magenta.name\", \"Magenta Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS_PANE\"), 3, langConfig.getString(\"tile.thinStainedGlass.lightBlue.name\", \"Light Blue Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS_PANE\"), 4, langConfig.getString(\"tile.thinStainedGlass.yellow.name\", \"Yellow Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS_PANE\"), 5, langConfig.getString(\"tile.thinStainedGlass.lime.name\", \"Lime Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS_PANE\"), 6, langConfig.getString(\"tile.thinStainedGlass.pink.name\", \"Pink Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS_PANE\"), 7, langConfig.getString(\"tile.thinStainedGlass.gray.name\", \"Gray Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS_PANE\"), 8, langConfig.getString(\"tile.thinStainedGlass.silver.name\", \"Light Gray Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS_PANE\"), 9, langConfig.getString(\"tile.thinStainedGlass.cyan.name\", \"Cyan Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS_PANE\"), 10, langConfig.getString(\"tile.thinStainedGlass.purple.name\", \"Purple Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS_PANE\"), 11, langConfig.getString(\"tile.thinStainedGlass.blue.name\", \"Blue Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS_PANE\"), 12, langConfig.getString(\"tile.thinStainedGlass.brown.name\", \"Brown Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS_PANE\"), 13, langConfig.getString(\"tile.thinStainedGlass.green.name\", \"Green Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS_PANE\"), 14, langConfig.getString(\"tile.thinStainedGlass.red.name\", \"Red Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.valueOf(\"STAINED_GLASS_PANE\"), 15, langConfig.getString(\"tile.thinStainedGlass.black.name\", \"Black Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.valueOf(\"LEAVES_2\"), langConfig.getString(\"tile.leaves.acacia.name\", \"Acacia Leaves\")));\n itemNames.add(new ItemName(Material.valueOf(\"LEAVES_2\"), 1, langConfig.getString(\"tile.leaves.big_oak.name\", \"Dark Oak Leaves\")));\n itemNames.add(new ItemName(Material.valueOf(\"LOG_2\"), langConfig.getString(\"tile.log.acacia.name\", \"Acacia Wood\")));\n itemNames.add(new ItemName(Material.valueOf(\"LOG_2\"), 1, langConfig.getString(\"tile.log.big_oak.name\", \"Dark Oak Wood\")));\n itemNames.add(new ItemName(Material.valueOf(\"ACACIA_STAIRS\"), langConfig.getString(\"tile.stairsWoodAcacia.name\", \"Acacia Wood Stairs\")));\n itemNames.add(new ItemName(Material.valueOf(\"DARK_OAK_STAIRS\"), langConfig.getString(\"tile.stairsWoodDarkOak.name\", \"Dark Oak Wood Stairs\")));\n itemNames.add(new ItemName(Material.valueOf(\"SLIME_BLOCK\"), langConfig.getString(\"tile.slime.name\", \"Slime Block\")));\n itemNames.add(new ItemName(Material.valueOf(\"BARRIER\"), langConfig.getString(\"tile.barrier.name\", \"Barrier\")));\n itemNames.add(new ItemName(Material.valueOf(\"IRON_TRAPDOOR\"), langConfig.getString(\"tile.ironTrapdoor.name\", \"Iron Trapdoor\")));\n itemNames.add(new ItemName(Material.valueOf(\"PRISMARINE\"), langConfig.getString(\"tile.prismarine.rough.name\", \"Prismarine\")));\n itemNames.add(new ItemName(Material.valueOf(\"PRISMARINE\"), 1, langConfig.getString(\"tile.prismarine.bricks.name\", \"Prismarine Bricks\")));\n itemNames.add(new ItemName(Material.valueOf(\"PRISMARINE\"), 2, langConfig.getString(\"tile.prismarine.dark.name\", \"Dark Prismarine\")));\n itemNames.add(new ItemName(Material.valueOf(\"SEA_LANTERN\"), langConfig.getString(\"tile.seaLantern.name\", \"Sea Lantern\")));\n itemNames.add(new ItemName(Material.valueOf(\"HAY_BLOCK\"), langConfig.getString(\"tile.hayBlock.name\", \"Hay Bale\")));\n itemNames.add(new ItemName(Material.valueOf(\"CARPET\"), langConfig.getString(\"tile.woolCarpet.white.name\", \"White Carpet\")));\n itemNames.add(new ItemName(Material.valueOf(\"CARPET\"), 1, langConfig.getString(\"tile.woolCarpet.orange.name\", \"Orange Carpet\")));\n itemNames.add(new ItemName(Material.valueOf(\"CARPET\"), 2, langConfig.getString(\"tile.woolCarpet.magenta.name\", \"Magenta Carpet\")));\n itemNames.add(new ItemName(Material.valueOf(\"CARPET\"), 3, langConfig.getString(\"tile.woolCarpet.lightBlue.name\", \"Light Blue Carpet\")));\n itemNames.add(new ItemName(Material.valueOf(\"CARPET\"), 4, langConfig.getString(\"tile.woolCarpet.yellow.name\", \"Yellow Carpet\")));\n itemNames.add(new ItemName(Material.valueOf(\"CARPET\"), 5, langConfig.getString(\"tile.woolCarpet.lime.name\", \"Lime Carpet\")));\n itemNames.add(new ItemName(Material.valueOf(\"CARPET\"), 6, langConfig.getString(\"tile.woolCarpet.pink.name\", \"Pink Carpet\")));\n itemNames.add(new ItemName(Material.valueOf(\"CARPET\"), 7, langConfig.getString(\"tile.woolCarpet.gray.name\", \"Gray Carpet\")));\n itemNames.add(new ItemName(Material.valueOf(\"CARPET\"), 8, langConfig.getString(\"tile.woolCarpet.silver.name\", \"Light Gray Carpet\")));\n itemNames.add(new ItemName(Material.valueOf(\"CARPET\"), 9, langConfig.getString(\"tile.woolCarpet.cyan.name\", \"Cyan Carpet\")));\n itemNames.add(new ItemName(Material.valueOf(\"CARPET\"), 10, langConfig.getString(\"tile.woolCarpet.purple.name\", \"Purple Carpet\")));\n itemNames.add(new ItemName(Material.valueOf(\"CARPET\"), 11, langConfig.getString(\"tile.woolCarpet.blue.name\", \"Blue Carpet\")));\n itemNames.add(new ItemName(Material.valueOf(\"CARPET\"), 12, langConfig.getString(\"tile.woolCarpet.brown.name\", \"Brown Carpet\")));\n itemNames.add(new ItemName(Material.valueOf(\"CARPET\"), 13, langConfig.getString(\"tile.woolCarpet.green.name\", \"Green Carpet\")));\n itemNames.add(new ItemName(Material.valueOf(\"CARPET\"), 14, langConfig.getString(\"tile.woolCarpet.red.name\", \"Red Carpet\")));\n itemNames.add(new ItemName(Material.valueOf(\"CARPET\"), 15, langConfig.getString(\"tile.woolCarpet.black.name\", \"Black Carpet\")));\n itemNames.add(new ItemName(Material.valueOf(\"HARD_CLAY\"), langConfig.getString(\"tile.clayHardened.name\", \"Hardened Clay\")));\n itemNames.add(new ItemName(Material.valueOf(\"COAL_BLOCK\"), langConfig.getString(\"tile.blockCoal.name\", \"Block of Coal\")));\n itemNames.add(new ItemName(Material.valueOf(\"PACKED_ICE\"), langConfig.getString(\"tile.icePacked.name\", \"Packed Ice\")));\n itemNames.add(new ItemName(Material.valueOf(\"DOUBLE_PLANT\"), langConfig.getString(\"tile.doublePlant.sunflower.name\", \"Sunflower\")));\n itemNames.add(new ItemName(Material.valueOf(\"DOUBLE_PLANT\"), 1, langConfig.getString(\"tile.doublePlant.syringa.name\", \"Lilac\")));\n itemNames.add(new ItemName(Material.valueOf(\"DOUBLE_PLANT\"), 2, langConfig.getString(\"tile.doublePlant.grass.name\", \"Double Tallgrass\")));\n itemNames.add(new ItemName(Material.valueOf(\"DOUBLE_PLANT\"), 3, langConfig.getString(\"tile.doublePlant.fern.name\", \"Large Fern\")));\n itemNames.add(new ItemName(Material.valueOf(\"DOUBLE_PLANT\"), 4, langConfig.getString(\"tile.doublePlant.rose.name\", \"Rose Bush\")));\n itemNames.add(new ItemName(Material.valueOf(\"DOUBLE_PLANT\"), 5, langConfig.getString(\"tile.doublePlant.paeonia.name\", \"Peony\")));\n itemNames.add(new ItemName(Material.valueOf(\"RED_SANDSTONE\"), langConfig.getString(\"tile.redSandStone.default.name\", \"Red Sandstone\")));\n itemNames.add(new ItemName(Material.valueOf(\"RED_SANDSTONE\"), 1, langConfig.getString(\"tile.redSandStone.chiseled.name\", \"Chiseled Red Sandstone\")));\n itemNames.add(new ItemName(Material.valueOf(\"RED_SANDSTONE\"), 2, langConfig.getString(\"tile.redSandStone.smooth.name\", \"Smooth Red Sandstone\")));\n itemNames.add(new ItemName(Material.valueOf(\"RED_SANDSTONE_STAIRS\"), langConfig.getString(\"tile.stairsRedSandStone.name\", \"Red Sandstone Stairs\")));\n itemNames.add(new ItemName(Material.valueOf(\"STONE_SLAB2\"), langConfig.getString(\"tile.stoneSlab2.red_sandstone.name\", \"Red Sandstone Slab\")));\n itemNames.add(new ItemName(Material.valueOf(\"SPRUCE_FENCE_GATE\"), langConfig.getString(\"tile.spruceFenceGate.name\", \"Spruce Fence Gate\")));\n itemNames.add(new ItemName(Material.valueOf(\"BIRCH_FENCE_GATE\"), langConfig.getString(\"tile.birchFenceGate.name\", \"Birch Fence Gate\")));\n itemNames.add(new ItemName(Material.valueOf(\"JUNGLE_FENCE_GATE\"), langConfig.getString(\"tile.jungleFenceGate.name\", \"Jungle Fence Gate\")));\n itemNames.add(new ItemName(Material.valueOf(\"DARK_OAK_FENCE_GATE\"), langConfig.getString(\"tile.darkOakFenceGate.name\", \"Dark Oak Fence Gate\")));\n itemNames.add(new ItemName(Material.valueOf(\"ACACIA_FENCE_GATE\"), langConfig.getString(\"tile.acaciaFenceGate.name\", \"Acacia Fence Gate\")));\n itemNames.add(new ItemName(Material.valueOf(\"SPRUCE_FENCE\"), langConfig.getString(\"tile.spruceFence.name\", \"Spruce Fence\")));\n itemNames.add(new ItemName(Material.valueOf(\"BIRCH_FENCE\"), langConfig.getString(\"tile.birchFence.name\", \"Birch Fence\")));\n itemNames.add(new ItemName(Material.valueOf(\"JUNGLE_FENCE\"), langConfig.getString(\"tile.jungleFence.name\", \"Jungle Fence\")));\n itemNames.add(new ItemName(Material.valueOf(\"DARK_OAK_FENCE\"), langConfig.getString(\"tile.darkOakFence.name\", \"Dark Oak Fence\")));\n itemNames.add(new ItemName(Material.valueOf(\"ACACIA_FENCE\"), langConfig.getString(\"tile.acaciaFence.name\", \"Acacia Fence\")));\n\n if (Utils.getMajorVersion() >= 9) {\n // Add Block Names of 1.9\n itemNames.add(new ItemName(Material.valueOf(\"END_ROD\"), langConfig.getString(\"tile.endRod.name\", \"End Rod\")));\n itemNames.add(new ItemName(Material.valueOf(\"CHORUS_PLANT\"), langConfig.getString(\"tile.chorusPlant.name\", \"Chorus Plant\")));\n itemNames.add(new ItemName(Material.valueOf(\"CHORUS_FLOWER\"), langConfig.getString(\"tile.chorusFlower.name\", \"Chorus Flower\")));\n itemNames.add(new ItemName(Material.valueOf(\"PURPUR_BLOCK\"), langConfig.getString(\"tile.purpurBlock.name\", \"Purpur Block\")));\n itemNames.add(new ItemName(Material.valueOf(\"PURPUR_PILLAR\"), langConfig.getString(\"tile.purpurPillar.name\", \"Purpur Pillar\")));\n itemNames.add(new ItemName(Material.valueOf(\"PURPUR_STAIRS\"), langConfig.getString(\"tile.stairsPurpur.name\", \"Purpur Stairs\")));\n itemNames.add(new ItemName(Material.valueOf(\"PURPUR_SLAB\"), langConfig.getString(\"tile.purpurSlab.name\", \"Purpur Slab\")));\n itemNames.add(new ItemName(Material.valueOf(\"END_BRICKS\"), langConfig.getString(\"tile.endBricks.name\", \"End Stone Bricks\")));\n itemNames.add(new ItemName(Material.valueOf(\"GRASS_PATH\"), langConfig.getString(\"tile.grassPath.name\", \"Grass Path\")));\n itemNames.add(new ItemName(Material.valueOf(\"COMMAND_REPEATING\"), langConfig.getString(\"tile.repeatingCommandBlock.name\", \"Repeating Command Block\")));\n itemNames.add(new ItemName(Material.valueOf(\"COMMAND_CHAIN\"), langConfig.getString(\"tile.chainCommandBlock.name\", \"Chain Command Block\")));\n itemNames.add(new ItemName(Material.valueOf(\"STRUCTURE_BLOCK\"), langConfig.getString(\"tile.structureBlock.name\", \"Structure Block\")));\n }\n\n if (Utils.getMajorVersion() >= 10) {\n // Add Block Names of 1.10\n itemNames.add(new ItemName(Material.valueOf(\"MAGMA\"), langConfig.getString(\"tile.magma.name\", \"Magma Block\")));\n itemNames.add(new ItemName(Material.valueOf(\"NETHER_WART_BLOCK\"), langConfig.getString(\"tile.netherWartBlock.name\", \"Nether Wart Block\")));\n itemNames.add(new ItemName(Material.valueOf(\"RED_NETHER_BRICK\"), langConfig.getString(\"tile.redNetherBrick.name\", \"Red Nether Brick\")));\n itemNames.add(new ItemName(Material.valueOf(\"BONE_BLOCK\"), langConfig.getString(\"tile.boneBlock.name\", \"Bone Block\")));\n itemNames.add(new ItemName(Material.valueOf(\"STRUCTURE_VOID\"), langConfig.getString(\"tile.structureVoid.name\", \"Structure Void\")));\n }\n\n if (Utils.getMajorVersion() >= 11) {\n // Add Block Names of 1.11\n itemNames.add(new ItemName(Material.valueOf(\"OBSERVER\"), langConfig.getString(\"tile.observer.name\", \"Observer\")));\n itemNames.add(new ItemName(Material.valueOf(\"WHITE_SHULKER_BOX\"), langConfig.getString(\"tile.shulkerBoxWhite.name\", \"White Shulker Box\")));\n itemNames.add(new ItemName(Material.valueOf(\"ORANGE_SHULKER_BOX\"), langConfig.getString(\"tile.shulkerBoxOrange.name\", \"Orange Shulker Box\")));\n itemNames.add(new ItemName(Material.valueOf(\"MAGENTA_SHULKER_BOX\"), langConfig.getString(\"tile.shulkerBoxMagenta.name\", \"Magenta Shulker Box\")));\n itemNames.add(new ItemName(Material.valueOf(\"LIGHT_BLUE_SHULKER_BOX\"), langConfig.getString(\"tile.shulkerBoxLightBlue.name\", \"Light Blue Shulker Box\")));\n itemNames.add(new ItemName(Material.valueOf(\"YELLOW_SHULKER_BOX\"), langConfig.getString(\"tile.shulkerBoxYellow.name\", \"Yellow Shulker Box\")));\n itemNames.add(new ItemName(Material.valueOf(\"LIME_SHULKER_BOX\"), langConfig.getString(\"tile.shulkerBoxLime.name\", \"Lime Shulker Box\")));\n itemNames.add(new ItemName(Material.valueOf(\"PINK_SHULKER_BOX\"), langConfig.getString(\"tile.shulkerBoxPink.name\", \"Pink Shulker Box\")));\n itemNames.add(new ItemName(Material.valueOf(\"GRAY_SHULKER_BOX\"), langConfig.getString(\"tile.shulkerBoxGray.name\", \"Gray Shulker Box\")));\n itemNames.add(new ItemName(Material.valueOf(\"SILVER_SHULKER_BOX\"), langConfig.getString(\"tile.shulkerBoxSilver.name\", \"Light Gray Shulker Box\")));\n itemNames.add(new ItemName(Material.valueOf(\"CYAN_SHULKER_BOX\"), langConfig.getString(\"tile.shulkerBoxCyan.name\", \"Cyan Shulker Box\")));\n itemNames.add(new ItemName(Material.valueOf(\"PURPLE_SHULKER_BOX\"), langConfig.getString(\"tile.shulkerBoxPurple.name\", \"Purple Shulker Box\")));\n itemNames.add(new ItemName(Material.valueOf(\"BLUE_SHULKER_BOX\"), langConfig.getString(\"tile.shulkerBoxBlue.name\", \"Blue Shulker Box\")));\n itemNames.add(new ItemName(Material.valueOf(\"BROWN_SHULKER_BOX\"), langConfig.getString(\"tile.shulkerBoxBrown.name\", \"Brown Shulker Box\")));\n itemNames.add(new ItemName(Material.valueOf(\"GREEN_SHULKER_BOX\"), langConfig.getString(\"tile.shulkerBoxGreen.name\", \"Green Shulker Box\")));\n itemNames.add(new ItemName(Material.valueOf(\"RED_SHULKER_BOX\"), langConfig.getString(\"tile.shulkerBoxRed.name\", \"Red Shulker Box\")));\n itemNames.add(new ItemName(Material.valueOf(\"BLACK_SHULKER_BOX\"), langConfig.getString(\"tile.shulkerBoxBlack.name\", \"Black Shulker Box\")));\n }\n\n if (Utils.getMajorVersion() >= 12) {\n // Add Block Names of 1.12\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE\"), langConfig.getString(\"tile.concrete.white.name\", \"White Concrete\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE\"), 1, langConfig.getString(\"tile.concrete.orange.name\", \"Orange Concrete\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE\"), 2, langConfig.getString(\"tile.concrete.magenta.name\", \"Magenta Concrete\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE\"), 3, langConfig.getString(\"tile.concrete.lightBlue.name\", \"Light Blue Concrete\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE\"), 4, langConfig.getString(\"tile.concrete.yellow.name\", \"Yellow Concrete\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE\"), 5, langConfig.getString(\"tile.concrete.lime.name\", \"Lime Concrete\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE\"), 6, langConfig.getString(\"tile.concrete.pink.name\", \"Pink Concrete\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE\"), 7, langConfig.getString(\"tile.concrete.gray.name\", \"Gray Concrete\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE\"), 8, langConfig.getString(\"tile.concrete.silver.name\", \"Light Gray Concrete\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE\"), 9, langConfig.getString(\"tile.concrete.cyan.name\", \"Cyan Concrete\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE\"), 10, langConfig.getString(\"tile.concrete.purple.name\", \"Purple Concrete\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE\"), 11, langConfig.getString(\"tile.concrete.blue.name\", \"Blue Concrete\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE\"), 12, langConfig.getString(\"tile.concrete.brown.name\", \"Brown Concrete\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE\"), 13, langConfig.getString(\"tile.concrete.green.name\", \"Green Concrete\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE\"), 14, langConfig.getString(\"tile.concrete.red.name\", \"Red Concrete\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE\"), 15, langConfig.getString(\"tile.concrete.black.name\", \"Black Concrete\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE_POWDER\"), langConfig.getString(\"tile.concretePowder.white.name\", \"White Concrete Powder\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE_POWDER\"), 1, langConfig.getString(\"tile.concretePowder.orange.name\", \"Orange Concrete Powder\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE_POWDER\"), 2, langConfig.getString(\"tile.concretePowder.magenta.name\", \"Magenta Concrete Powder\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE_POWDER\"), 3, langConfig.getString(\"tile.concretePowder.lightBlue.name\", \"Light Blue Concrete Powder\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE_POWDER\"), 4, langConfig.getString(\"tile.concretePowder.yellow.name\", \"Yellow Concrete Powder\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE_POWDER\"), 5, langConfig.getString(\"tile.concretePowder.lime.name\", \"Lime Concrete Powder\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE_POWDER\"), 6, langConfig.getString(\"tile.concretePowder.pink.name\", \"Pink Concrete Powder\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE_POWDER\"), 7, langConfig.getString(\"tile.concretePowder.gray.name\", \"Gray Concrete Powder\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE_POWDER\"), 8, langConfig.getString(\"tile.concretePowder.silver.name\", \"Light Gray Concrete Powder\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE_POWDER\"), 9, langConfig.getString(\"tile.concretePowder.cyan.name\", \"Cyan Concrete Powder\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE_POWDER\"), 10, langConfig.getString(\"tile.concretePowder.purple.name\", \"Purple Concrete Powder\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE_POWDER\"), 11, langConfig.getString(\"tile.concretePowder.blue.name\", \"Blue Concrete Powder\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE_POWDER\"), 12, langConfig.getString(\"tile.concretePowder.brown.name\", \"Brown Concrete Powder\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE_POWDER\"), 13, langConfig.getString(\"tile.concretePowder.green.name\", \"Green Concrete Powder\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE_POWDER\"), 14, langConfig.getString(\"tile.concretePowder.red.name\", \"Red Concrete Powder\")));\n itemNames.add(new ItemName(Material.valueOf(\"CONCRETE_POWDER\"), 15, langConfig.getString(\"tile.concretePowder.black.name\", \"Black Concrete Powder\")));\n itemNames.add(new ItemName(Material.valueOf(\"WHITE_GLAZED_TERRACOTTA\"), langConfig.getString(\"tile.glazedTerracottaWhite.name\", \"White Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"ORANGE_GLAZED_TERRACOTTA\"), langConfig.getString(\"tile.glazedTerracottaOrange.name\", \"Orange Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"MAGENTA_GLAZED_TERRACOTTA\"), langConfig.getString(\"tile.glazedTerracottaMagenta.name\", \"Magenta Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"LIGHT_BLUE_GLAZED_TERRACOTTA\"), langConfig.getString(\"tile.glazedTerracottaLightBlue.name\", \"Light Blue Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"YELLOW_GLAZED_TERRACOTTA\"), langConfig.getString(\"tile.glazedTerracottaYellow.name\", \"Yellow Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"LIME_GLAZED_TERRACOTTA\"), langConfig.getString(\"tile.glazedTerracottaLime.name\", \"Lime Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"PINK_GLAZED_TERRACOTTA\"), langConfig.getString(\"tile.glazedTerracottaPink.name\", \"Pink Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"GRAY_GLAZED_TERRACOTTA\"), langConfig.getString(\"tile.glazedTerracottaGray.name\", \"Gray Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"SILVER_GLAZED_TERRACOTTA\"), langConfig.getString(\"tile.glazedTerracottaSilver.name\", \"Light Gray Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"CYAN_GLAZED_TERRACOTTA\"), langConfig.getString(\"tile.glazedTerracottaCyan.name\", \"Cyan Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"PURPLE_GLAZED_TERRACOTTA\"), langConfig.getString(\"tile.glazedTerracottaPurple.name\", \"Purple Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"BLUE_GLAZED_TERRACOTTA\"), langConfig.getString(\"tile.glazedTerracottaBlue.name\", \"Blue Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"BROWN_GLAZED_TERRACOTTA\"), langConfig.getString(\"tile.glazedTerracottaBrown.name\", \"Brown Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"GREEN_GLAZED_TERRACOTTA\"), langConfig.getString(\"tile.glazedTerracottaGreen.name\", \"Green Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"RED_GLAZED_TERRACOTTA\"), langConfig.getString(\"tile.glazedTerracottaRed.name\", \"Red Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.valueOf(\"BLACK_GLAZED_TERRACOTTA\"), langConfig.getString(\"tile.glazedTerracottaBlack.name\", \"Black Glazed Terracotta\")));\n }\n\n // Add Item Names\n itemNames.add(new ItemName(Material.valueOf(\"IRON_SPADE\"), langConfig.getString(\"item.shovelIron.name\", \"Iron Shovel\")));\n itemNames.add(new ItemName(Material.valueOf(\"IRON_PICKAXE\"), langConfig.getString(\"item.pickaxeIron.name\", \"Iron Pickaxe\")));\n itemNames.add(new ItemName(Material.valueOf(\"IRON_AXE\"), langConfig.getString(\"item.hatchetIron.name\", \"Iron Axe\")));\n itemNames.add(new ItemName(Material.valueOf(\"FLINT_AND_STEEL\"), langConfig.getString(\"item.flintAndSteel.name\", \"Flint and Steel\")));\n itemNames.add(new ItemName(Material.valueOf(\"APPLE\"), langConfig.getString(\"item.apple.name\", \"Apple\")));\n itemNames.add(new ItemName(Material.valueOf(\"BOW\"), langConfig.getString(\"item.bow.name\", \"Bow\")));\n itemNames.add(new ItemName(Material.valueOf(\"ARROW\"), langConfig.getString(\"item.arrow.name\", \"Arrow\")));\n itemNames.add(new ItemName(Material.valueOf(\"COAL\"), langConfig.getString(\"item.coal.name\", \"Coal\")));\n itemNames.add(new ItemName(Material.valueOf(\"COAL\"), 1, langConfig.getString(\"item.charcoal.name\", \"Charcoal\")));\n itemNames.add(new ItemName(Material.valueOf(\"DIAMOND\"), langConfig.getString(\"item.diamond.name\", \"Diamond\")));\n itemNames.add(new ItemName(Material.valueOf(\"IRON_INGOT\"), langConfig.getString(\"item.ingotIron.name\", \"Iron Ingot\")));\n itemNames.add(new ItemName(Material.valueOf(\"GOLD_INGOT\"), langConfig.getString(\"item.ingotGold.name\", \"Gold Ingot\")));\n itemNames.add(new ItemName(Material.valueOf(\"IRON_SWORD\"), langConfig.getString(\"item.swordIron.name\", \"Iron Sword\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOD_SWORD\"), langConfig.getString(\"item.swordWood.name\", \"Wooden Sword\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOD_SPADE\"), langConfig.getString(\"item.shovelWood.name\", \"Wooden Shovel\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOD_PICKAXE\"), langConfig.getString(\"item.pickaxeWood.name\", \"Wooden Pickaxe\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOD_AXE\"), langConfig.getString(\"item.hatchetWood.name\", \"Wooden Axe\")));\n itemNames.add(new ItemName(Material.valueOf(\"STONE_SWORD\"), langConfig.getString(\"item.swordStone.name\", \"Stone Sword\")));\n itemNames.add(new ItemName(Material.valueOf(\"STONE_SPADE\"), langConfig.getString(\"item.shovelStone.name\", \"Stone Shovel\")));\n itemNames.add(new ItemName(Material.valueOf(\"STONE_PICKAXE\"), langConfig.getString(\"item.pickaxeStone.name\", \"Stone Pickaxe\")));\n itemNames.add(new ItemName(Material.valueOf(\"STONE_AXE\"), langConfig.getString(\"item.hatchetStone.name\", \"Stone Axe\")));\n itemNames.add(new ItemName(Material.valueOf(\"DIAMOND_SWORD\"), langConfig.getString(\"item.swordDiamond.name\", \"Diamond Sword\")));\n itemNames.add(new ItemName(Material.valueOf(\"DIAMOND_SPADE\"), langConfig.getString(\"item.shovelDiamond.name\", \"Diamond Shovel\")));\n itemNames.add(new ItemName(Material.valueOf(\"DIAMOND_PICKAXE\"), langConfig.getString(\"item.pickaxeDiamond.name\", \"Diamond Pickaxe\")));\n itemNames.add(new ItemName(Material.valueOf(\"DIAMOND_AXE\"), langConfig.getString(\"item.hatchetDiamond.name\", \"Diamond Axe\")));\n itemNames.add(new ItemName(Material.valueOf(\"STICK\"), langConfig.getString(\"item.stick.name\", \"Stick\")));\n itemNames.add(new ItemName(Material.valueOf(\"BOWL\"), langConfig.getString(\"item.bowl.name\", \"Bowl\")));\n itemNames.add(new ItemName(Material.valueOf(\"MUSHROOM_SOUP\"), langConfig.getString(\"item.mushroomStew.name\", \"Mushroom Stew\")));\n itemNames.add(new ItemName(Material.valueOf(\"GOLD_SWORD\"), langConfig.getString(\"item.swordGold.name\", \"Golden Sword\")));\n itemNames.add(new ItemName(Material.valueOf(\"GOLD_SPADE\"), langConfig.getString(\"item.shovelGold.name\", \"Golden Shovel\")));\n itemNames.add(new ItemName(Material.valueOf(\"GOLD_PICKAXE\"), langConfig.getString(\"item.pickaxeGold.name\", \"Golden Pickaxe\")));\n itemNames.add(new ItemName(Material.valueOf(\"GOLD_AXE\"), langConfig.getString(\"item.hatchetGold.name\", \"Golden Axe\")));\n itemNames.add(new ItemName(Material.valueOf(\"STRING\"), langConfig.getString(\"item.string.name\", \"String\")));\n itemNames.add(new ItemName(Material.valueOf(\"FEATHER\"), langConfig.getString(\"item.feather.name\", \"Feather\")));\n itemNames.add(new ItemName(Material.valueOf(\"SULPHUR\"), langConfig.getString(\"item.sulphur.name\", \"Gunpowder\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOD_HOE\"), langConfig.getString(\"item.hoeWood.name\", \"Wooden Hoe\")));\n itemNames.add(new ItemName(Material.valueOf(\"STONE_HOE\"), langConfig.getString(\"item.hoeStone.name\", \"Stone Hoe\")));\n itemNames.add(new ItemName(Material.valueOf(\"IRON_HOE\"), langConfig.getString(\"item.hoeIron.name\", \"Iron Hoe\")));\n itemNames.add(new ItemName(Material.valueOf(\"DIAMOND_HOE\"), langConfig.getString(\"item.hoeDiamond.name\", \"Diamond Hoe\")));\n itemNames.add(new ItemName(Material.valueOf(\"GOLD_HOE\"), langConfig.getString(\"item.hoeGold.name\", \"Golden Hoe\")));\n itemNames.add(new ItemName(Material.valueOf(\"SEEDS\"), langConfig.getString(\"item.seeds.name\", \"Seeds\")));\n itemNames.add(new ItemName(Material.valueOf(\"WHEAT\"), langConfig.getString(\"item.wheat.name\", \"Wheat\")));\n itemNames.add(new ItemName(Material.valueOf(\"BREAD\"), langConfig.getString(\"item.bread.name\", \"Bread\")));\n itemNames.add(new ItemName(Material.valueOf(\"LEATHER_HELMET\"), langConfig.getString(\"item.helmetCloth.name\", \"Leather Cap\")));\n itemNames.add(new ItemName(Material.valueOf(\"LEATHER_CHESTPLATE\"), langConfig.getString(\"item.chestplateCloth.name\", \"Leather Tunic\")));\n itemNames.add(new ItemName(Material.valueOf(\"LEATHER_LEGGINGS\"), langConfig.getString(\"item.leggingsCloth.name\", \"Leather Pants\")));\n itemNames.add(new ItemName(Material.valueOf(\"LEATHER_BOOTS\"), langConfig.getString(\"item.bootsCloth.name\", \"Leather Boots\")));\n itemNames.add(new ItemName(Material.valueOf(\"CHAINMAIL_HELMET\"), langConfig.getString(\"item.helmetChain.name\", \"Chain Helmet\")));\n itemNames.add(new ItemName(Material.valueOf(\"CHAINMAIL_CHESTPLATE\"), langConfig.getString(\"item.chestplateChain.name\", \"Chain Chestplate\")));\n itemNames.add(new ItemName(Material.valueOf(\"CHAINMAIL_LEGGINGS\"), langConfig.getString(\"item.leggingsChain.name\", \"Chain Leggings\")));\n itemNames.add(new ItemName(Material.valueOf(\"CHAINMAIL_BOOTS\"), langConfig.getString(\"item.bootsChain.name\", \"Chain Boots\")));\n itemNames.add(new ItemName(Material.valueOf(\"IRON_HELMET\"), langConfig.getString(\"item.helmetIron.name\", \"Iron Helmet\")));\n itemNames.add(new ItemName(Material.valueOf(\"IRON_CHESTPLATE\"), langConfig.getString(\"item.chestplateIron.name\", \"Iron Chestplate\")));\n itemNames.add(new ItemName(Material.valueOf(\"IRON_LEGGINGS\"), langConfig.getString(\"item.leggingsIron.name\", \"Iron Leggings\")));\n itemNames.add(new ItemName(Material.valueOf(\"IRON_BOOTS\"), langConfig.getString(\"item.bootsIron.name\", \"Iron Boots\")));\n itemNames.add(new ItemName(Material.valueOf(\"DIAMOND_HELMET\"), langConfig.getString(\"item.helmetDiamond.name\", \"Diamond Helmet\")));\n itemNames.add(new ItemName(Material.valueOf(\"DIAMOND_CHESTPLATE\"), langConfig.getString(\"item.chestplateDiamond.name\", \"Diamond Chestplate\")));\n itemNames.add(new ItemName(Material.valueOf(\"DIAMOND_LEGGINGS\"), langConfig.getString(\"item.leggingsDiamond.name\", \"Diamond Leggings\")));\n itemNames.add(new ItemName(Material.valueOf(\"DIAMOND_BOOTS\"), langConfig.getString(\"item.bootsDiamond.name\", \"Diamond Boots\")));\n itemNames.add(new ItemName(Material.valueOf(\"GOLD_HELMET\"), langConfig.getString(\"item.helmetGold.name\", \"Golden Helmet\")));\n itemNames.add(new ItemName(Material.valueOf(\"GOLD_CHESTPLATE\"), langConfig.getString(\"item.chestplateGold.name\", \"Golden Chestplate\")));\n itemNames.add(new ItemName(Material.valueOf(\"GOLD_LEGGINGS\"), langConfig.getString(\"item.leggingsGold.name\", \"Golden Leggings\")));\n itemNames.add(new ItemName(Material.valueOf(\"GOLD_BOOTS\"), langConfig.getString(\"item.bootsGold.name\", \"Golden Boots\")));\n itemNames.add(new ItemName(Material.valueOf(\"FLINT\"), langConfig.getString(\"item.flint.name\", \"Flint\")));\n itemNames.add(new ItemName(Material.valueOf(\"PORK\"), langConfig.getString(\"item.porkchopRaw.name\", \"Raw Porkchop\")));\n itemNames.add(new ItemName(Material.valueOf(\"GRILLED_PORK\"), langConfig.getString(\"item.porkchopCooked.name\", \"Cooked Porkchop\")));\n itemNames.add(new ItemName(Material.valueOf(\"PAINTING\"), langConfig.getString(\"item.painting.name\", \"Painting\")));\n itemNames.add(new ItemName(Material.valueOf(\"GOLDEN_APPLE\"), langConfig.getString(\"item.appleGold.name\", \"Golden Apple\")));\n itemNames.add(new ItemName(Material.valueOf(\"GOLDEN_APPLE\"), 1, langConfig.getString(\"item.appleGold.name\", \"Golden Apple\")));\n itemNames.add(new ItemName(Material.valueOf(\"SIGN\"), langConfig.getString(\"item.sign.name\", \"Sign\")));\n itemNames.add(new ItemName(Material.valueOf(\"WOOD_DOOR\"), langConfig.getString(\"item.doorOak.name\", \"Oak Door\")));\n itemNames.add(new ItemName(Material.valueOf(\"BUCKET\"), langConfig.getString(\"item.bucket.name\", \"Bucket\")));\n itemNames.add(new ItemName(Material.valueOf(\"WATER_BUCKET\"), langConfig.getString(\"item.bucketWater.name\", \"Water Bucket\")));\n itemNames.add(new ItemName(Material.valueOf(\"LAVA_BUCKET\"), langConfig.getString(\"item.bucketLava.name\", \"Lava Bucket\")));\n itemNames.add(new ItemName(Material.valueOf(\"MINECART\"), langConfig.getString(\"item.minecart.name\", \"Minecart\")));\n itemNames.add(new ItemName(Material.valueOf(\"SADDLE\"), langConfig.getString(\"item.saddle.name\", \"Saddle\")));\n itemNames.add(new ItemName(Material.valueOf(\"IRON_DOOR\"), langConfig.getString(\"item.doorIron.name\", \"Iron Door\")));\n itemNames.add(new ItemName(Material.valueOf(\"REDSTONE\"), langConfig.getString(\"item.redstone.name\", \"Redstone\")));\n itemNames.add(new ItemName(Material.valueOf(\"SNOW_BALL\"), langConfig.getString(\"item.snowball.name\", \"Snowball\")));\n itemNames.add(new ItemName(Material.valueOf(\"BOAT\"), langConfig.getString(\"item.boat.oak.name\", \"Oak Boat\")));\n itemNames.add(new ItemName(Material.valueOf(\"LEATHER\"), langConfig.getString(\"item.leather.name\", \"Leather\")));\n itemNames.add(new ItemName(Material.valueOf(\"MILK_BUCKET\"), langConfig.getString(\"item.milk.name\", \"Milk\")));\n itemNames.add(new ItemName(Material.valueOf(\"BRICK\"), langConfig.getString(\"item.brick.name\", \"Brick\")));\n itemNames.add(new ItemName(Material.valueOf(\"CLAY_BALL\"), langConfig.getString(\"item.clay.name\", \"Clay\")));\n itemNames.add(new ItemName(Material.valueOf(\"SUGAR_CANE\"), langConfig.getString(\"item.reeds.name\", \"Sugar Canes\")));\n itemNames.add(new ItemName(Material.valueOf(\"PAPER\"), langConfig.getString(\"item.paper.name\", \"Paper\")));\n itemNames.add(new ItemName(Material.valueOf(\"BOOK\"), langConfig.getString(\"item.book.name\", \"Book\")));\n itemNames.add(new ItemName(Material.valueOf(\"SLIME_BALL\"), langConfig.getString(\"item.slimeball.name\", \"Slimeball\")));\n itemNames.add(new ItemName(Material.valueOf(\"STORAGE_MINECART\"), langConfig.getString(\"item.minecartChest.name\", \"Minecart with Chest\")));\n itemNames.add(new ItemName(Material.valueOf(\"POWERED_MINECART\"), langConfig.getString(\"item.minecartFurnace.name\", \"Minecart with Furnace\")));\n itemNames.add(new ItemName(Material.valueOf(\"EGG\"), langConfig.getString(\"item.egg.name\", \"Egg\")));\n itemNames.add(new ItemName(Material.valueOf(\"COMPASS\"), langConfig.getString(\"item.compass.name\", \"Compass\")));\n itemNames.add(new ItemName(Material.valueOf(\"FISHING_ROD\"), langConfig.getString(\"item.fishingRod.name\", \"Fishing Rod\")));\n itemNames.add(new ItemName(Material.valueOf(\"WATCH\"), langConfig.getString(\"item.clock.name\", \"Clock\")));\n itemNames.add(new ItemName(Material.valueOf(\"GLOWSTONE_DUST\"), langConfig.getString(\"item.yellowDust.name\", \"Glowstone Dust\")));\n itemNames.add(new ItemName(Material.valueOf(\"RAW_FISH\"), langConfig.getString(\"item.fish.cod.raw.name\", \"Raw Fish\")));\n itemNames.add(new ItemName(Material.valueOf(\"RAW_FISH\"), 1, langConfig.getString(\"item.fish.salmon.raw.name\", \"Raw Salmon\")));\n itemNames.add(new ItemName(Material.valueOf(\"RAW_FISH\"), 2, langConfig.getString(\"item.fish.clownfish.raw.name\", \"Clownfish\")));\n itemNames.add(new ItemName(Material.valueOf(\"RAW_FISH\"), 3, langConfig.getString(\"item.fish.pufferfish.raw.name\", \"Pufferfish\")));\n itemNames.add(new ItemName(Material.valueOf(\"COOKED_FISH\"), langConfig.getString(\"item.fish.cod.cooked.name\", \"Cooked Fish\")));\n itemNames.add(new ItemName(Material.valueOf(\"COOKED_FISH\"), 1, langConfig.getString(\"item.fish.salmon.cooked.name\", \"Cooked Salmon\")));\n itemNames.add(new ItemName(Material.valueOf(\"INK_SACK\"), langConfig.getString(\"item.dyePowder.black.name\", \"Ink Sac\")));\n itemNames.add(new ItemName(Material.valueOf(\"INK_SACK\"), 1, langConfig.getString(\"item.dyePowder.red.name\", \"Rose Red\")));\n itemNames.add(new ItemName(Material.valueOf(\"INK_SACK\"), 2, langConfig.getString(\"item.dyePowder.green.name\", \"Cactus Green\")));\n itemNames.add(new ItemName(Material.valueOf(\"INK_SACK\"), 3, langConfig.getString(\"item.dyePowder.brown.name\", \"Cocoa Beans\")));\n itemNames.add(new ItemName(Material.valueOf(\"INK_SACK\"), 4, langConfig.getString(\"item.dyePowder.blue.name\", \"Lapis Lazuli\")));\n itemNames.add(new ItemName(Material.valueOf(\"INK_SACK\"), 5, langConfig.getString(\"item.dyePowder.purple.name\", \"Purple Dye\")));\n itemNames.add(new ItemName(Material.valueOf(\"INK_SACK\"), 6, langConfig.getString(\"item.dyePowder.cyan.name\", \"Cyan Dye\")));\n itemNames.add(new ItemName(Material.valueOf(\"INK_SACK\"), 7, langConfig.getString(\"item.dyePowder.silver.name\", \"Light Gray Dye\")));\n itemNames.add(new ItemName(Material.valueOf(\"INK_SACK\"), 8, langConfig.getString(\"item.dyePowder.gray.name\", \"Gray Dye\")));\n itemNames.add(new ItemName(Material.valueOf(\"INK_SACK\"), 9, langConfig.getString(\"item.dyePowder.pink.name\", \"Pink Dye\")));\n itemNames.add(new ItemName(Material.valueOf(\"INK_SACK\"), 10, langConfig.getString(\"item.dyePowder.lime.name\", \"Lime Dye\")));\n itemNames.add(new ItemName(Material.valueOf(\"INK_SACK\"), 11, langConfig.getString(\"item.dyePowder.yellow.name\", \"Dandelion Yellow\")));\n itemNames.add(new ItemName(Material.valueOf(\"INK_SACK\"), 12, langConfig.getString(\"item.dyePowder.lightBlue.name\", \"Light Blue Dye\")));\n itemNames.add(new ItemName(Material.valueOf(\"INK_SACK\"), 13, langConfig.getString(\"item.dyePowder.magenta.name\", \"Magenta Dye\")));\n itemNames.add(new ItemName(Material.valueOf(\"INK_SACK\"), 14, langConfig.getString(\"item.dyePowder.orange.name\", \"Orange Dye\")));\n itemNames.add(new ItemName(Material.valueOf(\"INK_SACK\"), 15, langConfig.getString(\"item.dyePowder.white.name\", \"Bone Meal\")));\n itemNames.add(new ItemName(Material.valueOf(\"BONE\"), langConfig.getString(\"item.bone.name\", \"Bone\")));\n itemNames.add(new ItemName(Material.valueOf(\"SUGAR\"), langConfig.getString(\"item.sugar.name\", \"Sugar\")));\n itemNames.add(new ItemName(Material.valueOf(\"CAKE\"), langConfig.getString(\"item.cake.name\", \"Cake\")));\n itemNames.add(new ItemName(Material.valueOf(\"DIODE\"), langConfig.getString(\"item.diode.name\", \"Redstone Repeater\")));\n itemNames.add(new ItemName(Material.valueOf(\"COOKIE\"), langConfig.getString(\"item.cookie.name\", \"Cookie\")));\n itemNames.add(new ItemName(Material.valueOf(\"MAP\"), langConfig.getString(\"item.map.name\", \"Map\")));\n itemNames.add(new ItemName(Material.valueOf(\"SHEARS\"), langConfig.getString(\"item.shears.name\", \"Shears\")));\n itemNames.add(new ItemName(Material.valueOf(\"MELON\"), langConfig.getString(\"item.melon.name\", \"Melon\")));\n itemNames.add(new ItemName(Material.valueOf(\"PUMPKIN_SEEDS\"), langConfig.getString(\"item.seeds_pumpkin.name\", \"Pumpkin Seeds\")));\n itemNames.add(new ItemName(Material.valueOf(\"MELON_SEEDS\"), langConfig.getString(\"item.seeds_melon.name\", \"Melon Seeds\")));\n itemNames.add(new ItemName(Material.valueOf(\"RAW_BEEF\"), langConfig.getString(\"item.beefRaw.name\", \"Raw Beef\")));\n itemNames.add(new ItemName(Material.valueOf(\"COOKED_BEEF\"), langConfig.getString(\"item.beefCooked.name\", \"Steak\")));\n itemNames.add(new ItemName(Material.valueOf(\"RAW_CHICKEN\"), langConfig.getString(\"item.chickenRaw.name\", \"Raw Chicken\")));\n itemNames.add(new ItemName(Material.valueOf(\"COOKED_CHICKEN\"), langConfig.getString(\"item.chickenCooked.name\", \"Cooked Chicken\")));\n itemNames.add(new ItemName(Material.valueOf(\"ROTTEN_FLESH\"), langConfig.getString(\"item.rottenFlesh.name\", \"Rotten Flesh\")));\n itemNames.add(new ItemName(Material.valueOf(\"ENDER_PEARL\"), langConfig.getString(\"item.enderPearl.name\", \"Ender Pearl\")));\n itemNames.add(new ItemName(Material.valueOf(\"BLAZE_ROD\"), langConfig.getString(\"item.blazeRod.name\", \"Blaze Rod\")));\n itemNames.add(new ItemName(Material.valueOf(\"GHAST_TEAR\"), langConfig.getString(\"item.ghastTear.name\", \"Ghast Tear\")));\n itemNames.add(new ItemName(Material.valueOf(\"GOLD_NUGGET\"), langConfig.getString(\"item.goldNugget.name\", \"Gold Nugget\")));\n itemNames.add(new ItemName(Material.valueOf(\"NETHER_WARTS\"), langConfig.getString(\"item.netherStalkSeeds.name\", \"Nether Wart\")));\n itemNames.add(new ItemName(Material.valueOf(\"POTION\"), langConfig.getString(\"item.potion.name\", \"Potion\")));\n itemNames.add(new ItemName(Material.valueOf(\"GLASS_BOTTLE\"), langConfig.getString(\"item.glassBottle.name\", \"Glass Bottle\")));\n itemNames.add(new ItemName(Material.valueOf(\"SPIDER_EYE\"), langConfig.getString(\"item.spiderEye.name\", \"Spider Eye\")));\n itemNames.add(new ItemName(Material.valueOf(\"FERMENTED_SPIDER_EYE\"), langConfig.getString(\"item.fermentedSpiderEye.name\", \"Fermented Spider Eye\")));\n itemNames.add(new ItemName(Material.valueOf(\"BLAZE_POWDER\"), langConfig.getString(\"item.blazePowder.name\", \"Blaze Powder\")));\n itemNames.add(new ItemName(Material.valueOf(\"MAGMA_CREAM\"), langConfig.getString(\"item.magmaCream.name\", \"Magma Cream\")));\n itemNames.add(new ItemName(Material.valueOf(\"BREWING_STAND_ITEM\"), langConfig.getString(\"item.brewingStand.name\", \"Brewing Stand\")));\n itemNames.add(new ItemName(Material.valueOf(\"CAULDRON_ITEM\"), langConfig.getString(\"item.cauldron.name\", \"Cauldron\")));\n itemNames.add(new ItemName(Material.valueOf(\"EYE_OF_ENDER\"), langConfig.getString(\"item.eyeOfEnder.name\", \"Eye of Ender\")));\n itemNames.add(new ItemName(Material.valueOf(\"SPECKLED_MELON\"), langConfig.getString(\"item.speckledMelon.name\", \"Glistering Melon\")));\n itemNames.add(new ItemName(Material.valueOf(\"MONSTER_EGG\"), langConfig.getString(\"item.monsterPlacer.name\", \"Spawn\")));\n itemNames.add(new ItemName(Material.valueOf(\"EXP_BOTTLE\"), langConfig.getString(\"item.expBottle.name\", \"Bottle o' Enchanting\")));\n itemNames.add(new ItemName(Material.valueOf(\"FIREWORK_CHARGE\"), langConfig.getString(\"item.fireball.name\", \"Fire Charge\")));\n itemNames.add(new ItemName(Material.valueOf(\"BOOK_AND_QUILL\"), langConfig.getString(\"item.writingBook.name\", \"Book and Quill\")));\n itemNames.add(new ItemName(Material.valueOf(\"WRITTEN_BOOK\"), langConfig.getString(\"item.writtenBook.name\", \"Written Book\")));\n itemNames.add(new ItemName(Material.valueOf(\"EMERALD\"), langConfig.getString(\"item.emerald.name\", \"Emerald\")));\n itemNames.add(new ItemName(Material.valueOf(\"ITEM_FRAME\"), langConfig.getString(\"item.frame.name\", \"Item Frame\")));\n itemNames.add(new ItemName(Material.valueOf(\"FLOWER_POT_ITEM\"), langConfig.getString(\"item.flowerPot.name\", \"Flower Pot\")));\n itemNames.add(new ItemName(Material.valueOf(\"CARROT_ITEM\"), langConfig.getString(\"item.carrots.name\", \"Carrot\")));\n itemNames.add(new ItemName(Material.valueOf(\"POTATO_ITEM\"), langConfig.getString(\"item.potato.name\", \"Potato\")));\n itemNames.add(new ItemName(Material.valueOf(\"BAKED_POTATO\"), langConfig.getString(\"item.potatoBaked.name\", \"Baked Potato\")));\n itemNames.add(new ItemName(Material.valueOf(\"POISONOUS_POTATO\"), langConfig.getString(\"item.potatoPoisonous.name\", \"Poisonous Potato\")));\n itemNames.add(new ItemName(Material.valueOf(\"EMPTY_MAP\"), langConfig.getString(\"item.emptyMap.name\", \"Empty Map\")));\n itemNames.add(new ItemName(Material.valueOf(\"GOLDEN_CARROT\"), langConfig.getString(\"item.carrotGolden.name\", \"Golden Carrot\")));\n itemNames.add(new ItemName(Material.valueOf(\"SKULL_ITEM\"), langConfig.getString(\"item.skull.skeleton.name\", \"Skeleton Skull\")));\n itemNames.add(new ItemName(Material.valueOf(\"SKULL_ITEM\"), 1, langConfig.getString(\"item.skull.wither.name\", \"Wither Skeleton Skull\")));\n itemNames.add(new ItemName(Material.valueOf(\"SKULL_ITEM\"), 2, langConfig.getString(\"item.skull.zombie.name\", \"Zombie Head\")));\n itemNames.add(new ItemName(Material.valueOf(\"SKULL_ITEM\"), 3, langConfig.getString(\"item.skull.char.name\", \"Head\")));\n itemNames.add(new ItemName(Material.valueOf(\"SKULL_ITEM\"), 4, langConfig.getString(\"item.skull.creeper.name\", \"Creeper Head\")));\n itemNames.add(new ItemName(Material.valueOf(\"SKULL_ITEM\"), 5, langConfig.getString(\"item.skull.dragon.name\", \"Creeper Head\")));\n itemNames.add(new ItemName(Material.valueOf(\"CARROT_STICK\"), langConfig.getString(\"item.carrotOnAStick.name\", \"Carrot on a Stick\")));\n itemNames.add(new ItemName(Material.valueOf(\"NETHER_STAR\"), langConfig.getString(\"item.netherStar.name\", \"Nether Star\")));\n itemNames.add(new ItemName(Material.valueOf(\"PUMPKIN_PIE\"), langConfig.getString(\"item.pumpkinPie.name\", \"Pumpkin Pie\")));\n itemNames.add(new ItemName(Material.valueOf(\"FIREWORK\"), langConfig.getString(\"item.fireworks.name\", \"Firework Rocket\")));\n itemNames.add(new ItemName(Material.valueOf(\"FIREWORK_CHARGE\"), langConfig.getString(\"item.fireworksCharge.name\", \"Firework Star\")));\n itemNames.add(new ItemName(Material.valueOf(\"ENCHANTED_BOOK\"), langConfig.getString(\"item.enchantedBook.name\", \"Enchanted Book\")));\n itemNames.add(new ItemName(Material.valueOf(\"REDSTONE_COMPARATOR\"), langConfig.getString(\"item.comparator.name\", \"Redstone Comparator\")));\n itemNames.add(new ItemName(Material.valueOf(\"NETHER_BRICK_ITEM\"), langConfig.getString(\"item.netherbrick.name\", \"Nether Brick\")));\n itemNames.add(new ItemName(Material.valueOf(\"QUARTZ\"), langConfig.getString(\"item.netherquartz.name\", \"Nether Quartz\")));\n itemNames.add(new ItemName(Material.valueOf(\"EXPLOSIVE_MINECART\"), langConfig.getString(\"item.minecartTnt.name\", \"Minecart with TNT\")));\n itemNames.add(new ItemName(Material.valueOf(\"HOPPER_MINECART\"), langConfig.getString(\"item.minecartHopper.name\", \"Minecart with Hopper\")));\n itemNames.add(new ItemName(Material.valueOf(\"PRISMARINE_SHARD\"), langConfig.getString(\"item.prismarineShard.name\", \"Prismarine Shard\")));\n itemNames.add(new ItemName(Material.valueOf(\"PRISMARINE_CRYSTALS\"), langConfig.getString(\"item.prismarineCrystals.name\", \"Prismarine Crystals\")));\n itemNames.add(new ItemName(Material.valueOf(\"RABBIT\"), langConfig.getString(\"item.rabbitRaw.name\", \"Raw Rabbit\")));\n itemNames.add(new ItemName(Material.valueOf(\"COOKED_RABBIT\"), langConfig.getString(\"item.rabbitCooked.name\", \"Cooked Rabbit\")));\n itemNames.add(new ItemName(Material.valueOf(\"RABBIT_STEW\"), langConfig.getString(\"item.rabbitStew.name\", \"Rabbit Stew\")));\n itemNames.add(new ItemName(Material.valueOf(\"RABBIT_FOOT\"), langConfig.getString(\"item.rabbitFoot.name\", \"Rabbit's Foot\")));\n itemNames.add(new ItemName(Material.valueOf(\"RABBIT_HIDE\"), langConfig.getString(\"item.rabbitHide.name\", \"Rabbit Hide\")));\n itemNames.add(new ItemName(Material.valueOf(\"ARMOR_STAND\"), langConfig.getString(\"item.armorStand.name\", \"Armor Stand\")));\n itemNames.add(new ItemName(Material.valueOf(\"IRON_BARDING\"), langConfig.getString(\"item.horsearmormetal.name\", \"Iron Horse Armor\")));\n itemNames.add(new ItemName(Material.valueOf(\"GOLD_BARDING\"), langConfig.getString(\"item.horsearmorgold.name\", \"Gold Horse Armor\")));\n itemNames.add(new ItemName(Material.valueOf(\"DIAMOND_BARDING\"), langConfig.getString(\"item.horsearmordiamond.name\", \"Diamond Horse Armor\")));\n itemNames.add(new ItemName(Material.valueOf(\"LEASH\"), langConfig.getString(\"item.leash.name\", \"Lead\")));\n itemNames.add(new ItemName(Material.valueOf(\"NAME_TAG\"), langConfig.getString(\"item.nameTag.name\", \"Name Tag\")));\n itemNames.add(new ItemName(Material.valueOf(\"COMMAND_MINECART\"), langConfig.getString(\"item.minecartCommandBlock.name\", \"Minecart with Command Block\")));\n itemNames.add(new ItemName(Material.valueOf(\"MUTTON\"), langConfig.getString(\"item.muttonRaw.name\", \"Raw Mutton\")));\n itemNames.add(new ItemName(Material.valueOf(\"COOKED_MUTTON\"), langConfig.getString(\"item.muttonCooked.name\", \"Cooked Mutton\")));\n itemNames.add(new ItemName(Material.valueOf(\"BANNER\"), langConfig.getString(\"item.banner.black.name\", \"Black Banner\")));\n itemNames.add(new ItemName(Material.valueOf(\"BANNER\"), 1, langConfig.getString(\"item.banner.red.name\", \"Red Banner\")));\n itemNames.add(new ItemName(Material.valueOf(\"BANNER\"), 2, langConfig.getString(\"item.banner.green.name\", \"Green Banner\")));\n itemNames.add(new ItemName(Material.valueOf(\"BANNER\"), 3, langConfig.getString(\"item.banner.brown.name\", \"Brown Banner\")));\n itemNames.add(new ItemName(Material.valueOf(\"BANNER\"), 4, langConfig.getString(\"item.banner.blue.name\", \"Blue Banner\")));\n itemNames.add(new ItemName(Material.valueOf(\"BANNER\"), 5, langConfig.getString(\"item.banner.purple.name\", \"Purple Banner\")));\n itemNames.add(new ItemName(Material.valueOf(\"BANNER\"), 6, langConfig.getString(\"item.banner.cyan.name\", \"Cyan Banner\")));\n itemNames.add(new ItemName(Material.valueOf(\"BANNER\"), 7, langConfig.getString(\"item.banner.silver.name\", \"Light Gray Banner\")));\n itemNames.add(new ItemName(Material.valueOf(\"BANNER\"), 8, langConfig.getString(\"item.banner.gray.name\", \"Gray Banner\")));\n itemNames.add(new ItemName(Material.valueOf(\"BANNER\"), 9, langConfig.getString(\"item.banner.pink.name\", \"Pink Banner\")));\n itemNames.add(new ItemName(Material.valueOf(\"BANNER\"), 10, langConfig.getString(\"item.banner.lime.name\", \"Lime Banner\")));\n itemNames.add(new ItemName(Material.valueOf(\"BANNER\"), 11, langConfig.getString(\"item.banner.yellow.name\", \"Yellow Banner\")));\n itemNames.add(new ItemName(Material.valueOf(\"BANNER\"), 12, langConfig.getString(\"item.banner.lightBlue.name\", \"Light Blue Banner\")));\n itemNames.add(new ItemName(Material.valueOf(\"BANNER\"), 13, langConfig.getString(\"item.banner.magenta.name\", \"Magenta Banner\")));\n itemNames.add(new ItemName(Material.valueOf(\"BANNER\"), 14, langConfig.getString(\"item.banner.orange.name\", \"Orange Banner\")));\n itemNames.add(new ItemName(Material.valueOf(\"BANNER\"), 15, langConfig.getString(\"item.banner.white.name\", \"White Banner\")));\n itemNames.add(new ItemName(Material.valueOf(\"SPRUCE_DOOR_ITEM\"), langConfig.getString(\"item.doorSpruce.name\", \"Spruce Door\")));\n itemNames.add(new ItemName(Material.valueOf(\"BIRCH_DOOR_ITEM\"), langConfig.getString(\"item.doorBirch.name\", \"Birch Door\")));\n itemNames.add(new ItemName(Material.valueOf(\"JUNGLE_DOOR_ITEM\"), langConfig.getString(\"item.doorJungle.name\", \"Jungle Door\")));\n itemNames.add(new ItemName(Material.valueOf(\"ACACIA_DOOR_ITEM\"), langConfig.getString(\"item.doorAcacia.name\", \"Acacia Door\")));\n itemNames.add(new ItemName(Material.valueOf(\"DARK_OAK_DOOR_ITEM\"), langConfig.getString(\"item.doorDarkOak.name\", \"Dark Oak Door\")));\n itemNames.add(new ItemName(Material.valueOf(\"GOLD_RECORD\"), langConfig.getString(\"item.record.name\", \"Music Disc\")));\n itemNames.add(new ItemName(Material.valueOf(\"GREEN_RECORD\"), langConfig.getString(\"item.record.name\", \"Music Disc\")));\n itemNames.add(new ItemName(Material.valueOf(\"RECORD_3\"), langConfig.getString(\"item.record.name\", \"Music Disc\")));\n itemNames.add(new ItemName(Material.valueOf(\"RECORD_4\"), langConfig.getString(\"item.record.name\", \"Music Disc\")));\n itemNames.add(new ItemName(Material.valueOf(\"RECORD_5\"), langConfig.getString(\"item.record.name\", \"Music Disc\")));\n itemNames.add(new ItemName(Material.valueOf(\"RECORD_6\"), langConfig.getString(\"item.record.name\", \"Music Disc\")));\n itemNames.add(new ItemName(Material.valueOf(\"RECORD_7\"), langConfig.getString(\"item.record.name\", \"Music Disc\")));\n itemNames.add(new ItemName(Material.valueOf(\"RECORD_8\"), langConfig.getString(\"item.record.name\", \"Music Disc\")));\n itemNames.add(new ItemName(Material.valueOf(\"RECORD_9\"), langConfig.getString(\"item.record.name\", \"Music Disc\")));\n itemNames.add(new ItemName(Material.valueOf(\"RECORD_10\"), langConfig.getString(\"item.record.name\", \"Music Disc\")));\n itemNames.add(new ItemName(Material.valueOf(\"RECORD_11\"), langConfig.getString(\"item.record.name\", \"Music Disc\")));\n itemNames.add(new ItemName(Material.valueOf(\"RECORD_12\"), langConfig.getString(\"item.record.name\", \"Music Disc\")));\n\n if (Utils.getMajorVersion() >= 9) {\n // Add Item names of 1.9\n itemNames.add(new ItemName(Material.valueOf(\"END_CRYSTAL\"), langConfig.getString(\"item.end_crystal.name\", \"End Crystal\")));\n itemNames.add(new ItemName(Material.valueOf(\"CHORUS_FRUIT\"), langConfig.getString(\"item.chorusFruit.name\", \"Chorus Fruit\")));\n itemNames.add(new ItemName(Material.valueOf(\"CHORUS_FRUIT_POPPED\"), langConfig.getString(\"item.chorusFruitPopped.name\", \"Popped Chorus Fruit\")));\n itemNames.add(new ItemName(Material.valueOf(\"BEETROOT\"), langConfig.getString(\"item.beetroot.name\", \"Beetroot\")));\n itemNames.add(new ItemName(Material.valueOf(\"BEETROOT_SEEDS\"), langConfig.getString(\"item.beetroot_seeds.name\", \"Beetroot Seeds\")));\n itemNames.add(new ItemName(Material.valueOf(\"BEETROOT_SOUP\"), langConfig.getString(\"item.beetroot_soup.name\", \"Beetroot Soup\")));\n itemNames.add(new ItemName(Material.valueOf(\"DRAGONS_BREATH\"), langConfig.getString(\"item.dragon_breath.name\", \"Dragon's Breath\")));\n itemNames.add(new ItemName(Material.valueOf(\"SPECTRAL_ARROW\"), langConfig.getString(\"item.spectral_arrow.name\", \"Spectral Arrow\")));\n itemNames.add(new ItemName(Material.valueOf(\"TIPPED_ARROW\"), langConfig.getString(\"item.tipped_arrow.name\", \"Tipped Arrow\")));\n itemNames.add(new ItemName(Material.valueOf(\"SHIELD\"), langConfig.getString(\"item.shield.name\", \"Shield\")));\n itemNames.add(new ItemName(Material.valueOf(\"ELYTRA\"), langConfig.getString(\"item.elytra.name\", \"Elytra\")));\n itemNames.add(new ItemName(Material.valueOf(\"BOAT_SPRUCE\"), langConfig.getString(\"item.boat.spruce.name\", \"Spruce Boat\")));\n itemNames.add(new ItemName(Material.valueOf(\"BOAT_BIRCH\"), langConfig.getString(\"item.boat.birch.name\", \"Birch Boat\")));\n itemNames.add(new ItemName(Material.valueOf(\"BOAT_JUNGLE\"), langConfig.getString(\"item.boat.jungle.name\", \"Jungle Boat\")));\n itemNames.add(new ItemName(Material.valueOf(\"BOAT_ACACIA\"), langConfig.getString(\"item.boat.acacia.name\", \"Acacia Boat\")));\n itemNames.add(new ItemName(Material.valueOf(\"BOAT_DARK_OAK\"), langConfig.getString(\"item.boat.dark_oak.name\", \"Dark Oak Boat\")));\n }\n\n if (Utils.getMajorVersion() >= 11) {\n // Add Item Names of 1.11\n itemNames.add(new ItemName(Material.valueOf(\"TOTEM\"), langConfig.getString(\"item.totem.name\", \"Totem of Undying\")));\n itemNames.add(new ItemName(Material.valueOf(\"SHULKER_SHELL\"), langConfig.getString(\"item.shulkerShell.name\", \"Shulker Shell\")));\n\n if (Utils.getRevision() >= 2 || Utils.getMajorVersion() > 11) {\n // Add Item Name of 1.11.2\n itemNames.add(new ItemName(Material.valueOf(\"IRON_NUGGET\"), langConfig.getString(\"item.ironNugget.name\", \"Iron Nugget\")));\n }\n }\n\n if (Utils.getMajorVersion() >= 12) {\n // Add Item Name of 1.12\n itemNames.add(new ItemName(Material.valueOf(\"KNOWLEDGE_BOOK\"), langConfig.getString(\"item.knowledgeBook.name\", \"Knowledge Book\")));\n itemNames.add(new ItemName(Material.valueOf(\"BED\"), langConfig.getString(\"item.bed.white.name\", \"White Bed\")));\n itemNames.add(new ItemName(Material.valueOf(\"BED\"), 1, langConfig.getString(\"item.bed.orange.name\", \"Orange Bed\")));\n itemNames.add(new ItemName(Material.valueOf(\"BED\"), 2, langConfig.getString(\"item.bed.magenta.name\", \"Magenta Bed\")));\n itemNames.add(new ItemName(Material.valueOf(\"BED\"), 3, langConfig.getString(\"item.bed.lightBlue.name\", \"Light Blue Bed\")));\n itemNames.add(new ItemName(Material.valueOf(\"BED\"), 4, langConfig.getString(\"item.bed.yellow.name\", \"Yellow Bed\")));\n itemNames.add(new ItemName(Material.valueOf(\"BED\"), 5, langConfig.getString(\"item.bed.lime.name\", \"Lime Bed\")));\n itemNames.add(new ItemName(Material.valueOf(\"BED\"), 6, langConfig.getString(\"item.bed.pink.name\", \"Pink Bed\")));\n itemNames.add(new ItemName(Material.valueOf(\"BED\"), 7, langConfig.getString(\"item.bed.gray.name\", \"Gray Bed\")));\n itemNames.add(new ItemName(Material.valueOf(\"BED\"), 8, langConfig.getString(\"item.bed.silver.name\", \"Light Gray Bed\")));\n itemNames.add(new ItemName(Material.valueOf(\"BED\"), 9, langConfig.getString(\"item.bed.cyan.name\", \"Cyan Bed\")));\n itemNames.add(new ItemName(Material.valueOf(\"BED\"), 10, langConfig.getString(\"item.bed.purple.name\", \"Purple Bed\")));\n itemNames.add(new ItemName(Material.valueOf(\"BED\"), 11, langConfig.getString(\"item.bed.blue.name\", \"Blue Bed\")));\n itemNames.add(new ItemName(Material.valueOf(\"BED\"), 12, langConfig.getString(\"item.bed.brown.name\", \"Brown Bed\")));\n itemNames.add(new ItemName(Material.valueOf(\"BED\"), 13, langConfig.getString(\"item.bed.green.name\", \"Green Bed\")));\n itemNames.add(new ItemName(Material.valueOf(\"BED\"), 14, langConfig.getString(\"item.bed.red.name\", \"Red Bed\")));\n itemNames.add(new ItemName(Material.valueOf(\"BED\"), 15, langConfig.getString(\"item.bed.black.name\", \"Black Bed\")));\n } else {\n // Before 1.12, bed is just called \"Bed\" without colors\n itemNames.add(new ItemName(Material.valueOf(\"BED\"), langConfig.getString(\"item.bed.name\", \"Bed\")));\n }\n\n // Add Enchantment Names\n enchantmentNames.add(new EnchantmentName(Enchantment.ARROW_DAMAGE, langConfig.getString(\"enchantment.arrowDamage\", \"Power\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.ARROW_FIRE, langConfig.getString(\"enchantment.arrowFire\", \"Flame\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.ARROW_INFINITE, langConfig.getString(\"enchantment.arrowInfinite\", \"Infinity\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.ARROW_KNOCKBACK, langConfig.getString(\"enchantment.arrowKnockback\", \"Punch\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.DAMAGE_ALL, langConfig.getString(\"enchantment.damage.all\", \"Sharpness\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.DAMAGE_ARTHROPODS, langConfig.getString(\"enchantment.damage.arthropods\", \"Bane of Arthropods\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.DAMAGE_UNDEAD, langConfig.getString(\"enchantment.damage.undead\", \"Smite\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.DIG_SPEED, langConfig.getString(\"enchantment.digging\", \"Efficiency\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.DURABILITY, langConfig.getString(\"enchantment.durability\", \"Unbreaking\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.FIRE_ASPECT, langConfig.getString(\"enchantment.fire\", \"Fire Aspect\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.LURE, langConfig.getString(\"enchantment.fishingSpeed\", \"Lure\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.KNOCKBACK, langConfig.getString(\"enchantment.knockback\", \"Knockback\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.LOOT_BONUS_MOBS, langConfig.getString(\"enchantment.lootBonus\", \"Looting\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.LOOT_BONUS_BLOCKS, langConfig.getString(\"enchantment.lootBonusDigger\", \"Fortune\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.LUCK, langConfig.getString(\"enchantment.lootBonusFishing\", \"Luck of the Sea\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.OXYGEN, langConfig.getString(\"enchantment.oxygen\", \"Respiration\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.PROTECTION_ENVIRONMENTAL, langConfig.getString(\"enchantment.protect.all\", \"Protection\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.PROTECTION_EXPLOSIONS, langConfig.getString(\"enchantment.protect.explosion\", \"Blast Protection\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.PROTECTION_FALL, langConfig.getString(\"enchantment.protect.fall\", \"Feather Falling\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.PROTECTION_FIRE, langConfig.getString(\"enchantment.protect.fire\", \"Fire Protection\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.PROTECTION_PROJECTILE, langConfig.getString(\"enchantment.protect.projectile\", \"Projectile Protection\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.THORNS, langConfig.getString(\"enchantment.thorns\", \"Thorns\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.SILK_TOUCH, langConfig.getString(\"enchantment.untouching\", \"Silk Touch\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.DEPTH_STRIDER, langConfig.getString(\"enchantment.waterWalker\", \"Depth Strider\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.WATER_WORKER, langConfig.getString(\"enchantment.waterWorker\", \"Aqua Affinity\")));\n\n if (Utils.getMajorVersion() >= 9) {\n // Add Enchantment Names of 1.9\n enchantmentNames.add(new EnchantmentName(Enchantment.FROST_WALKER, langConfig.getString(\"enchantment.frostWalker\", \"Frost Walker\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.MENDING, langConfig.getString(\"enchantment.mending\", \"Mending\")));\n }\n\n if (Utils.getMajorVersion() >= 11) {\n // Add Enchantment Names of 1.11\n enchantmentNames.add(new EnchantmentName(Enchantment.BINDING_CURSE, langConfig.getString(\"enchantment.binding_curse\", \"Curse of Binding\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.VANISHING_CURSE, langConfig.getString(\"enchantment.vanishing_curse\", \"Curse of Vanishing\")));\n\n if (Utils.getRevision() >= 2 || Utils.getMajorVersion() > 11) {\n // Add Enchantment Name of 1.11.2\n enchantmentNames.add(new EnchantmentName(Enchantment.SWEEPING_EDGE, langConfig.getString(\"enchantment.sweeping\", \"Sweeping Edge\")));\n }\n }\n\n // Add Enchantment Level Names\n enchantmentLevelNames.add(new EnchantmentName.EnchantmentLevelName(1, langConfig.getString(\"enchantment.level.1\", \"I\")));\n enchantmentLevelNames.add(new EnchantmentName.EnchantmentLevelName(2, langConfig.getString(\"enchantment.level.2\", \"II\")));\n enchantmentLevelNames.add(new EnchantmentName.EnchantmentLevelName(3, langConfig.getString(\"enchantment.level.3\", \"II\")));\n enchantmentLevelNames.add(new EnchantmentName.EnchantmentLevelName(4, langConfig.getString(\"enchantment.level.4\", \"IV\")));\n enchantmentLevelNames.add(new EnchantmentName.EnchantmentLevelName(5, langConfig.getString(\"enchantment.level.5\", \"V\")));\n enchantmentLevelNames.add(new EnchantmentName.EnchantmentLevelName(6, langConfig.getString(\"enchantment.level.6\", \"VI\")));\n enchantmentLevelNames.add(new EnchantmentName.EnchantmentLevelName(7, langConfig.getString(\"enchantment.level.7\", \"VII\")));\n enchantmentLevelNames.add(new EnchantmentName.EnchantmentLevelName(8, langConfig.getString(\"enchantment.level.8\", \"VIII\")));\n enchantmentLevelNames.add(new EnchantmentName.EnchantmentLevelName(9, langConfig.getString(\"enchantment.level.9\", \"IX\")));\n enchantmentLevelNames.add(new EnchantmentName.EnchantmentLevelName(10, langConfig.getString(\"enchantment.level.10\", \"X\")));\n\n // Add Entity Names\n String horseName = (Utils.getMajorVersion() >= 11 ? \"entity.Horse.name\" : \"entity.EntityHorse.name\");\n entityNames.add(new EntityName(EntityType.CREEPER, langConfig.getString(\"entity.Creeper.name\", \"Creeper\")));\n entityNames.add(new EntityName(EntityType.SKELETON, langConfig.getString(\"entity.Skeleton.name\", \"Skeleton\")));\n entityNames.add(new EntityName(EntityType.SPIDER, langConfig.getString(\"entity.Spider.name\", \"Spider\")));\n entityNames.add(new EntityName(EntityType.ZOMBIE, langConfig.getString(\"entity.Zombie.name\", \"Zombie\")));\n entityNames.add(new EntityName(EntityType.SLIME, langConfig.getString(\"entity.Slime.name\", \"Slime\")));\n entityNames.add(new EntityName(EntityType.GHAST, langConfig.getString(\"entity.Ghast.name\", \"Ghast\")));\n entityNames.add(new EntityName(EntityType.valueOf(\"PIG_ZOMBIE\"), langConfig.getString(\"entity.PigZombie.name\", \"Zombie Pigman\")));\n entityNames.add(new EntityName(EntityType.ENDERMAN, langConfig.getString(\"entity.Enderman.name\", \"Enderman\")));\n entityNames.add(new EntityName(EntityType.CAVE_SPIDER, langConfig.getString(\"entity.CaveSpider.name\", \"Cave Spider\")));\n entityNames.add(new EntityName(EntityType.SILVERFISH, langConfig.getString(\"entity.Silverfish.name\", \"Silverfish\")));\n entityNames.add(new EntityName(EntityType.BLAZE, langConfig.getString(\"entity.Blaze.name\", \"Blaze\")));\n entityNames.add(new EntityName(EntityType.MAGMA_CUBE, langConfig.getString(\"entity.LavaSlime.name\", \"Magma Cube\")));\n entityNames.add(new EntityName(EntityType.BAT, langConfig.getString(\"entity.Bat.name\", \"Bat\")));\n entityNames.add(new EntityName(EntityType.WITCH, langConfig.getString(\"entity.Witch.name\", \"Witch\")));\n entityNames.add(new EntityName(EntityType.ENDERMITE, langConfig.getString(\"entity.Endermite.name\", \"Endermite\")));\n entityNames.add(new EntityName(EntityType.GUARDIAN, langConfig.getString(\"entity.Guardian.name\", \"Guardian\")));\n entityNames.add(new EntityName(EntityType.PIG, langConfig.getString(\"entity.Pig.name\", \"Pig\")));\n entityNames.add(new EntityName(EntityType.SHEEP, langConfig.getString(\"entity.Sheep.name\", \"Sheep\")));\n entityNames.add(new EntityName(EntityType.COW, langConfig.getString(\"entity.Cow.name\", \"Cow\")));\n entityNames.add(new EntityName(EntityType.CHICKEN, langConfig.getString(\"entity.Chicken.name\", \"Chicken\")));\n entityNames.add(new EntityName(EntityType.SQUID, langConfig.getString(\"entity.Squid.name\", \"Squid\")));\n entityNames.add(new EntityName(EntityType.WOLF, langConfig.getString(\"entity.Wolf.name\", \"Wolf\")));\n entityNames.add(new EntityName(EntityType.MUSHROOM_COW, langConfig.getString(\"entity.MushroomCow.name\", \"Mooshroom\")));\n entityNames.add(new EntityName(EntityType.OCELOT, langConfig.getString(\"entity.Ozelot.name\", \"Ocelot\")));\n entityNames.add(new EntityName(EntityType.HORSE, langConfig.getString(horseName, \"Horse\")));\n entityNames.add(new EntityName(EntityType.RABBIT, langConfig.getString(\"entity.Rabbit.name\", \"Rabbit\")));\n entityNames.add(new EntityName(EntityType.VILLAGER, langConfig.getString(\"entity.Villager.name\", \"Villager\")));\n\n if (Utils.getMajorVersion() >= 9) {\n // Add Entity Names of 1.9\n entityNames.add(new EntityName(EntityType.SHULKER, langConfig.getString(\"entity.Shulker.name\", \"Shulker\")));\n }\n\n if (Utils.getMajorVersion() >= 10) {\n // Add Entity Names of 1.10\n entityNames.add(new EntityName(EntityType.POLAR_BEAR, langConfig.getString(\"entity.PolarBear.name\", \"Polar Bear\")));\n }\n\n if (Utils.getMajorVersion() >= 11) {\n // Add Entity Names of 1.11\n entityNames.add(new EntityName(EntityType.ZOMBIE_VILLAGER, langConfig.getString(\"entity.ZombieVillager.name\", \"Zombie Villager\")));\n entityNames.add(new EntityName(EntityType.ELDER_GUARDIAN, langConfig.getString(\"entity.ElderGuardian.name\", \"Elder Guardian\")));\n entityNames.add(new EntityName(EntityType.EVOKER, langConfig.getString(\"entity.EvocationIllager.name\", \"Evoker\")));\n entityNames.add(new EntityName(EntityType.VEX, langConfig.getString(\"entity.Vex.name\", \"Vex\")));\n entityNames.add(new EntityName(EntityType.VINDICATOR, langConfig.getString(\"entity.VindicationIllager.name\", \"Vindicator\")));\n entityNames.add(new EntityName(EntityType.LLAMA, langConfig.getString(\"entity.Llama.name\", \"Llama\")));\n entityNames.add(new EntityName(EntityType.WITHER_SKELETON, langConfig.getString(\"entity.WitherSkeleton.name\", \"Wither Skeleton\")));\n entityNames.add(new EntityName(EntityType.STRAY, langConfig.getString(\"entity.Stray.name\", \"Stray\")));\n entityNames.add(new EntityName(EntityType.ZOMBIE_HORSE, langConfig.getString(\"entity.ZombieHorse.name\", \"Zombie Horse\")));\n entityNames.add(new EntityName(EntityType.SKELETON_HORSE, langConfig.getString(\"entity.SkeletonHorse.name\", \"Skeleton Horse\")));\n entityNames.add(new EntityName(EntityType.DONKEY, langConfig.getString(\"entity.Donkey.name\", \"Donkey\")));\n entityNames.add(new EntityName(EntityType.MULE, langConfig.getString(\"entity.Mule.name\", \"Mule\")));\n entityNames.add(new EntityName(EntityType.HUSK, langConfig.getString(\"entity.Husk.name\", \"Husk\")));\n }\n\n if (Utils.getMajorVersion() >= 12) {\n // Add Entity Names of 1.12\n entityNames.add(new EntityName(EntityType.PARROT, langConfig.getString(\"entity.Parrot.name\", \"Parrot\")));\n entityNames.add(new EntityName(EntityType.ILLUSIONER, langConfig.getString(\"entity.IllusionIllager.name\", \"Illusioner\")));\n }\n\n // Add Potion Effect Names\n potionEffectNames.add(new PotionEffectName(PotionEffectType.FIRE_RESISTANCE, langConfig.getString(\"effect.fireResistance\", \"Fire Resistance\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.HARM, langConfig.getString(\"effect.harm\", \"Instant Damage\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.HEAL, langConfig.getString(\"effect.heal\", \"Instant Health\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.INVISIBILITY, langConfig.getString(\"effect.invisibility\", \"Invisibility\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.JUMP, langConfig.getString(\"effect.jump\", \"Jump Boost\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.NIGHT_VISION, langConfig.getString(\"effect.nightVision\", \"Night Vision\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.POISON, langConfig.getString(\"effect.poison\", \"Poison\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.REGENERATION, langConfig.getString(\"effect.regeneration\", \"Regeneration\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.SLOW, langConfig.getString(\"effect.moveSlowdown\", \"Slowness\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.SPEED, langConfig.getString(\"effect.moveSpeed\", \"Speed\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.INCREASE_DAMAGE, langConfig.getString(\"effect.damageBoost\", \"Strength\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.WATER_BREATHING, langConfig.getString(\"effect.waterBreathing\", \"Water Breathing\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.WEAKNESS, langConfig.getString(\"effect.weakness\", \"Weakness\")));\n\n if (Utils.getMajorVersion() >= 9) {\n // Add Potion Effect Names of 1.9\n potionEffectNames.add(new PotionEffectName(PotionEffectType.LUCK, langConfig.getString(\"effect.luck\", \"Luck\")));\n }\n\n // Add Potion Names\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.FIRE_RESISTANCE, langConfig.getString(\"potion.effect.fire_resistance\", \"Potion of Fire Resistance\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.INSTANT_DAMAGE, langConfig.getString(\"potion.effect.harming\", \"Potion of Harming\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.INSTANT_HEAL, langConfig.getString(\"potion.effect.healing\", \"Potion of Healing\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.INVISIBILITY, langConfig.getString(\"potion.effect.invisibility\", \"Potion of Invisibility\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.JUMP, langConfig.getString(\"potion.effect.leaping\", \"Potion of Leaping\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.NIGHT_VISION, langConfig.getString(\"potion.effect.night_vision\", \"Potion of Night Vision\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.POISON, langConfig.getString(\"potion.effect.poison\", \"Potion of Poison\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.REGEN, langConfig.getString(\"potion.effect.regeneration\", \"Potion of Regeneration\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.SLOWNESS, langConfig.getString(\"potion.effect.slowness\", \"Potion of Slowness\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.SPEED, langConfig.getString(\"potion.effect.swiftness\", \"Potion of Swiftness\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.STRENGTH, langConfig.getString(\"potion.effect.strength\", \"Potion of Strength\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.WATER_BREATHING, langConfig.getString(\"potion.effect.water_breathing\", \"Potion of Water Breathing\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.WEAKNESS, langConfig.getString(\"potion.effect.weakness\", \"Potion of Weakness\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.WATER, langConfig.getString(\"potion.effect.water\", \"Water Bottle\")));\n\n if (Utils.getMajorVersion() >= 9) {\n // Add Potion Names of 1.9\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.AWKWARD, langConfig.getString(\"potion.effect.awkward\", \"Awkward Potion\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.LUCK, langConfig.getString(\"potion.effect.luck\", \"Potion of Luck\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.MUNDANE, langConfig.getString(\"potion.effect.mundane\", \"Mundane Potion\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.THICK, langConfig.getString(\"potion.effect.thick\", \"Thick Potion\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.UNCRAFTABLE, langConfig.getString(\"potion.effect.empty\", \"Uncraftable Potion\")));\n }\n\n if (Utils.getMajorVersion() >= 9) {\n // Add Tipped Arrow Names (implemented in Minecraft since 1.9)\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.AWKWARD, langConfig.getString(\"tipped_arrow.effect.awkward\", \"Tipped Arrow\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.FIRE_RESISTANCE, langConfig.getString(\"tipped_arrow.effect.fire_resistance\", \"Arrow of Fire Resistance\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.INSTANT_DAMAGE, langConfig.getString(\"tipped_arrow.effect.harming\", \"Arrow of Harming\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.INSTANT_HEAL, langConfig.getString(\"tipped_arrow.effect.healing\", \"Arrow of Healing\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.INVISIBILITY, langConfig.getString(\"tipped_arrow.effect.invisibility\", \"Arrow of Invisibility\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.JUMP, langConfig.getString(\"tipped_arrow.effect.leaping\", \"Arrow of Leaping\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.NIGHT_VISION, langConfig.getString(\"tipped_arrow.effect.night_vision\", \"Arrow of Night Vision\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.POISON, langConfig.getString(\"tipped_arrow.effect.poison\", \"Arrow of Poison\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.REGEN, langConfig.getString(\"tipped_arrow.effect.regeneration\", \"Arrow of Regeneration\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.SLOWNESS, langConfig.getString(\"tipped_arrow.effect.slowness\", \"Arrow of Slowness\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.SPEED, langConfig.getString(\"tipped_arrow.effect.swiftness\", \"Arrow of Swiftness\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.STRENGTH, langConfig.getString(\"tipped_arrow.effect.strength\", \"Arrow of Strength\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.WATER_BREATHING, langConfig.getString(\"tipped_arrow.effect.water_breathing\", \"Arrow of Water Breathing\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.WEAKNESS, langConfig.getString(\"tipped_arrow.effect.weakness\", \"Arrow of Weakness\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.WATER, langConfig.getString(\"tipped_arrow.effect.water\", \"Arrow of Splashing\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.LUCK, langConfig.getString(\"tipped_arrow.effect.luck\", \"Arrow of Luck\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.MUNDANE, langConfig.getString(\"tipped_arrow.effect.mundane\", \"Tipped Arrow\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.THICK, langConfig.getString(\"tipped_arrow.effect.thick\", \"Tipped Arrow\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.UNCRAFTABLE, langConfig.getString(\"tipped_arrow.effect.empty\", \"Uncraftable Tipped Arrow\")));\n }\n\n // Add Splash Potion Names\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.FIRE_RESISTANCE, langConfig.getString(\"splash_potion.effect.fire_resistance\", \"Splash Potion of Fire Resistance\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.INSTANT_DAMAGE, langConfig.getString(\"splash_potion.effect.harming\", \"Splash Potion of Harming\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.INSTANT_HEAL, langConfig.getString(\"splash_potion.effect.healing\", \"Splash Potion of Healing\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.INVISIBILITY, langConfig.getString(\"splash_potion.effect.invisibility\", \"Splash Potion of Invisibility\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.JUMP, langConfig.getString(\"splash_potion.effect.leaping\", \"Splash Potion of Leaping\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.NIGHT_VISION, langConfig.getString(\"splash_potion.effect.night_vision\", \"Splash Potion of Night Vision\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.POISON, langConfig.getString(\"splash_potion.effect.poison\", \"Splash Potion of Poison\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.REGEN, langConfig.getString(\"splash_potion.effect.regeneration\", \"Splash Potion of Regeneration\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.SLOWNESS, langConfig.getString(\"splash_potion.effect.slowness\", \"Splash Potion of Slowness\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.SPEED, langConfig.getString(\"splash_potion.effect.swiftness\", \"Splash Potion of Swiftness\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.STRENGTH, langConfig.getString(\"splash_potion.effect.strength\", \"Splash Potion of Strength\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.WATER_BREATHING, langConfig.getString(\"splash_potion.effect.water_breathing\", \"Splash Potion of Water Breathing\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.WEAKNESS, langConfig.getString(\"splash_potion.effect.weakness\", \"Splash Potion of Weakness\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.WATER, langConfig.getString(\"splash_potion.effect.water\", \"Splash Water Bottle\")));\n\n if (Utils.getMajorVersion() >= 9) {\n // Add Splash Potion Names of 1.9\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.AWKWARD, langConfig.getString(\"splash_potion.effect.awkward\", \"Awkward Splash Potion\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.LUCK, langConfig.getString(\"splash_potion.effect.luck\", \"Splash Potion of Luck\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.MUNDANE, langConfig.getString(\"splash_potion.effect.mundane\", \"Mundane Splash Potion\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.THICK, langConfig.getString(\"splash_potion.effect.thick\", \"Thick Splash Potion\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.UNCRAFTABLE, langConfig.getString(\"splash_potion.effect.empty\", \"Splash Uncraftable Potion\")));\n }\n\n if (Utils.getMajorVersion() >= 9) {\n // Add Lingering Potion Names (implemented in Minecraft since 1.9)\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.AWKWARD, langConfig.getString(\"lingering_potion.effect.awkward\", \"Awkward Lingering Potion\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.FIRE_RESISTANCE, langConfig.getString(\"lingering_potion.effect.fire_resistance\", \"Lingering Potion of Fire Resistance\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.INSTANT_DAMAGE, langConfig.getString(\"lingering_potion.effect.harming\", \"Lingering Potion of Harming\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.INSTANT_HEAL, langConfig.getString(\"lingering_potion.effect.healing\", \"Lingering Potion of Healing\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.INVISIBILITY, langConfig.getString(\"lingering_potion.effect.invisibility\", \"Lingering Potion of Invisibility\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.JUMP, langConfig.getString(\"lingering_potion.effect.leaping\", \"Lingering Potion of Leaping\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.NIGHT_VISION, langConfig.getString(\"lingering_potion.effect.night_vision\", \"Lingering Potion of Night Vision\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.POISON, langConfig.getString(\"lingering_potion.effect.poison\", \"Lingering Potion of Poison\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.REGEN, langConfig.getString(\"lingering_potion.effect.regeneration\", \"Lingering Potion of Regeneration\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.SLOWNESS, langConfig.getString(\"lingering_potion.effect.slowness\", \"Lingering Potion of Slowness\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.SPEED, langConfig.getString(\"lingering_potion.effect.swiftness\", \"Lingering Potion of Swiftness\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.STRENGTH, langConfig.getString(\"lingering_potion.effect.strength\", \"Lingering Potion of Strength\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.WATER_BREATHING, langConfig.getString(\"lingering_potion.effect.water_breathing\", \"Lingering Potion of Water Breathing\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.WEAKNESS, langConfig.getString(\"lingering_potion.effect.weakness\", \"Lingering Potion of Weakness\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.WATER, langConfig.getString(\"lingering_potion.effect.water\", \"Lingering Water Bottle\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.LUCK, langConfig.getString(\"lingering_potion.effect.luck\", \"Lingering Potion of Luck\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.MUNDANE, langConfig.getString(\"lingering_potion.effect.mundane\", \"Mundane Lingering Potion\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.THICK, langConfig.getString(\"lingering_potion.effect.thick\", \"Thick Lingering Potion\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.UNCRAFTABLE, langConfig.getString(\"lingering_potion.effect.empty\", \"Lingering Uncraftable Potion\")));\n }\n\n // Add Music Disc Titles\n musicDiscNames.add(new MusicDiscName(Material.valueOf(\"GOLD_RECORD\"), langConfig.getString(\"item.record.13.desc\", \"C418 - 13\")));\n musicDiscNames.add(new MusicDiscName(Material.valueOf(\"GREEN_RECORD\"), langConfig.getString(\"item.record.cat.desc\", \"C418 - cat\")));\n musicDiscNames.add(new MusicDiscName(Material.valueOf(\"RECORD_3\"), langConfig.getString(\"item.record.blocks.desc\", \"C418 - blocks\")));\n musicDiscNames.add(new MusicDiscName(Material.valueOf(\"RECORD_4\"), langConfig.getString(\"item.record.chirp.desc\", \"C418 - chirp\")));\n musicDiscNames.add(new MusicDiscName(Material.valueOf(\"RECORD_5\"), langConfig.getString(\"item.record.far.desc\", \"C418 - far\")));\n musicDiscNames.add(new MusicDiscName(Material.valueOf(\"RECORD_6\"), langConfig.getString(\"item.record.mall.desc\", \"C418 - mall\")));\n musicDiscNames.add(new MusicDiscName(Material.valueOf(\"RECORD_7\"), langConfig.getString(\"item.record.mellohi.desc\", \"C418 - mellohi\")));\n musicDiscNames.add(new MusicDiscName(Material.valueOf(\"RECORD_8\"), langConfig.getString(\"item.record.stal.desc\", \"C418 - stal\")));\n musicDiscNames.add(new MusicDiscName(Material.valueOf(\"RECORD_9\"), langConfig.getString(\"item.record.strad.desc\", \"C418 - strad\")));\n musicDiscNames.add(new MusicDiscName(Material.valueOf(\"RECORD_10\"), langConfig.getString(\"item.record.ward.desc\", \"C418 - ward\")));\n musicDiscNames.add(new MusicDiscName(Material.valueOf(\"RECORD_11\"), langConfig.getString(\"item.record.11.desc\", \"C418 - 11\")));\n musicDiscNames.add(new MusicDiscName(Material.valueOf(\"RECORD_12\"), langConfig.getString(\"item.record.wait.desc\", \"C418 - wait\")));\n\n // Add Book Generation Names\n generationNames.add(new BookGenerationName(CustomBookMeta.Generation.ORIGINAL, langConfig.getString(\"book.generation.0\", \"Original\")));\n generationNames.add(new BookGenerationName(CustomBookMeta.Generation.COPY_OF_ORIGINAL, langConfig.getString(\"book.generation.1\", \"Copy of original\")));\n generationNames.add(new BookGenerationName(CustomBookMeta.Generation.COPY_OF_COPY, langConfig.getString(\"book.generation.2\", \"Copy of a copy\")));\n generationNames.add(new BookGenerationName(CustomBookMeta.Generation.TATTERED, langConfig.getString(\"book.generation.3\", \"Tattered\")));\n\n loadMessages();\n }\n\n public static void load() {\n langConfig = Config.langConfig;\n\n itemNames.clear();\n enchantmentNames.clear();\n enchantmentLevelNames.clear();\n potionEffectNames.clear();\n entityNames.clear();\n potionNames.clear();\n musicDiscNames.clear();\n generationNames.clear();\n messages.clear();\n\n if (Utils.getMajorVersion() < 13) {\n loadLegacy();\n return;\n }\n\n // Add Block/Item Names\n itemNames.add(new ItemName(Material.AIR, langConfig.getString(\"block.minecraft.air\", \"Air\")));\n itemNames.add(new ItemName(Material.BARRIER, langConfig.getString(\"block.minecraft.barrier\", \"Barrier\")));\n itemNames.add(new ItemName(Material.STONE, langConfig.getString(\"block.minecraft.stone\", \"Stone\")));\n itemNames.add(new ItemName(Material.GRANITE, langConfig.getString(\"block.minecraft.granite\", \"Granite\")));\n itemNames.add(new ItemName(Material.POLISHED_GRANITE, langConfig.getString(\"block.minecraft.polished_granite\", \"Polished Granite\")));\n itemNames.add(new ItemName(Material.DIORITE, langConfig.getString(\"block.minecraft.diorite\", \"Diorite\")));\n itemNames.add(new ItemName(Material.POLISHED_DIORITE, langConfig.getString(\"block.minecraft.polished_diorite\", \"Polished Diorite\")));\n itemNames.add(new ItemName(Material.ANDESITE, langConfig.getString(\"block.minecraft.andesite\", \"Andesite\")));\n itemNames.add(new ItemName(Material.POLISHED_ANDESITE, langConfig.getString(\"block.minecraft.polished_andesite\", \"Polished Andesite\")));\n itemNames.add(new ItemName(Material.HAY_BLOCK, langConfig.getString(\"block.minecraft.hay_block\", \"Hay Bale\")));\n itemNames.add(new ItemName(Material.GRASS_BLOCK, langConfig.getString(\"block.minecraft.grass_block\", \"Grass Block\")));\n itemNames.add(new ItemName(Material.DIRT, langConfig.getString(\"block.minecraft.dirt\", \"Dirt\")));\n itemNames.add(new ItemName(Material.COARSE_DIRT, langConfig.getString(\"block.minecraft.coarse_dirt\", \"Coarse Dirt\")));\n itemNames.add(new ItemName(Material.PODZOL, langConfig.getString(\"block.minecraft.podzol\", \"Podzol\")));\n itemNames.add(new ItemName(Material.COBBLESTONE, langConfig.getString(\"block.minecraft.cobblestone\", \"Cobblestone\")));\n itemNames.add(new ItemName(Material.OAK_PLANKS, langConfig.getString(\"block.minecraft.oak_planks\", \"Oak Planks\")));\n itemNames.add(new ItemName(Material.SPRUCE_PLANKS, langConfig.getString(\"block.minecraft.spruce_planks\", \"Spruce Planks\")));\n itemNames.add(new ItemName(Material.BIRCH_PLANKS, langConfig.getString(\"block.minecraft.birch_planks\", \"Birch Planks\")));\n itemNames.add(new ItemName(Material.JUNGLE_PLANKS, langConfig.getString(\"block.minecraft.jungle_planks\", \"Jungle Planks\")));\n itemNames.add(new ItemName(Material.ACACIA_PLANKS, langConfig.getString(\"block.minecraft.acacia_planks\", \"Acacia Planks\")));\n itemNames.add(new ItemName(Material.DARK_OAK_PLANKS, langConfig.getString(\"block.minecraft.dark_oak_planks\", \"Dark Oak Planks\")));\n itemNames.add(new ItemName(Material.OAK_SAPLING, langConfig.getString(\"block.minecraft.oak_sapling\", \"Oak Sapling\")));\n itemNames.add(new ItemName(Material.SPRUCE_SAPLING, langConfig.getString(\"block.minecraft.spruce_sapling\", \"Spruce Sapling\")));\n itemNames.add(new ItemName(Material.BIRCH_SAPLING, langConfig.getString(\"block.minecraft.birch_sapling\", \"Birch Sapling\")));\n itemNames.add(new ItemName(Material.JUNGLE_SAPLING, langConfig.getString(\"block.minecraft.jungle_sapling\", \"Jungle Sapling\")));\n itemNames.add(new ItemName(Material.ACACIA_SAPLING, langConfig.getString(\"block.minecraft.acacia_sapling\", \"Acacia Sapling\")));\n itemNames.add(new ItemName(Material.DARK_OAK_SAPLING, langConfig.getString(\"block.minecraft.dark_oak_sapling\", \"Dark Oak Sapling\")));\n itemNames.add(new ItemName(Material.OAK_DOOR, langConfig.getString(\"block.minecraft.oak_door\", \"Oak Door\")));\n itemNames.add(new ItemName(Material.SPRUCE_DOOR, langConfig.getString(\"block.minecraft.spruce_door\", \"Spruce Door\")));\n itemNames.add(new ItemName(Material.BIRCH_DOOR, langConfig.getString(\"block.minecraft.birch_door\", \"Birch Door\")));\n itemNames.add(new ItemName(Material.JUNGLE_DOOR, langConfig.getString(\"block.minecraft.jungle_door\", \"Jungle Door\")));\n itemNames.add(new ItemName(Material.ACACIA_DOOR, langConfig.getString(\"block.minecraft.acacia_door\", \"Acacia Door\")));\n itemNames.add(new ItemName(Material.DARK_OAK_DOOR, langConfig.getString(\"block.minecraft.dark_oak_door\", \"Dark Oak Door\")));\n itemNames.add(new ItemName(Material.BEDROCK, langConfig.getString(\"block.minecraft.bedrock\", \"Bedrock\")));\n itemNames.add(new ItemName(Material.WATER, langConfig.getString(\"block.minecraft.water\", \"Water\")));\n itemNames.add(new ItemName(Material.LAVA, langConfig.getString(\"block.minecraft.lava\", \"Lava\")));\n itemNames.add(new ItemName(Material.SAND, langConfig.getString(\"block.minecraft.sand\", \"Sand\")));\n itemNames.add(new ItemName(Material.RED_SAND, langConfig.getString(\"block.minecraft.red_sand\", \"Red Sand\")));\n itemNames.add(new ItemName(Material.SANDSTONE, langConfig.getString(\"block.minecraft.sandstone\", \"Sandstone\")));\n itemNames.add(new ItemName(Material.CHISELED_SANDSTONE, langConfig.getString(\"block.minecraft.chiseled_sandstone\", \"Chiseled Sandstone\")));\n itemNames.add(new ItemName(Material.CUT_SANDSTONE, langConfig.getString(\"block.minecraft.cut_sandstone\", \"Cut Sandstone\")));\n itemNames.add(new ItemName(Material.RED_SANDSTONE, langConfig.getString(\"block.minecraft.red_sandstone\", \"Red Sandstone\")));\n itemNames.add(new ItemName(Material.CHISELED_RED_SANDSTONE, langConfig.getString(\"block.minecraft.chiseled_red_sandstone\", \"Chiseled Red Sandstone\")));\n itemNames.add(new ItemName(Material.CUT_RED_SANDSTONE, langConfig.getString(\"block.minecraft.cut_red_sandstone\", \"Cut Red Sandstone\")));\n itemNames.add(new ItemName(Material.GRAVEL, langConfig.getString(\"block.minecraft.gravel\", \"Gravel\")));\n itemNames.add(new ItemName(Material.GOLD_ORE, langConfig.getString(\"block.minecraft.gold_ore\", \"Gold Ore\")));\n itemNames.add(new ItemName(Material.IRON_ORE, langConfig.getString(\"block.minecraft.iron_ore\", \"Iron Ore\")));\n itemNames.add(new ItemName(Material.COAL_ORE, langConfig.getString(\"block.minecraft.coal_ore\", \"Coal Ore\")));\n itemNames.add(new ItemName(Material.OAK_WOOD, langConfig.getString(\"block.minecraft.oak_wood\", \"Oak Wood\")));\n itemNames.add(new ItemName(Material.SPRUCE_WOOD, langConfig.getString(\"block.minecraft.spruce_wood\", \"Spruce Wood\")));\n itemNames.add(new ItemName(Material.BIRCH_WOOD, langConfig.getString(\"block.minecraft.birch_wood\", \"Birch Wood\")));\n itemNames.add(new ItemName(Material.JUNGLE_WOOD, langConfig.getString(\"block.minecraft.jungle_wood\", \"Jungle Wood\")));\n itemNames.add(new ItemName(Material.ACACIA_WOOD, langConfig.getString(\"block.minecraft.acacia_wood\", \"Acacia Wood\")));\n itemNames.add(new ItemName(Material.DARK_OAK_WOOD, langConfig.getString(\"block.minecraft.dark_oak_wood\", \"Dark Oak Wood\")));\n itemNames.add(new ItemName(Material.OAK_LOG, langConfig.getString(\"block.minecraft.oak_log\", \"Oak Log\")));\n itemNames.add(new ItemName(Material.SPRUCE_LOG, langConfig.getString(\"block.minecraft.spruce_log\", \"Spruce Log\")));\n itemNames.add(new ItemName(Material.BIRCH_LOG, langConfig.getString(\"block.minecraft.birch_log\", \"Birch Log\")));\n itemNames.add(new ItemName(Material.JUNGLE_LOG, langConfig.getString(\"block.minecraft.jungle_log\", \"Jungle Log\")));\n itemNames.add(new ItemName(Material.ACACIA_LOG, langConfig.getString(\"block.minecraft.acacia_log\", \"Acacia Log\")));\n itemNames.add(new ItemName(Material.DARK_OAK_LOG, langConfig.getString(\"block.minecraft.dark_oak_log\", \"Dark Oak Log\")));\n itemNames.add(new ItemName(Material.STRIPPED_OAK_LOG, langConfig.getString(\"block.minecraft.stripped_oak_log\", \"Stripped Oak Log\")));\n itemNames.add(new ItemName(Material.STRIPPED_SPRUCE_LOG, langConfig.getString(\"block.minecraft.stripped_spruce_log\", \"Stripped Spruce Log\")));\n itemNames.add(new ItemName(Material.STRIPPED_BIRCH_LOG, langConfig.getString(\"block.minecraft.stripped_birch_log\", \"Stripped Birch Log\")));\n itemNames.add(new ItemName(Material.STRIPPED_JUNGLE_LOG, langConfig.getString(\"block.minecraft.stripped_jungle_log\", \"Stripped Jungle Log\")));\n itemNames.add(new ItemName(Material.STRIPPED_ACACIA_LOG, langConfig.getString(\"block.minecraft.stripped_acacia_log\", \"Stripped Acacia Log\")));\n itemNames.add(new ItemName(Material.STRIPPED_DARK_OAK_LOG, langConfig.getString(\"block.minecraft.stripped_dark_oak_log\", \"Stripped Dark Oak Log\")));\n itemNames.add(new ItemName(Material.STRIPPED_OAK_WOOD, langConfig.getString(\"block.minecraft.stripped_oak_wood\", \"Stripped Oak Wood\")));\n itemNames.add(new ItemName(Material.STRIPPED_SPRUCE_WOOD, langConfig.getString(\"block.minecraft.stripped_spruce_wood\", \"Stripped Spruce Wood\")));\n itemNames.add(new ItemName(Material.STRIPPED_BIRCH_WOOD, langConfig.getString(\"block.minecraft.stripped_birch_wood\", \"Stripped Birch Wood\")));\n itemNames.add(new ItemName(Material.STRIPPED_JUNGLE_WOOD, langConfig.getString(\"block.minecraft.stripped_jungle_wood\", \"Stripped Jungle Wood\")));\n itemNames.add(new ItemName(Material.STRIPPED_ACACIA_WOOD, langConfig.getString(\"block.minecraft.stripped_acacia_wood\", \"Stripped Acacia Wood\")));\n itemNames.add(new ItemName(Material.STRIPPED_DARK_OAK_WOOD, langConfig.getString(\"block.minecraft.stripped_dark_oak_wood\", \"Stripped Dark Oak Wood\")));\n itemNames.add(new ItemName(Material.OAK_LEAVES, langConfig.getString(\"block.minecraft.oak_leaves\", \"Oak Leaves\")));\n itemNames.add(new ItemName(Material.SPRUCE_LEAVES, langConfig.getString(\"block.minecraft.spruce_leaves\", \"Spruce Leaves\")));\n itemNames.add(new ItemName(Material.BIRCH_LEAVES, langConfig.getString(\"block.minecraft.birch_leaves\", \"Birch Leaves\")));\n itemNames.add(new ItemName(Material.JUNGLE_LEAVES, langConfig.getString(\"block.minecraft.jungle_leaves\", \"Jungle Leaves\")));\n itemNames.add(new ItemName(Material.ACACIA_LEAVES, langConfig.getString(\"block.minecraft.acacia_leaves\", \"Acacia Leaves\")));\n itemNames.add(new ItemName(Material.DARK_OAK_LEAVES, langConfig.getString(\"block.minecraft.dark_oak_leaves\", \"Dark Oak Leaves\")));\n itemNames.add(new ItemName(Material.DEAD_BUSH, langConfig.getString(\"block.minecraft.dead_bush\", \"Dead Bush\")));\n itemNames.add(new ItemName(Material.GRASS, langConfig.getString(\"block.minecraft.grass\", \"Grass\")));\n itemNames.add(new ItemName(Material.FERN, langConfig.getString(\"block.minecraft.fern\", \"Fern\")));\n itemNames.add(new ItemName(Material.SPONGE, langConfig.getString(\"block.minecraft.sponge\", \"Sponge\")));\n itemNames.add(new ItemName(Material.WET_SPONGE, langConfig.getString(\"block.minecraft.wet_sponge\", \"Wet Sponge\")));\n itemNames.add(new ItemName(Material.GLASS, langConfig.getString(\"block.minecraft.glass\", \"Glass\")));\n itemNames.add(new ItemName(Material.KELP_PLANT, langConfig.getString(\"block.minecraft.kelp_plant\", \"Kelp Plant\")));\n itemNames.add(new ItemName(Material.KELP, langConfig.getString(\"block.minecraft.kelp\", \"Kelp\")));\n itemNames.add(new ItemName(Material.DRIED_KELP_BLOCK, langConfig.getString(\"block.minecraft.dried_kelp_block\", \"Dried Kelp Block\")));\n itemNames.add(new ItemName(Material.WHITE_STAINED_GLASS, langConfig.getString(\"block.minecraft.white_stained_glass\", \"White Stained Glass\")));\n itemNames.add(new ItemName(Material.ORANGE_STAINED_GLASS, langConfig.getString(\"block.minecraft.orange_stained_glass\", \"Orange Stained Glass\")));\n itemNames.add(new ItemName(Material.MAGENTA_STAINED_GLASS, langConfig.getString(\"block.minecraft.magenta_stained_glass\", \"Magenta Stained Glass\")));\n itemNames.add(new ItemName(Material.LIGHT_BLUE_STAINED_GLASS, langConfig.getString(\"block.minecraft.light_blue_stained_glass\", \"Light Blue Stained Glass\")));\n itemNames.add(new ItemName(Material.YELLOW_STAINED_GLASS, langConfig.getString(\"block.minecraft.yellow_stained_glass\", \"Yellow Stained Glass\")));\n itemNames.add(new ItemName(Material.LIME_STAINED_GLASS, langConfig.getString(\"block.minecraft.lime_stained_glass\", \"Lime Stained Glass\")));\n itemNames.add(new ItemName(Material.PINK_STAINED_GLASS, langConfig.getString(\"block.minecraft.pink_stained_glass\", \"Pink Stained Glass\")));\n itemNames.add(new ItemName(Material.GRAY_STAINED_GLASS, langConfig.getString(\"block.minecraft.gray_stained_glass\", \"Gray Stained Glass\")));\n itemNames.add(new ItemName(Material.LIGHT_GRAY_STAINED_GLASS, langConfig.getString(\"block.minecraft.light_gray_stained_glass\", \"Light Gray Stained Glass\")));\n itemNames.add(new ItemName(Material.CYAN_STAINED_GLASS, langConfig.getString(\"block.minecraft.cyan_stained_glass\", \"Cyan Stained Glass\")));\n itemNames.add(new ItemName(Material.PURPLE_STAINED_GLASS, langConfig.getString(\"block.minecraft.purple_stained_glass\", \"Purple Stained Glass\")));\n itemNames.add(new ItemName(Material.BLUE_STAINED_GLASS, langConfig.getString(\"block.minecraft.blue_stained_glass\", \"Blue Stained Glass\")));\n itemNames.add(new ItemName(Material.BROWN_STAINED_GLASS, langConfig.getString(\"block.minecraft.brown_stained_glass\", \"Brown Stained Glass\")));\n itemNames.add(new ItemName(Material.GREEN_STAINED_GLASS, langConfig.getString(\"block.minecraft.green_stained_glass\", \"Green Stained Glass\")));\n itemNames.add(new ItemName(Material.RED_STAINED_GLASS, langConfig.getString(\"block.minecraft.red_stained_glass\", \"Red Stained Glass\")));\n itemNames.add(new ItemName(Material.BLACK_STAINED_GLASS, langConfig.getString(\"block.minecraft.black_stained_glass\", \"Black Stained Glass\")));\n itemNames.add(new ItemName(Material.WHITE_STAINED_GLASS_PANE, langConfig.getString(\"block.minecraft.white_stained_glass_pane\", \"White Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.ORANGE_STAINED_GLASS_PANE, langConfig.getString(\"block.minecraft.orange_stained_glass_pane\", \"Orange Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.MAGENTA_STAINED_GLASS_PANE, langConfig.getString(\"block.minecraft.magenta_stained_glass_pane\", \"Magenta Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.LIGHT_BLUE_STAINED_GLASS_PANE, langConfig.getString(\"block.minecraft.light_blue_stained_glass_pane\", \"Light Blue Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.YELLOW_STAINED_GLASS_PANE, langConfig.getString(\"block.minecraft.yellow_stained_glass_pane\", \"Yellow Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.LIME_STAINED_GLASS_PANE, langConfig.getString(\"block.minecraft.lime_stained_glass_pane\", \"Lime Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.PINK_STAINED_GLASS_PANE, langConfig.getString(\"block.minecraft.pink_stained_glass_pane\", \"Pink Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.GRAY_STAINED_GLASS_PANE, langConfig.getString(\"block.minecraft.gray_stained_glass_pane\", \"Gray Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.LIGHT_GRAY_STAINED_GLASS_PANE, langConfig.getString(\"block.minecraft.light_gray_stained_glass_pane\", \"Light Gray Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.CYAN_STAINED_GLASS_PANE, langConfig.getString(\"block.minecraft.cyan_stained_glass_pane\", \"Cyan Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.PURPLE_STAINED_GLASS_PANE, langConfig.getString(\"block.minecraft.purple_stained_glass_pane\", \"Purple Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.BLUE_STAINED_GLASS_PANE, langConfig.getString(\"block.minecraft.blue_stained_glass_pane\", \"Blue Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.BROWN_STAINED_GLASS_PANE, langConfig.getString(\"block.minecraft.brown_stained_glass_pane\", \"Brown Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.GREEN_STAINED_GLASS_PANE, langConfig.getString(\"block.minecraft.green_stained_glass_pane\", \"Green Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.RED_STAINED_GLASS_PANE, langConfig.getString(\"block.minecraft.red_stained_glass_pane\", \"Red Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.BLACK_STAINED_GLASS_PANE, langConfig.getString(\"block.minecraft.black_stained_glass_pane\", \"Black Stained Glass Pane\")));\n itemNames.add(new ItemName(Material.GLASS_PANE, langConfig.getString(\"block.minecraft.glass_pane\", \"Glass Pane\")));\n itemNames.add(new ItemName(Material.DANDELION, langConfig.getString(\"block.minecraft.dandelion\", \"Dandelion\")));\n itemNames.add(new ItemName(Material.POPPY, langConfig.getString(\"block.minecraft.poppy\", \"Poppy\")));\n itemNames.add(new ItemName(Material.BLUE_ORCHID, langConfig.getString(\"block.minecraft.blue_orchid\", \"Blue Orchid\")));\n itemNames.add(new ItemName(Material.ALLIUM, langConfig.getString(\"block.minecraft.allium\", \"Allium\")));\n itemNames.add(new ItemName(Material.AZURE_BLUET, langConfig.getString(\"block.minecraft.azure_bluet\", \"Azure Bluet\")));\n itemNames.add(new ItemName(Material.RED_TULIP, langConfig.getString(\"block.minecraft.red_tulip\", \"Red Tulip\")));\n itemNames.add(new ItemName(Material.ORANGE_TULIP, langConfig.getString(\"block.minecraft.orange_tulip\", \"Orange Tulip\")));\n itemNames.add(new ItemName(Material.WHITE_TULIP, langConfig.getString(\"block.minecraft.white_tulip\", \"White Tulip\")));\n itemNames.add(new ItemName(Material.PINK_TULIP, langConfig.getString(\"block.minecraft.pink_tulip\", \"Pink Tulip\")));\n itemNames.add(new ItemName(Material.OXEYE_DAISY, langConfig.getString(\"block.minecraft.oxeye_daisy\", \"Oxeye Daisy\")));\n itemNames.add(new ItemName(Material.SUNFLOWER, langConfig.getString(\"block.minecraft.sunflower\", \"Sunflower\")));\n itemNames.add(new ItemName(Material.LILAC, langConfig.getString(\"block.minecraft.lilac\", \"Lilac\")));\n itemNames.add(new ItemName(Material.TALL_GRASS, langConfig.getString(\"block.minecraft.tall_grass\", \"Tall Grass\")));\n itemNames.add(new ItemName(Material.TALL_SEAGRASS, langConfig.getString(\"block.minecraft.tall_seagrass\", \"Tall Seagrass\")));\n itemNames.add(new ItemName(Material.LARGE_FERN, langConfig.getString(\"block.minecraft.large_fern\", \"Large Fern\")));\n itemNames.add(new ItemName(Material.ROSE_BUSH, langConfig.getString(\"block.minecraft.rose_bush\", \"Rose Bush\")));\n itemNames.add(new ItemName(Material.PEONY, langConfig.getString(\"block.minecraft.peony\", \"Peony\")));\n itemNames.add(new ItemName(Material.SEAGRASS, langConfig.getString(\"block.minecraft.seagrass\", \"Seagrass\")));\n itemNames.add(new ItemName(Material.SEA_PICKLE, langConfig.getString(\"block.minecraft.sea_pickle\", \"Sea Pickle\")));\n itemNames.add(new ItemName(Material.BROWN_MUSHROOM, langConfig.getString(\"block.minecraft.brown_mushroom\", \"Brown Mushroom\")));\n itemNames.add(new ItemName(Material.RED_MUSHROOM_BLOCK, langConfig.getString(\"block.minecraft.red_mushroom_block\", \"Red Mushroom Block\")));\n itemNames.add(new ItemName(Material.BROWN_MUSHROOM_BLOCK, langConfig.getString(\"block.minecraft.brown_mushroom_block\", \"Brown Mushroom Block\")));\n itemNames.add(new ItemName(Material.MUSHROOM_STEM, langConfig.getString(\"block.minecraft.mushroom_stem\", \"Mushroom Stem\")));\n itemNames.add(new ItemName(Material.GOLD_BLOCK, langConfig.getString(\"block.minecraft.gold_block\", \"Block of Gold\")));\n itemNames.add(new ItemName(Material.IRON_BLOCK, langConfig.getString(\"block.minecraft.iron_block\", \"Block of Iron\")));\n itemNames.add(new ItemName(Material.SMOOTH_STONE, langConfig.getString(\"block.minecraft.smooth_stone\", \"Smooth Stone\")));\n itemNames.add(new ItemName(Material.SMOOTH_SANDSTONE, langConfig.getString(\"block.minecraft.smooth_sandstone\", \"Smooth Sandstone\")));\n itemNames.add(new ItemName(Material.SMOOTH_RED_SANDSTONE, langConfig.getString(\"block.minecraft.smooth_red_sandstone\", \"Smooth Red Sandstone\")));\n itemNames.add(new ItemName(Material.SMOOTH_QUARTZ, langConfig.getString(\"block.minecraft.smooth_quartz\", \"Smooth Quartz\")));\n itemNames.add(new ItemName(Material.STONE_SLAB, langConfig.getString(\"block.minecraft.stone_slab\", \"Stone Slab\")));\n itemNames.add(new ItemName(Material.SANDSTONE_SLAB, langConfig.getString(\"block.minecraft.sandstone_slab\", \"Sandstone Slab\")));\n itemNames.add(new ItemName(Material.RED_SANDSTONE_SLAB, langConfig.getString(\"block.minecraft.red_sandstone_slab\", \"Red Sandstone Slab\")));\n itemNames.add(new ItemName(Material.PETRIFIED_OAK_SLAB, langConfig.getString(\"block.minecraft.petrified_oak_slab\", \"Petrified Oak Slab\")));\n itemNames.add(new ItemName(Material.COBBLESTONE_SLAB, langConfig.getString(\"block.minecraft.cobblestone_slab\", \"Cobblestone Slab\")));\n itemNames.add(new ItemName(Material.BRICK_SLAB, langConfig.getString(\"block.minecraft.brick_slab\", \"Brick Slab\")));\n itemNames.add(new ItemName(Material.STONE_BRICK_SLAB, langConfig.getString(\"block.minecraft.stone_brick_slab\", \"Stone Brick Slab\")));\n itemNames.add(new ItemName(Material.NETHER_BRICK_SLAB, langConfig.getString(\"block.minecraft.nether_brick_slab\", \"Nether Brick Slab\")));\n itemNames.add(new ItemName(Material.QUARTZ_SLAB, langConfig.getString(\"block.minecraft.quartz_slab\", \"Quartz Slab\")));\n itemNames.add(new ItemName(Material.OAK_SLAB, langConfig.getString(\"block.minecraft.oak_slab\", \"Oak Slab\")));\n itemNames.add(new ItemName(Material.SPRUCE_SLAB, langConfig.getString(\"block.minecraft.spruce_slab\", \"Spruce Slab\")));\n itemNames.add(new ItemName(Material.BIRCH_SLAB, langConfig.getString(\"block.minecraft.birch_slab\", \"Birch Slab\")));\n itemNames.add(new ItemName(Material.JUNGLE_SLAB, langConfig.getString(\"block.minecraft.jungle_slab\", \"Jungle Slab\")));\n itemNames.add(new ItemName(Material.ACACIA_SLAB, langConfig.getString(\"block.minecraft.acacia_slab\", \"Acacia Slab\")));\n itemNames.add(new ItemName(Material.DARK_OAK_SLAB, langConfig.getString(\"block.minecraft.dark_oak_slab\", \"Dark Oak Slab\")));\n itemNames.add(new ItemName(Material.DARK_PRISMARINE_SLAB, langConfig.getString(\"block.minecraft.dark_prismarine_slab\", \"Dark Prismarine Slab\")));\n itemNames.add(new ItemName(Material.PRISMARINE_SLAB, langConfig.getString(\"block.minecraft.prismarine_slab\", \"Prismarine Slab\")));\n itemNames.add(new ItemName(Material.PRISMARINE_BRICK_SLAB, langConfig.getString(\"block.minecraft.prismarine_brick_slab\", \"Prismarine Brick Slab\")));\n itemNames.add(new ItemName(Material.BRICKS, langConfig.getString(\"block.minecraft.bricks\", \"Bricks\")));\n itemNames.add(new ItemName(Material.TNT, langConfig.getString(\"block.minecraft.tnt\", \"TNT\")));\n itemNames.add(new ItemName(Material.BOOKSHELF, langConfig.getString(\"block.minecraft.bookshelf\", \"Bookshelf\")));\n itemNames.add(new ItemName(Material.MOSSY_COBBLESTONE, langConfig.getString(\"block.minecraft.mossy_cobblestone\", \"Mossy Cobblestone\")));\n itemNames.add(new ItemName(Material.OBSIDIAN, langConfig.getString(\"block.minecraft.obsidian\", \"Obsidian\")));\n itemNames.add(new ItemName(Material.TORCH, langConfig.getString(\"block.minecraft.torch\", \"Torch\")));\n itemNames.add(new ItemName(Material.WALL_TORCH, langConfig.getString(\"block.minecraft.wall_torch\", \"Wall Torch\")));\n itemNames.add(new ItemName(Material.FIRE, langConfig.getString(\"block.minecraft.fire\", \"Fire\")));\n itemNames.add(new ItemName(Material.SPAWNER, langConfig.getString(\"block.minecraft.spawner\", \"Spawner\")));\n itemNames.add(new ItemName(Material.OAK_STAIRS, langConfig.getString(\"block.minecraft.oak_stairs\", \"Oak Stairs\")));\n itemNames.add(new ItemName(Material.SPRUCE_STAIRS, langConfig.getString(\"block.minecraft.spruce_stairs\", \"Spruce Stairs\")));\n itemNames.add(new ItemName(Material.BIRCH_STAIRS, langConfig.getString(\"block.minecraft.birch_stairs\", \"Birch Stairs\")));\n itemNames.add(new ItemName(Material.JUNGLE_STAIRS, langConfig.getString(\"block.minecraft.jungle_stairs\", \"Jungle Stairs\")));\n itemNames.add(new ItemName(Material.ACACIA_STAIRS, langConfig.getString(\"block.minecraft.acacia_stairs\", \"Acacia Stairs\")));\n itemNames.add(new ItemName(Material.DARK_OAK_STAIRS, langConfig.getString(\"block.minecraft.dark_oak_stairs\", \"Dark Oak Stairs\")));\n itemNames.add(new ItemName(Material.DARK_PRISMARINE_STAIRS, langConfig.getString(\"block.minecraft.dark_prismarine_stairs\", \"Dark Prismarine Stairs\")));\n itemNames.add(new ItemName(Material.PRISMARINE_STAIRS, langConfig.getString(\"block.minecraft.prismarine_stairs\", \"Prismarine Stairs\")));\n itemNames.add(new ItemName(Material.PRISMARINE_BRICK_STAIRS, langConfig.getString(\"block.minecraft.prismarine_brick_stairs\", \"Prismarine Brick Stairs\")));\n itemNames.add(new ItemName(Material.CHEST, langConfig.getString(\"block.minecraft.chest\", \"Chest\")));\n itemNames.add(new ItemName(Material.TRAPPED_CHEST, langConfig.getString(\"block.minecraft.trapped_chest\", \"Trapped Chest\")));\n itemNames.add(new ItemName(Material.REDSTONE_WIRE, langConfig.getString(\"block.minecraft.redstone_wire\", \"Redstone Dust\")));\n itemNames.add(new ItemName(Material.DIAMOND_ORE, langConfig.getString(\"block.minecraft.diamond_ore\", \"Diamond Ore\")));\n itemNames.add(new ItemName(Material.COAL_BLOCK, langConfig.getString(\"block.minecraft.coal_block\", \"Block of Coal\")));\n itemNames.add(new ItemName(Material.DIAMOND_BLOCK, langConfig.getString(\"block.minecraft.diamond_block\", \"Block of Diamond\")));\n itemNames.add(new ItemName(Material.CRAFTING_TABLE, langConfig.getString(\"block.minecraft.crafting_table\", \"Crafting Table\")));\n itemNames.add(new ItemName(Material.WHEAT, langConfig.getString(\"block.minecraft.wheat\", \"Wheat Crops\")));\n itemNames.add(new ItemName(Material.FARMLAND, langConfig.getString(\"block.minecraft.farmland\", \"Farmland\")));\n itemNames.add(new ItemName(Material.FURNACE, langConfig.getString(\"block.minecraft.furnace\", \"Furnace\")));\n itemNames.add(new ItemName(Material.LADDER, langConfig.getString(\"block.minecraft.ladder\", \"Ladder\")));\n itemNames.add(new ItemName(Material.RAIL, langConfig.getString(\"block.minecraft.rail\", \"Rail\")));\n itemNames.add(new ItemName(Material.POWERED_RAIL, langConfig.getString(\"block.minecraft.powered_rail\", \"Powered Rail\")));\n itemNames.add(new ItemName(Material.ACTIVATOR_RAIL, langConfig.getString(\"block.minecraft.activator_rail\", \"Activator Rail\")));\n itemNames.add(new ItemName(Material.DETECTOR_RAIL, langConfig.getString(\"block.minecraft.detector_rail\", \"Detector Rail\")));\n itemNames.add(new ItemName(Material.COBBLESTONE_STAIRS, langConfig.getString(\"block.minecraft.cobblestone_stairs\", \"Cobblestone Stairs\")));\n itemNames.add(new ItemName(Material.SANDSTONE_STAIRS, langConfig.getString(\"block.minecraft.sandstone_stairs\", \"Sandstone Stairs\")));\n itemNames.add(new ItemName(Material.RED_SANDSTONE_STAIRS, langConfig.getString(\"block.minecraft.red_sandstone_stairs\", \"Red Sandstone Stairs\")));\n itemNames.add(new ItemName(Material.LEVER, langConfig.getString(\"block.minecraft.lever\", \"Lever\")));\n itemNames.add(new ItemName(Material.STONE_PRESSURE_PLATE, langConfig.getString(\"block.minecraft.stone_pressure_plate\", \"Stone Pressure Plate\")));\n itemNames.add(new ItemName(Material.OAK_PRESSURE_PLATE, langConfig.getString(\"block.minecraft.oak_pressure_plate\", \"Oak Pressure Plate\")));\n itemNames.add(new ItemName(Material.SPRUCE_PRESSURE_PLATE, langConfig.getString(\"block.minecraft.spruce_pressure_plate\", \"Spruce Pressure Plate\")));\n itemNames.add(new ItemName(Material.BIRCH_PRESSURE_PLATE, langConfig.getString(\"block.minecraft.birch_pressure_plate\", \"Birch Pressure Plate\")));\n itemNames.add(new ItemName(Material.JUNGLE_PRESSURE_PLATE, langConfig.getString(\"block.minecraft.jungle_pressure_plate\", \"Jungle Pressure Plate\")));\n itemNames.add(new ItemName(Material.ACACIA_PRESSURE_PLATE, langConfig.getString(\"block.minecraft.acacia_pressure_plate\", \"Acacia Pressure Plate\")));\n itemNames.add(new ItemName(Material.DARK_OAK_PRESSURE_PLATE, langConfig.getString(\"block.minecraft.dark_oak_pressure_plate\", \"Dark Oak Pressure Plate\")));\n itemNames.add(new ItemName(Material.LIGHT_WEIGHTED_PRESSURE_PLATE, langConfig.getString(\"block.minecraft.light_weighted_pressure_plate\", \"Light Weighted Pressure Plate\")));\n itemNames.add(new ItemName(Material.HEAVY_WEIGHTED_PRESSURE_PLATE, langConfig.getString(\"block.minecraft.heavy_weighted_pressure_plate\", \"Heavy Weighted Pressure Plate\")));\n itemNames.add(new ItemName(Material.IRON_DOOR, langConfig.getString(\"block.minecraft.iron_door\", \"Iron Door\")));\n itemNames.add(new ItemName(Material.REDSTONE_ORE, langConfig.getString(\"block.minecraft.redstone_ore\", \"Redstone Ore\")));\n itemNames.add(new ItemName(Material.REDSTONE_TORCH, langConfig.getString(\"block.minecraft.redstone_torch\", \"Redstone Torch\")));\n itemNames.add(new ItemName(Material.REDSTONE_WALL_TORCH, langConfig.getString(\"block.minecraft.redstone_wall_torch\", \"Redstone Wall Torch\")));\n itemNames.add(new ItemName(Material.STONE_BUTTON, langConfig.getString(\"block.minecraft.stone_button\", \"Stone Button\")));\n itemNames.add(new ItemName(Material.OAK_BUTTON, langConfig.getString(\"block.minecraft.oak_button\", \"Oak Button\")));\n itemNames.add(new ItemName(Material.SPRUCE_BUTTON, langConfig.getString(\"block.minecraft.spruce_button\", \"Spruce Button\")));\n itemNames.add(new ItemName(Material.BIRCH_BUTTON, langConfig.getString(\"block.minecraft.birch_button\", \"Birch Button\")));\n itemNames.add(new ItemName(Material.JUNGLE_BUTTON, langConfig.getString(\"block.minecraft.jungle_button\", \"Jungle Button\")));\n itemNames.add(new ItemName(Material.ACACIA_BUTTON, langConfig.getString(\"block.minecraft.acacia_button\", \"Acacia Button\")));\n itemNames.add(new ItemName(Material.DARK_OAK_BUTTON, langConfig.getString(\"block.minecraft.dark_oak_button\", \"Dark Oak Button\")));\n itemNames.add(new ItemName(Material.SNOW, langConfig.getString(\"block.minecraft.snow\", \"Snow\")));\n itemNames.add(new ItemName(Material.WHITE_CARPET, langConfig.getString(\"block.minecraft.white_carpet\", \"White Carpet\")));\n itemNames.add(new ItemName(Material.ORANGE_CARPET, langConfig.getString(\"block.minecraft.orange_carpet\", \"Orange Carpet\")));\n itemNames.add(new ItemName(Material.MAGENTA_CARPET, langConfig.getString(\"block.minecraft.magenta_carpet\", \"Magenta Carpet\")));\n itemNames.add(new ItemName(Material.LIGHT_BLUE_CARPET, langConfig.getString(\"block.minecraft.light_blue_carpet\", \"Light Blue Carpet\")));\n itemNames.add(new ItemName(Material.YELLOW_CARPET, langConfig.getString(\"block.minecraft.yellow_carpet\", \"Yellow Carpet\")));\n itemNames.add(new ItemName(Material.LIME_CARPET, langConfig.getString(\"block.minecraft.lime_carpet\", \"Lime Carpet\")));\n itemNames.add(new ItemName(Material.PINK_CARPET, langConfig.getString(\"block.minecraft.pink_carpet\", \"Pink Carpet\")));\n itemNames.add(new ItemName(Material.GRAY_CARPET, langConfig.getString(\"block.minecraft.gray_carpet\", \"Gray Carpet\")));\n itemNames.add(new ItemName(Material.LIGHT_GRAY_CARPET, langConfig.getString(\"block.minecraft.light_gray_carpet\", \"Light Gray Carpet\")));\n itemNames.add(new ItemName(Material.CYAN_CARPET, langConfig.getString(\"block.minecraft.cyan_carpet\", \"Cyan Carpet\")));\n itemNames.add(new ItemName(Material.PURPLE_CARPET, langConfig.getString(\"block.minecraft.purple_carpet\", \"Purple Carpet\")));\n itemNames.add(new ItemName(Material.BLUE_CARPET, langConfig.getString(\"block.minecraft.blue_carpet\", \"Blue Carpet\")));\n itemNames.add(new ItemName(Material.BROWN_CARPET, langConfig.getString(\"block.minecraft.brown_carpet\", \"Brown Carpet\")));\n itemNames.add(new ItemName(Material.GREEN_CARPET, langConfig.getString(\"block.minecraft.green_carpet\", \"Green Carpet\")));\n itemNames.add(new ItemName(Material.RED_CARPET, langConfig.getString(\"block.minecraft.red_carpet\", \"Red Carpet\")));\n itemNames.add(new ItemName(Material.BLACK_CARPET, langConfig.getString(\"block.minecraft.black_carpet\", \"Black Carpet\")));\n itemNames.add(new ItemName(Material.ICE, langConfig.getString(\"block.minecraft.ice\", \"Ice\")));\n itemNames.add(new ItemName(Material.FROSTED_ICE, langConfig.getString(\"block.minecraft.frosted_ice\", \"Frosted Ice\")));\n itemNames.add(new ItemName(Material.PACKED_ICE, langConfig.getString(\"block.minecraft.packed_ice\", \"Packed Ice\")));\n itemNames.add(new ItemName(Material.BLUE_ICE, langConfig.getString(\"block.minecraft.blue_ice\", \"Blue Ice\")));\n itemNames.add(new ItemName(Material.CACTUS, langConfig.getString(\"block.minecraft.cactus\", \"Cactus\")));\n itemNames.add(new ItemName(Material.CLAY, langConfig.getString(\"block.minecraft.clay\", \"Clay\")));\n itemNames.add(new ItemName(Material.WHITE_TERRACOTTA, langConfig.getString(\"block.minecraft.white_terracotta\", \"White Terracotta\")));\n itemNames.add(new ItemName(Material.ORANGE_TERRACOTTA, langConfig.getString(\"block.minecraft.orange_terracotta\", \"Orange Terracotta\")));\n itemNames.add(new ItemName(Material.MAGENTA_TERRACOTTA, langConfig.getString(\"block.minecraft.magenta_terracotta\", \"Magenta Terracotta\")));\n itemNames.add(new ItemName(Material.LIGHT_BLUE_TERRACOTTA, langConfig.getString(\"block.minecraft.light_blue_terracotta\", \"Light Blue Terracotta\")));\n itemNames.add(new ItemName(Material.YELLOW_TERRACOTTA, langConfig.getString(\"block.minecraft.yellow_terracotta\", \"Yellow Terracotta\")));\n itemNames.add(new ItemName(Material.LIME_TERRACOTTA, langConfig.getString(\"block.minecraft.lime_terracotta\", \"Lime Terracotta\")));\n itemNames.add(new ItemName(Material.PINK_TERRACOTTA, langConfig.getString(\"block.minecraft.pink_terracotta\", \"Pink Terracotta\")));\n itemNames.add(new ItemName(Material.GRAY_TERRACOTTA, langConfig.getString(\"block.minecraft.gray_terracotta\", \"Gray Terracotta\")));\n itemNames.add(new ItemName(Material.LIGHT_GRAY_TERRACOTTA, langConfig.getString(\"block.minecraft.light_gray_terracotta\", \"Light Gray Terracotta\")));\n itemNames.add(new ItemName(Material.CYAN_TERRACOTTA, langConfig.getString(\"block.minecraft.cyan_terracotta\", \"Cyan Terracotta\")));\n itemNames.add(new ItemName(Material.PURPLE_TERRACOTTA, langConfig.getString(\"block.minecraft.purple_terracotta\", \"Purple Terracotta\")));\n itemNames.add(new ItemName(Material.BLUE_TERRACOTTA, langConfig.getString(\"block.minecraft.blue_terracotta\", \"Blue Terracotta\")));\n itemNames.add(new ItemName(Material.BROWN_TERRACOTTA, langConfig.getString(\"block.minecraft.brown_terracotta\", \"Brown Terracotta\")));\n itemNames.add(new ItemName(Material.GREEN_TERRACOTTA, langConfig.getString(\"block.minecraft.green_terracotta\", \"Green Terracotta\")));\n itemNames.add(new ItemName(Material.RED_TERRACOTTA, langConfig.getString(\"block.minecraft.red_terracotta\", \"Red Terracotta\")));\n itemNames.add(new ItemName(Material.BLACK_TERRACOTTA, langConfig.getString(\"block.minecraft.black_terracotta\", \"Black Terracotta\")));\n itemNames.add(new ItemName(Material.TERRACOTTA, langConfig.getString(\"block.minecraft.terracotta\", \"Terracotta\")));\n itemNames.add(new ItemName(Material.SUGAR_CANE, langConfig.getString(\"block.minecraft.sugar_cane\", \"Sugar Cane\")));\n itemNames.add(new ItemName(Material.JUKEBOX, langConfig.getString(\"block.minecraft.jukebox\", \"Jukebox\")));\n itemNames.add(new ItemName(Material.OAK_FENCE, langConfig.getString(\"block.minecraft.oak_fence\", \"Oak Fence\")));\n itemNames.add(new ItemName(Material.SPRUCE_FENCE, langConfig.getString(\"block.minecraft.spruce_fence\", \"Spruce Fence\")));\n itemNames.add(new ItemName(Material.BIRCH_FENCE, langConfig.getString(\"block.minecraft.birch_fence\", \"Birch Fence\")));\n itemNames.add(new ItemName(Material.JUNGLE_FENCE, langConfig.getString(\"block.minecraft.jungle_fence\", \"Jungle Fence\")));\n itemNames.add(new ItemName(Material.DARK_OAK_FENCE, langConfig.getString(\"block.minecraft.dark_oak_fence\", \"Dark Oak Fence\")));\n itemNames.add(new ItemName(Material.ACACIA_FENCE, langConfig.getString(\"block.minecraft.acacia_fence\", \"Acacia Fence\")));\n itemNames.add(new ItemName(Material.OAK_FENCE_GATE, langConfig.getString(\"block.minecraft.oak_fence_gate\", \"Oak Fence Gate\")));\n itemNames.add(new ItemName(Material.SPRUCE_FENCE_GATE, langConfig.getString(\"block.minecraft.spruce_fence_gate\", \"Spruce Fence Gate\")));\n itemNames.add(new ItemName(Material.BIRCH_FENCE_GATE, langConfig.getString(\"block.minecraft.birch_fence_gate\", \"Birch Fence Gate\")));\n itemNames.add(new ItemName(Material.JUNGLE_FENCE_GATE, langConfig.getString(\"block.minecraft.jungle_fence_gate\", \"Jungle Fence Gate\")));\n itemNames.add(new ItemName(Material.DARK_OAK_FENCE_GATE, langConfig.getString(\"block.minecraft.dark_oak_fence_gate\", \"Dark Oak Fence Gate\")));\n itemNames.add(new ItemName(Material.ACACIA_FENCE_GATE, langConfig.getString(\"block.minecraft.acacia_fence_gate\", \"Acacia Fence Gate\")));\n itemNames.add(new ItemName(Material.PUMPKIN_STEM, langConfig.getString(\"block.minecraft.pumpkin_stem\", \"Pumpkin Stem\")));\n itemNames.add(new ItemName(Material.ATTACHED_PUMPKIN_STEM, langConfig.getString(\"block.minecraft.attached_pumpkin_stem\", \"Attached Pumpkin Stem\")));\n itemNames.add(new ItemName(Material.PUMPKIN, langConfig.getString(\"block.minecraft.pumpkin\", \"Pumpkin\")));\n itemNames.add(new ItemName(Material.CARVED_PUMPKIN, langConfig.getString(\"block.minecraft.carved_pumpkin\", \"Carved Pumpkin\")));\n itemNames.add(new ItemName(Material.JACK_O_LANTERN, langConfig.getString(\"block.minecraft.jack_o_lantern\", \"Jack o'Lantern\")));\n itemNames.add(new ItemName(Material.NETHERRACK, langConfig.getString(\"block.minecraft.netherrack\", \"Netherrack\")));\n itemNames.add(new ItemName(Material.SOUL_SAND, langConfig.getString(\"block.minecraft.soul_sand\", \"Soul Sand\")));\n itemNames.add(new ItemName(Material.GLOWSTONE, langConfig.getString(\"block.minecraft.glowstone\", \"Glowstone\")));\n itemNames.add(new ItemName(Material.NETHER_PORTAL, langConfig.getString(\"block.minecraft.nether_portal\", \"Nether Portal\")));\n itemNames.add(new ItemName(Material.WHITE_WOOL, langConfig.getString(\"block.minecraft.white_wool\", \"White Wool\")));\n itemNames.add(new ItemName(Material.ORANGE_WOOL, langConfig.getString(\"block.minecraft.orange_wool\", \"Orange Wool\")));\n itemNames.add(new ItemName(Material.MAGENTA_WOOL, langConfig.getString(\"block.minecraft.magenta_wool\", \"Magenta Wool\")));\n itemNames.add(new ItemName(Material.LIGHT_BLUE_WOOL, langConfig.getString(\"block.minecraft.light_blue_wool\", \"Light Blue Wool\")));\n itemNames.add(new ItemName(Material.YELLOW_WOOL, langConfig.getString(\"block.minecraft.yellow_wool\", \"Yellow Wool\")));\n itemNames.add(new ItemName(Material.LIME_WOOL, langConfig.getString(\"block.minecraft.lime_wool\", \"Lime Wool\")));\n itemNames.add(new ItemName(Material.PINK_WOOL, langConfig.getString(\"block.minecraft.pink_wool\", \"Pink Wool\")));\n itemNames.add(new ItemName(Material.GRAY_WOOL, langConfig.getString(\"block.minecraft.gray_wool\", \"Gray Wool\")));\n itemNames.add(new ItemName(Material.LIGHT_GRAY_WOOL, langConfig.getString(\"block.minecraft.light_gray_wool\", \"Light Gray Wool\")));\n itemNames.add(new ItemName(Material.CYAN_WOOL, langConfig.getString(\"block.minecraft.cyan_wool\", \"Cyan Wool\")));\n itemNames.add(new ItemName(Material.PURPLE_WOOL, langConfig.getString(\"block.minecraft.purple_wool\", \"Purple Wool\")));\n itemNames.add(new ItemName(Material.BLUE_WOOL, langConfig.getString(\"block.minecraft.blue_wool\", \"Blue Wool\")));\n itemNames.add(new ItemName(Material.BROWN_WOOL, langConfig.getString(\"block.minecraft.brown_wool\", \"Brown Wool\")));\n itemNames.add(new ItemName(Material.GREEN_WOOL, langConfig.getString(\"block.minecraft.green_wool\", \"Green Wool\")));\n itemNames.add(new ItemName(Material.RED_WOOL, langConfig.getString(\"block.minecraft.red_wool\", \"Red Wool\")));\n itemNames.add(new ItemName(Material.BLACK_WOOL, langConfig.getString(\"block.minecraft.black_wool\", \"Black Wool\")));\n itemNames.add(new ItemName(Material.LAPIS_ORE, langConfig.getString(\"block.minecraft.lapis_ore\", \"Lapis Lazuli Ore\")));\n itemNames.add(new ItemName(Material.LAPIS_BLOCK, langConfig.getString(\"block.minecraft.lapis_block\", \"Lapis Lazuli Block\")));\n itemNames.add(new ItemName(Material.DISPENSER, langConfig.getString(\"block.minecraft.dispenser\", \"Dispenser\")));\n itemNames.add(new ItemName(Material.DROPPER, langConfig.getString(\"block.minecraft.dropper\", \"Dropper\")));\n itemNames.add(new ItemName(Material.NOTE_BLOCK, langConfig.getString(\"block.minecraft.note_block\", \"Note Block\")));\n itemNames.add(new ItemName(Material.CAKE, langConfig.getString(\"block.minecraft.cake\", \"Cake\")));\n itemNames.add(new ItemName(Material.OAK_TRAPDOOR, langConfig.getString(\"block.minecraft.oak_trapdoor\", \"Oak Trapdoor\")));\n itemNames.add(new ItemName(Material.SPRUCE_TRAPDOOR, langConfig.getString(\"block.minecraft.spruce_trapdoor\", \"Spruce Trapdoor\")));\n itemNames.add(new ItemName(Material.BIRCH_TRAPDOOR, langConfig.getString(\"block.minecraft.birch_trapdoor\", \"Birch Trapdoor\")));\n itemNames.add(new ItemName(Material.JUNGLE_TRAPDOOR, langConfig.getString(\"block.minecraft.jungle_trapdoor\", \"Jungle Trapdoor\")));\n itemNames.add(new ItemName(Material.ACACIA_TRAPDOOR, langConfig.getString(\"block.minecraft.acacia_trapdoor\", \"Acacia Trapdoor\")));\n itemNames.add(new ItemName(Material.DARK_OAK_TRAPDOOR, langConfig.getString(\"block.minecraft.dark_oak_trapdoor\", \"Dark Oak Trapdoor\")));\n itemNames.add(new ItemName(Material.IRON_TRAPDOOR, langConfig.getString(\"block.minecraft.iron_trapdoor\", \"Iron Trapdoor\")));\n itemNames.add(new ItemName(Material.COBWEB, langConfig.getString(\"block.minecraft.cobweb\", \"Cobweb\")));\n itemNames.add(new ItemName(Material.STONE_BRICKS, langConfig.getString(\"block.minecraft.stone_bricks\", \"Stone Bricks\")));\n itemNames.add(new ItemName(Material.MOSSY_STONE_BRICKS, langConfig.getString(\"block.minecraft.mossy_stone_bricks\", \"Mossy Stone Bricks\")));\n itemNames.add(new ItemName(Material.CRACKED_STONE_BRICKS, langConfig.getString(\"block.minecraft.cracked_stone_bricks\", \"Cracked Stone Bricks\")));\n itemNames.add(new ItemName(Material.CHISELED_STONE_BRICKS, langConfig.getString(\"block.minecraft.chiseled_stone_bricks\", \"Chiseled Stone Bricks\")));\n itemNames.add(new ItemName(Material.INFESTED_STONE, langConfig.getString(\"block.minecraft.infested_stone\", \"Infested Stone\")));\n itemNames.add(new ItemName(Material.INFESTED_COBBLESTONE, langConfig.getString(\"block.minecraft.infested_cobblestone\", \"Infested Cobblestone\")));\n itemNames.add(new ItemName(Material.INFESTED_STONE_BRICKS, langConfig.getString(\"block.minecraft.infested_stone_bricks\", \"Infested Stone Bricks\")));\n itemNames.add(new ItemName(Material.INFESTED_MOSSY_STONE_BRICKS, langConfig.getString(\"block.minecraft.infested_mossy_stone_bricks\", \"Infested Mossy Stone Bricks\")));\n itemNames.add(new ItemName(Material.INFESTED_CRACKED_STONE_BRICKS, langConfig.getString(\"block.minecraft.infested_cracked_stone_bricks\", \"Infested Cracked Stone Bricks\")));\n itemNames.add(new ItemName(Material.INFESTED_CHISELED_STONE_BRICKS, langConfig.getString(\"block.minecraft.infested_chiseled_stone_bricks\", \"Infested Chiseled Stone Bricks\")));\n itemNames.add(new ItemName(Material.PISTON, langConfig.getString(\"block.minecraft.piston\", \"Piston\")));\n itemNames.add(new ItemName(Material.STICKY_PISTON, langConfig.getString(\"block.minecraft.sticky_piston\", \"Sticky Piston\")));\n itemNames.add(new ItemName(Material.IRON_BARS, langConfig.getString(\"block.minecraft.iron_bars\", \"Iron Bars\")));\n itemNames.add(new ItemName(Material.MELON, langConfig.getString(\"block.minecraft.melon\", \"Melon\")));\n itemNames.add(new ItemName(Material.BRICK_STAIRS, langConfig.getString(\"block.minecraft.brick_stairs\", \"Brick Stairs\")));\n itemNames.add(new ItemName(Material.STONE_BRICK_STAIRS, langConfig.getString(\"block.minecraft.stone_brick_stairs\", \"Stone Brick Stairs\")));\n itemNames.add(new ItemName(Material.VINE, langConfig.getString(\"block.minecraft.vine\", \"Vines\")));\n itemNames.add(new ItemName(Material.NETHER_BRICKS, langConfig.getString(\"block.minecraft.nether_bricks\", \"Nether Bricks\")));\n itemNames.add(new ItemName(Material.NETHER_BRICK_FENCE, langConfig.getString(\"block.minecraft.nether_brick_fence\", \"Nether Brick Fence\")));\n itemNames.add(new ItemName(Material.NETHER_BRICK_STAIRS, langConfig.getString(\"block.minecraft.nether_brick_stairs\", \"Nether Brick Stairs\")));\n itemNames.add(new ItemName(Material.NETHER_WART, langConfig.getString(\"block.minecraft.nether_wart\", \"Nether Wart\")));\n itemNames.add(new ItemName(Material.CAULDRON, langConfig.getString(\"block.minecraft.cauldron\", \"Cauldron\")));\n itemNames.add(new ItemName(Material.ENCHANTING_TABLE, langConfig.getString(\"block.minecraft.enchanting_table\", \"Enchanting Table\")));\n itemNames.add(new ItemName(Material.ANVIL, langConfig.getString(\"block.minecraft.anvil\", \"Anvil\")));\n itemNames.add(new ItemName(Material.CHIPPED_ANVIL, langConfig.getString(\"block.minecraft.chipped_anvil\", \"Chipped Anvil\")));\n itemNames.add(new ItemName(Material.DAMAGED_ANVIL, langConfig.getString(\"block.minecraft.damaged_anvil\", \"Damaged Anvil\")));\n itemNames.add(new ItemName(Material.END_STONE, langConfig.getString(\"block.minecraft.end_stone\", \"End Stone\")));\n itemNames.add(new ItemName(Material.END_PORTAL_FRAME, langConfig.getString(\"block.minecraft.end_portal_frame\", \"End Portal Frame\")));\n itemNames.add(new ItemName(Material.MYCELIUM, langConfig.getString(\"block.minecraft.mycelium\", \"Mycelium\")));\n itemNames.add(new ItemName(Material.LILY_PAD, langConfig.getString(\"block.minecraft.lily_pad\", \"Lily Pad\")));\n itemNames.add(new ItemName(Material.DRAGON_EGG, langConfig.getString(\"block.minecraft.dragon_egg\", \"Dragon Egg\")));\n itemNames.add(new ItemName(Material.REDSTONE_LAMP, langConfig.getString(\"block.minecraft.redstone_lamp\", \"Redstone Lamp\")));\n itemNames.add(new ItemName(Material.COCOA, langConfig.getString(\"block.minecraft.cocoa\", \"Cocoa\")));\n itemNames.add(new ItemName(Material.ENDER_CHEST, langConfig.getString(\"block.minecraft.ender_chest\", \"Ender Chest\")));\n itemNames.add(new ItemName(Material.EMERALD_ORE, langConfig.getString(\"block.minecraft.emerald_ore\", \"Emerald Ore\")));\n itemNames.add(new ItemName(Material.EMERALD_BLOCK, langConfig.getString(\"block.minecraft.emerald_block\", \"Block of Emerald\")));\n itemNames.add(new ItemName(Material.REDSTONE_BLOCK, langConfig.getString(\"block.minecraft.redstone_block\", \"Block of Redstone\")));\n itemNames.add(new ItemName(Material.TRIPWIRE, langConfig.getString(\"block.minecraft.tripwire\", \"Tripwire\")));\n itemNames.add(new ItemName(Material.TRIPWIRE_HOOK, langConfig.getString(\"block.minecraft.tripwire_hook\", \"Tripwire Hook\")));\n itemNames.add(new ItemName(Material.COMMAND_BLOCK, langConfig.getString(\"block.minecraft.command_block\", \"Command Block\")));\n itemNames.add(new ItemName(Material.REPEATING_COMMAND_BLOCK, langConfig.getString(\"block.minecraft.repeating_command_block\", \"Repeating Command Block\")));\n itemNames.add(new ItemName(Material.CHAIN_COMMAND_BLOCK, langConfig.getString(\"block.minecraft.chain_command_block\", \"Chain Command Block\")));\n itemNames.add(new ItemName(Material.BEACON, langConfig.getString(\"block.minecraft.beacon\", \"Beacon\")));\n itemNames.add(new ItemName(Material.COBBLESTONE_WALL, langConfig.getString(\"block.minecraft.cobblestone_wall\", \"Cobblestone Wall\")));\n itemNames.add(new ItemName(Material.MOSSY_COBBLESTONE_WALL, langConfig.getString(\"block.minecraft.mossy_cobblestone_wall\", \"Mossy Cobblestone Wall\")));\n itemNames.add(new ItemName(Material.CARROTS, langConfig.getString(\"block.minecraft.carrots\", \"Carrots\")));\n itemNames.add(new ItemName(Material.POTATOES, langConfig.getString(\"block.minecraft.potatoes\", \"Potatoes\")));\n itemNames.add(new ItemName(Material.DAYLIGHT_DETECTOR, langConfig.getString(\"block.minecraft.daylight_detector\", \"Daylight Detector\")));\n itemNames.add(new ItemName(Material.NETHER_QUARTZ_ORE, langConfig.getString(\"block.minecraft.nether_quartz_ore\", \"Nether Quartz Ore\")));\n itemNames.add(new ItemName(Material.HOPPER, langConfig.getString(\"block.minecraft.hopper\", \"Hopper\")));\n itemNames.add(new ItemName(Material.QUARTZ_BLOCK, langConfig.getString(\"block.minecraft.quartz_block\", \"Block of Quartz\")));\n itemNames.add(new ItemName(Material.CHISELED_QUARTZ_BLOCK, langConfig.getString(\"block.minecraft.chiseled_quartz_block\", \"Chiseled Quartz Block\")));\n itemNames.add(new ItemName(Material.QUARTZ_PILLAR, langConfig.getString(\"block.minecraft.quartz_pillar\", \"Quartz Pillar\")));\n itemNames.add(new ItemName(Material.QUARTZ_STAIRS, langConfig.getString(\"block.minecraft.quartz_stairs\", \"Quartz Stairs\")));\n itemNames.add(new ItemName(Material.SLIME_BLOCK, langConfig.getString(\"block.minecraft.slime_block\", \"Slime Block\")));\n itemNames.add(new ItemName(Material.PRISMARINE, langConfig.getString(\"block.minecraft.prismarine\", \"Prismarine\")));\n itemNames.add(new ItemName(Material.PRISMARINE_BRICKS, langConfig.getString(\"block.minecraft.prismarine_bricks\", \"Prismarine Bricks\")));\n itemNames.add(new ItemName(Material.DARK_PRISMARINE, langConfig.getString(\"block.minecraft.dark_prismarine\", \"Dark Prismarine\")));\n itemNames.add(new ItemName(Material.SEA_LANTERN, langConfig.getString(\"block.minecraft.sea_lantern\", \"Sea Lantern\")));\n itemNames.add(new ItemName(Material.END_ROD, langConfig.getString(\"block.minecraft.end_rod\", \"End Rod\")));\n itemNames.add(new ItemName(Material.CHORUS_PLANT, langConfig.getString(\"block.minecraft.chorus_plant\", \"Chorus Plant\")));\n itemNames.add(new ItemName(Material.CHORUS_FLOWER, langConfig.getString(\"block.minecraft.chorus_flower\", \"Chorus Flower\")));\n itemNames.add(new ItemName(Material.PURPUR_BLOCK, langConfig.getString(\"block.minecraft.purpur_block\", \"Purpur Block\")));\n itemNames.add(new ItemName(Material.PURPUR_PILLAR, langConfig.getString(\"block.minecraft.purpur_pillar\", \"Purpur Pillar\")));\n itemNames.add(new ItemName(Material.PURPUR_STAIRS, langConfig.getString(\"block.minecraft.purpur_stairs\", \"Purpur Stairs\")));\n itemNames.add(new ItemName(Material.PURPUR_SLAB, langConfig.getString(\"block.minecraft.purpur_slab\", \"Purpur Slab\")));\n itemNames.add(new ItemName(Material.END_STONE_BRICKS, langConfig.getString(\"block.minecraft.end_stone_bricks\", \"End Stone Bricks\")));\n itemNames.add(new ItemName(Material.BEETROOTS, langConfig.getString(\"block.minecraft.beetroots\", \"Beetroots\")));\n itemNames.add(new ItemName(Material.MAGMA_BLOCK, langConfig.getString(\"block.minecraft.magma_block\", \"Magma Block\")));\n itemNames.add(new ItemName(Material.NETHER_WART_BLOCK, langConfig.getString(\"block.minecraft.nether_wart_block\", \"Nether Wart Block\")));\n itemNames.add(new ItemName(Material.RED_NETHER_BRICKS, langConfig.getString(\"block.minecraft.red_nether_bricks\", \"Red Nether Bricks\")));\n itemNames.add(new ItemName(Material.BONE_BLOCK, langConfig.getString(\"block.minecraft.bone_block\", \"Bone Block\")));\n itemNames.add(new ItemName(Material.OBSERVER, langConfig.getString(\"block.minecraft.observer\", \"Observer\")));\n itemNames.add(new ItemName(Material.SHULKER_BOX, langConfig.getString(\"block.minecraft.shulker_box\", \"Shulker Box\")));\n itemNames.add(new ItemName(Material.WHITE_SHULKER_BOX, langConfig.getString(\"block.minecraft.white_shulker_box\", \"White Shulker Box\")));\n itemNames.add(new ItemName(Material.ORANGE_SHULKER_BOX, langConfig.getString(\"block.minecraft.orange_shulker_box\", \"Orange Shulker Box\")));\n itemNames.add(new ItemName(Material.MAGENTA_SHULKER_BOX, langConfig.getString(\"block.minecraft.magenta_shulker_box\", \"Magenta Shulker Box\")));\n itemNames.add(new ItemName(Material.LIGHT_BLUE_SHULKER_BOX, langConfig.getString(\"block.minecraft.light_blue_shulker_box\", \"Light Blue Shulker Box\")));\n itemNames.add(new ItemName(Material.YELLOW_SHULKER_BOX, langConfig.getString(\"block.minecraft.yellow_shulker_box\", \"Yellow Shulker Box\")));\n itemNames.add(new ItemName(Material.LIME_SHULKER_BOX, langConfig.getString(\"block.minecraft.lime_shulker_box\", \"Lime Shulker Box\")));\n itemNames.add(new ItemName(Material.PINK_SHULKER_BOX, langConfig.getString(\"block.minecraft.pink_shulker_box\", \"Pink Shulker Box\")));\n itemNames.add(new ItemName(Material.GRAY_SHULKER_BOX, langConfig.getString(\"block.minecraft.gray_shulker_box\", \"Gray Shulker Box\")));\n itemNames.add(new ItemName(Material.LIGHT_GRAY_SHULKER_BOX, langConfig.getString(\"block.minecraft.light_gray_shulker_box\", \"Light Gray Shulker Box\")));\n itemNames.add(new ItemName(Material.CYAN_SHULKER_BOX, langConfig.getString(\"block.minecraft.cyan_shulker_box\", \"Cyan Shulker Box\")));\n itemNames.add(new ItemName(Material.PURPLE_SHULKER_BOX, langConfig.getString(\"block.minecraft.purple_shulker_box\", \"Purple Shulker Box\")));\n itemNames.add(new ItemName(Material.BLUE_SHULKER_BOX, langConfig.getString(\"block.minecraft.blue_shulker_box\", \"Blue Shulker Box\")));\n itemNames.add(new ItemName(Material.BROWN_SHULKER_BOX, langConfig.getString(\"block.minecraft.brown_shulker_box\", \"Brown Shulker Box\")));\n itemNames.add(new ItemName(Material.GREEN_SHULKER_BOX, langConfig.getString(\"block.minecraft.green_shulker_box\", \"Green Shulker Box\")));\n itemNames.add(new ItemName(Material.RED_SHULKER_BOX, langConfig.getString(\"block.minecraft.red_shulker_box\", \"Red Shulker Box\")));\n itemNames.add(new ItemName(Material.BLACK_SHULKER_BOX, langConfig.getString(\"block.minecraft.black_shulker_box\", \"Black Shulker Box\")));\n itemNames.add(new ItemName(Material.WHITE_GLAZED_TERRACOTTA, langConfig.getString(\"block.minecraft.white_glazed_terracotta\", \"White Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.ORANGE_GLAZED_TERRACOTTA, langConfig.getString(\"block.minecraft.orange_glazed_terracotta\", \"Orange Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.MAGENTA_GLAZED_TERRACOTTA, langConfig.getString(\"block.minecraft.magenta_glazed_terracotta\", \"Magenta Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.LIGHT_BLUE_GLAZED_TERRACOTTA, langConfig.getString(\"block.minecraft.light_blue_glazed_terracotta\", \"Light Blue Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.YELLOW_GLAZED_TERRACOTTA, langConfig.getString(\"block.minecraft.yellow_glazed_terracotta\", \"Yellow Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.LIME_GLAZED_TERRACOTTA, langConfig.getString(\"block.minecraft.lime_glazed_terracotta\", \"Lime Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.PINK_GLAZED_TERRACOTTA, langConfig.getString(\"block.minecraft.pink_glazed_terracotta\", \"Pink Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.GRAY_GLAZED_TERRACOTTA, langConfig.getString(\"block.minecraft.gray_glazed_terracotta\", \"Gray Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.LIGHT_GRAY_GLAZED_TERRACOTTA, langConfig.getString(\"block.minecraft.light_gray_glazed_terracotta\", \"Light Gray Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.CYAN_GLAZED_TERRACOTTA, langConfig.getString(\"block.minecraft.cyan_glazed_terracotta\", \"Cyan Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.PURPLE_GLAZED_TERRACOTTA, langConfig.getString(\"block.minecraft.purple_glazed_terracotta\", \"Purple Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.BLUE_GLAZED_TERRACOTTA, langConfig.getString(\"block.minecraft.blue_glazed_terracotta\", \"Blue Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.BROWN_GLAZED_TERRACOTTA, langConfig.getString(\"block.minecraft.brown_glazed_terracotta\", \"Brown Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.GREEN_GLAZED_TERRACOTTA, langConfig.getString(\"block.minecraft.green_glazed_terracotta\", \"Green Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.RED_GLAZED_TERRACOTTA, langConfig.getString(\"block.minecraft.red_glazed_terracotta\", \"Red Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.BLACK_GLAZED_TERRACOTTA, langConfig.getString(\"block.minecraft.black_glazed_terracotta\", \"Black Glazed Terracotta\")));\n itemNames.add(new ItemName(Material.BLACK_CONCRETE, langConfig.getString(\"block.minecraft.black_concrete\", \"Black Concrete\")));\n itemNames.add(new ItemName(Material.RED_CONCRETE, langConfig.getString(\"block.minecraft.red_concrete\", \"Red Concrete\")));\n itemNames.add(new ItemName(Material.GREEN_CONCRETE, langConfig.getString(\"block.minecraft.green_concrete\", \"Green Concrete\")));\n itemNames.add(new ItemName(Material.BROWN_CONCRETE, langConfig.getString(\"block.minecraft.brown_concrete\", \"Brown Concrete\")));\n itemNames.add(new ItemName(Material.BLUE_CONCRETE, langConfig.getString(\"block.minecraft.blue_concrete\", \"Blue Concrete\")));\n itemNames.add(new ItemName(Material.PURPLE_CONCRETE, langConfig.getString(\"block.minecraft.purple_concrete\", \"Purple Concrete\")));\n itemNames.add(new ItemName(Material.CYAN_CONCRETE, langConfig.getString(\"block.minecraft.cyan_concrete\", \"Cyan Concrete\")));\n itemNames.add(new ItemName(Material.LIGHT_GRAY_CONCRETE, langConfig.getString(\"block.minecraft.light_gray_concrete\", \"Light Gray Concrete\")));\n itemNames.add(new ItemName(Material.GRAY_CONCRETE, langConfig.getString(\"block.minecraft.gray_concrete\", \"Gray Concrete\")));\n itemNames.add(new ItemName(Material.PINK_CONCRETE, langConfig.getString(\"block.minecraft.pink_concrete\", \"Pink Concrete\")));\n itemNames.add(new ItemName(Material.LIME_CONCRETE, langConfig.getString(\"block.minecraft.lime_concrete\", \"Lime Concrete\")));\n itemNames.add(new ItemName(Material.YELLOW_CONCRETE, langConfig.getString(\"block.minecraft.yellow_concrete\", \"Yellow Concrete\")));\n itemNames.add(new ItemName(Material.LIGHT_BLUE_CONCRETE, langConfig.getString(\"block.minecraft.light_blue_concrete\", \"Light Blue Concrete\")));\n itemNames.add(new ItemName(Material.MAGENTA_CONCRETE, langConfig.getString(\"block.minecraft.magenta_concrete\", \"Magenta Concrete\")));\n itemNames.add(new ItemName(Material.ORANGE_CONCRETE, langConfig.getString(\"block.minecraft.orange_concrete\", \"Orange Concrete\")));\n itemNames.add(new ItemName(Material.WHITE_CONCRETE, langConfig.getString(\"block.minecraft.white_concrete\", \"White Concrete\")));\n itemNames.add(new ItemName(Material.BLACK_CONCRETE_POWDER, langConfig.getString(\"block.minecraft.black_concrete_powder\", \"Black Concrete Powder\")));\n itemNames.add(new ItemName(Material.RED_CONCRETE_POWDER, langConfig.getString(\"block.minecraft.red_concrete_powder\", \"Red Concrete Powder\")));\n itemNames.add(new ItemName(Material.GREEN_CONCRETE_POWDER, langConfig.getString(\"block.minecraft.green_concrete_powder\", \"Green Concrete Powder\")));\n itemNames.add(new ItemName(Material.BROWN_CONCRETE_POWDER, langConfig.getString(\"block.minecraft.brown_concrete_powder\", \"Brown Concrete Powder\")));\n itemNames.add(new ItemName(Material.BLUE_CONCRETE_POWDER, langConfig.getString(\"block.minecraft.blue_concrete_powder\", \"Blue Concrete Powder\")));\n itemNames.add(new ItemName(Material.PURPLE_CONCRETE_POWDER, langConfig.getString(\"block.minecraft.purple_concrete_powder\", \"Purple Concrete Powder\")));\n itemNames.add(new ItemName(Material.CYAN_CONCRETE_POWDER, langConfig.getString(\"block.minecraft.cyan_concrete_powder\", \"Cyan Concrete Powder\")));\n itemNames.add(new ItemName(Material.LIGHT_GRAY_CONCRETE_POWDER, langConfig.getString(\"block.minecraft.light_gray_concrete_powder\", \"Light Gray Concrete Powder\")));\n itemNames.add(new ItemName(Material.GRAY_CONCRETE_POWDER, langConfig.getString(\"block.minecraft.gray_concrete_powder\", \"Gray Concrete Powder\")));\n itemNames.add(new ItemName(Material.PINK_CONCRETE_POWDER, langConfig.getString(\"block.minecraft.pink_concrete_powder\", \"Pink Concrete Powder\")));\n itemNames.add(new ItemName(Material.LIME_CONCRETE_POWDER, langConfig.getString(\"block.minecraft.lime_concrete_powder\", \"Lime Concrete Powder\")));\n itemNames.add(new ItemName(Material.YELLOW_CONCRETE_POWDER, langConfig.getString(\"block.minecraft.yellow_concrete_powder\", \"Yellow Concrete Powder\")));\n itemNames.add(new ItemName(Material.LIGHT_BLUE_CONCRETE_POWDER, langConfig.getString(\"block.minecraft.light_blue_concrete_powder\", \"Light Blue Concrete Powder\")));\n itemNames.add(new ItemName(Material.MAGENTA_CONCRETE_POWDER, langConfig.getString(\"block.minecraft.magenta_concrete_powder\", \"Magenta Concrete Powder\")));\n itemNames.add(new ItemName(Material.ORANGE_CONCRETE_POWDER, langConfig.getString(\"block.minecraft.orange_concrete_powder\", \"Orange Concrete Powder\")));\n itemNames.add(new ItemName(Material.WHITE_CONCRETE_POWDER, langConfig.getString(\"block.minecraft.white_concrete_powder\", \"White Concrete Powder\")));\n itemNames.add(new ItemName(Material.TURTLE_EGG, langConfig.getString(\"block.minecraft.turtle_egg\", \"Turtle Egg\")));\n itemNames.add(new ItemName(Material.PISTON_HEAD, langConfig.getString(\"block.minecraft.piston_head\", \"Piston Head\")));\n itemNames.add(new ItemName(Material.MOVING_PISTON, langConfig.getString(\"block.minecraft.moving_piston\", \"Moving Piston\")));\n itemNames.add(new ItemName(Material.RED_MUSHROOM, langConfig.getString(\"block.minecraft.red_mushroom\", \"Red Mushroom\")));\n itemNames.add(new ItemName(Material.SNOW_BLOCK, langConfig.getString(\"block.minecraft.snow_block\", \"Snow Block\")));\n itemNames.add(new ItemName(Material.ATTACHED_MELON_STEM, langConfig.getString(\"block.minecraft.attached_melon_stem\", \"Attached Melon Stem\")));\n itemNames.add(new ItemName(Material.MELON_STEM, langConfig.getString(\"block.minecraft.melon_stem\", \"Melon Stem\")));\n itemNames.add(new ItemName(Material.BREWING_STAND, langConfig.getString(\"block.minecraft.brewing_stand\", \"Brewing Stand\")));\n itemNames.add(new ItemName(Material.END_PORTAL, langConfig.getString(\"block.minecraft.end_portal\", \"End Portal\")));\n itemNames.add(new ItemName(Material.FLOWER_POT, langConfig.getString(\"block.minecraft.flower_pot\", \"Flower Pot\")));\n itemNames.add(new ItemName(Material.POTTED_OAK_SAPLING, langConfig.getString(\"block.minecraft.potted_oak_sapling\", \"Potted Oak Sapling\")));\n itemNames.add(new ItemName(Material.POTTED_SPRUCE_SAPLING, langConfig.getString(\"block.minecraft.potted_spruce_sapling\", \"Potted Spruce Sapling\")));\n itemNames.add(new ItemName(Material.POTTED_BIRCH_SAPLING, langConfig.getString(\"block.minecraft.potted_birch_sapling\", \"Potted Birch Sapling\")));\n itemNames.add(new ItemName(Material.POTTED_JUNGLE_SAPLING, langConfig.getString(\"block.minecraft.potted_jungle_sapling\", \"Potted Jungle Sapling\")));\n itemNames.add(new ItemName(Material.POTTED_ACACIA_SAPLING, langConfig.getString(\"block.minecraft.potted_acacia_sapling\", \"Potted Acacia Sapling\")));\n itemNames.add(new ItemName(Material.POTTED_DARK_OAK_SAPLING, langConfig.getString(\"block.minecraft.potted_dark_oak_sapling\", \"Potted Dark Oak Sapling\")));\n itemNames.add(new ItemName(Material.POTTED_FERN, langConfig.getString(\"block.minecraft.potted_fern\", \"Potted Fern\")));\n itemNames.add(new ItemName(Material.POTTED_DANDELION, langConfig.getString(\"block.minecraft.potted_dandelion\", \"Potted Dandelion\")));\n itemNames.add(new ItemName(Material.POTTED_POPPY, langConfig.getString(\"block.minecraft.potted_poppy\", \"Potted Poppy\")));\n itemNames.add(new ItemName(Material.POTTED_BLUE_ORCHID, langConfig.getString(\"block.minecraft.potted_blue_orchid\", \"Potted Blue Orchid\")));\n itemNames.add(new ItemName(Material.POTTED_ALLIUM, langConfig.getString(\"block.minecraft.potted_allium\", \"Potted Allium\")));\n itemNames.add(new ItemName(Material.POTTED_AZURE_BLUET, langConfig.getString(\"block.minecraft.potted_azure_bluet\", \"Potted Azure Bluet\")));\n itemNames.add(new ItemName(Material.POTTED_RED_TULIP, langConfig.getString(\"block.minecraft.potted_red_tulip\", \"Potted Red Tulip\")));\n itemNames.add(new ItemName(Material.POTTED_ORANGE_TULIP, langConfig.getString(\"block.minecraft.potted_orange_tulip\", \"Potted Orange Tulip\")));\n itemNames.add(new ItemName(Material.POTTED_WHITE_TULIP, langConfig.getString(\"block.minecraft.potted_white_tulip\", \"Potted White Tulip\")));\n itemNames.add(new ItemName(Material.POTTED_PINK_TULIP, langConfig.getString(\"block.minecraft.potted_pink_tulip\", \"Potted Pink Tulip\")));\n itemNames.add(new ItemName(Material.POTTED_OXEYE_DAISY, langConfig.getString(\"block.minecraft.potted_oxeye_daisy\", \"Potted Oxeye Daisy\")));\n itemNames.add(new ItemName(Material.POTTED_RED_MUSHROOM, langConfig.getString(\"block.minecraft.potted_red_mushroom\", \"Potted Red Mushroom\")));\n itemNames.add(new ItemName(Material.POTTED_BROWN_MUSHROOM, langConfig.getString(\"block.minecraft.potted_brown_mushroom\", \"Potted Brown Mushroom\")));\n itemNames.add(new ItemName(Material.POTTED_DEAD_BUSH, langConfig.getString(\"block.minecraft.potted_dead_bush\", \"Potted Dead Bush\")));\n itemNames.add(new ItemName(Material.POTTED_CACTUS, langConfig.getString(\"block.minecraft.potted_cactus\", \"Potted Cactus\")));\n itemNames.add(new ItemName(Material.SKELETON_WALL_SKULL, langConfig.getString(\"block.minecraft.skeleton_wall_skull\", \"Skeleton Wall Skull\")));\n itemNames.add(new ItemName(Material.SKELETON_SKULL, langConfig.getString(\"block.minecraft.skeleton_skull\", \"Skeleton Skull\")));\n itemNames.add(new ItemName(Material.WITHER_SKELETON_WALL_SKULL, langConfig.getString(\"block.minecraft.wither_skeleton_wall_skull\", \"Wither Skeleton Wall Skull\")));\n itemNames.add(new ItemName(Material.WITHER_SKELETON_SKULL, langConfig.getString(\"block.minecraft.wither_skeleton_skull\", \"Wither Skeleton Skull\")));\n itemNames.add(new ItemName(Material.ZOMBIE_WALL_HEAD, langConfig.getString(\"block.minecraft.zombie_wall_head\", \"Zombie Wall Head\")));\n itemNames.add(new ItemName(Material.ZOMBIE_HEAD, langConfig.getString(\"block.minecraft.zombie_head\", \"Zombie Head\")));\n itemNames.add(new ItemName(Material.PLAYER_WALL_HEAD, langConfig.getString(\"block.minecraft.player_wall_head\", \"Player Wall Head\")));\n itemNames.add(new ItemName(Material.PLAYER_HEAD, langConfig.getString(\"block.minecraft.player_head\", \"Player Head\")));\n itemNames.add(new ItemName(Material.CREEPER_WALL_HEAD, langConfig.getString(\"block.minecraft.creeper_wall_head\", \"Creeper Wall Head\")));\n itemNames.add(new ItemName(Material.CREEPER_HEAD, langConfig.getString(\"block.minecraft.creeper_head\", \"Creeper Head\")));\n itemNames.add(new ItemName(Material.DRAGON_WALL_HEAD, langConfig.getString(\"block.minecraft.dragon_wall_head\", \"Dragon Wall Head\")));\n itemNames.add(new ItemName(Material.DRAGON_HEAD, langConfig.getString(\"block.minecraft.dragon_head\", \"Dragon Head\")));\n itemNames.add(new ItemName(Material.END_GATEWAY, langConfig.getString(\"block.minecraft.end_gateway\", \"End Gateway\")));\n itemNames.add(new ItemName(Material.STRUCTURE_VOID, langConfig.getString(\"block.minecraft.structure_void\", \"Structure Void\")));\n itemNames.add(new ItemName(Material.STRUCTURE_BLOCK, langConfig.getString(\"block.minecraft.structure_block\", \"Structure Block\")));\n itemNames.add(new ItemName(Material.VOID_AIR, langConfig.getString(\"block.minecraft.void_air\", \"Void Air\")));\n itemNames.add(new ItemName(Material.CAVE_AIR, langConfig.getString(\"block.minecraft.cave_air\", \"Cave Air\")));\n itemNames.add(new ItemName(Material.BUBBLE_COLUMN, langConfig.getString(\"block.minecraft.bubble_column\", \"Bubble Column\")));\n itemNames.add(new ItemName(Material.DEAD_TUBE_CORAL_BLOCK, langConfig.getString(\"block.minecraft.dead_tube_coral_block\", \"Dead Tube Coral Block\")));\n itemNames.add(new ItemName(Material.DEAD_BRAIN_CORAL_BLOCK, langConfig.getString(\"block.minecraft.dead_brain_coral_block\", \"Dead Brain Coral Block\")));\n itemNames.add(new ItemName(Material.DEAD_BUBBLE_CORAL_BLOCK, langConfig.getString(\"block.minecraft.dead_bubble_coral_block\", \"Dead Bubble Coral Block\")));\n itemNames.add(new ItemName(Material.DEAD_FIRE_CORAL_BLOCK, langConfig.getString(\"block.minecraft.dead_fire_coral_block\", \"Dead Fire Coral Block\")));\n itemNames.add(new ItemName(Material.DEAD_HORN_CORAL_BLOCK, langConfig.getString(\"block.minecraft.dead_horn_coral_block\", \"Dead Horn Coral Block\")));\n itemNames.add(new ItemName(Material.TUBE_CORAL_BLOCK, langConfig.getString(\"block.minecraft.tube_coral_block\", \"Tube Coral Block\")));\n itemNames.add(new ItemName(Material.BRAIN_CORAL_BLOCK, langConfig.getString(\"block.minecraft.brain_coral_block\", \"Brain Coral Block\")));\n itemNames.add(new ItemName(Material.BUBBLE_CORAL_BLOCK, langConfig.getString(\"block.minecraft.bubble_coral_block\", \"Bubble Coral Block\")));\n itemNames.add(new ItemName(Material.FIRE_CORAL_BLOCK, langConfig.getString(\"block.minecraft.fire_coral_block\", \"Fire Coral Block\")));\n itemNames.add(new ItemName(Material.HORN_CORAL_BLOCK, langConfig.getString(\"block.minecraft.horn_coral_block\", \"Horn Coral Block\")));\n itemNames.add(new ItemName(Material.TUBE_CORAL, langConfig.getString(\"block.minecraft.tube_coral\", \"Tube Coral\")));\n itemNames.add(new ItemName(Material.BRAIN_CORAL, langConfig.getString(\"block.minecraft.brain_coral\", \"Brain Coral\")));\n itemNames.add(new ItemName(Material.BUBBLE_CORAL, langConfig.getString(\"block.minecraft.bubble_coral\", \"Bubble Coral\")));\n itemNames.add(new ItemName(Material.FIRE_CORAL, langConfig.getString(\"block.minecraft.fire_coral\", \"Fire Coral\")));\n itemNames.add(new ItemName(Material.HORN_CORAL, langConfig.getString(\"block.minecraft.horn_coral\", \"Horn Coral\")));\n itemNames.add(new ItemName(Material.TUBE_CORAL_FAN, langConfig.getString(\"block.minecraft.tube_coral_fan\", \"Tube Coral Fan\")));\n itemNames.add(new ItemName(Material.BRAIN_CORAL_FAN, langConfig.getString(\"block.minecraft.brain_coral_fan\", \"Brain Coral Fan\")));\n itemNames.add(new ItemName(Material.BUBBLE_CORAL_FAN, langConfig.getString(\"block.minecraft.bubble_coral_fan\", \"Bubble Coral Fan\")));\n itemNames.add(new ItemName(Material.FIRE_CORAL_FAN, langConfig.getString(\"block.minecraft.fire_coral_fan\", \"Fire Coral Fan\")));\n itemNames.add(new ItemName(Material.HORN_CORAL_FAN, langConfig.getString(\"block.minecraft.horn_coral_fan\", \"Horn Coral Fan\")));\n itemNames.add(new ItemName(Material.CONDUIT, langConfig.getString(\"block.minecraft.conduit\", \"Conduit\")));\n itemNames.add(new ItemName(Material.NAME_TAG, langConfig.getString(\"item.minecraft.name_tag\", \"Name Tag\")));\n itemNames.add(new ItemName(Material.LEAD, langConfig.getString(\"item.minecraft.lead\", \"Lead\")));\n itemNames.add(new ItemName(Material.IRON_SHOVEL, langConfig.getString(\"item.minecraft.iron_shovel\", \"Iron Shovel\")));\n itemNames.add(new ItemName(Material.IRON_PICKAXE, langConfig.getString(\"item.minecraft.iron_pickaxe\", \"Iron Pickaxe\")));\n itemNames.add(new ItemName(Material.IRON_AXE, langConfig.getString(\"item.minecraft.iron_axe\", \"Iron Axe\")));\n itemNames.add(new ItemName(Material.FLINT_AND_STEEL, langConfig.getString(\"item.minecraft.flint_and_steel\", \"Flint and Steel\")));\n itemNames.add(new ItemName(Material.APPLE, langConfig.getString(\"item.minecraft.apple\", \"Apple\")));\n itemNames.add(new ItemName(Material.COOKIE, langConfig.getString(\"item.minecraft.cookie\", \"Cookie\")));\n itemNames.add(new ItemName(Material.BOW, langConfig.getString(\"item.minecraft.bow\", \"Bow\")));\n itemNames.add(new ItemName(Material.ARROW, langConfig.getString(\"item.minecraft.arrow\", \"Arrow\")));\n itemNames.add(new ItemName(Material.SPECTRAL_ARROW, langConfig.getString(\"item.minecraft.spectral_arrow\", \"Spectral Arrow\")));\n itemNames.add(new ItemName(Material.TIPPED_ARROW, langConfig.getString(\"item.minecraft.tipped_arrow\", \"Tipped Arrow\")));\n itemNames.add(new ItemName(Material.DRIED_KELP, langConfig.getString(\"item.minecraft.dried_kelp\", \"Dried Kelp\")));\n itemNames.add(new ItemName(Material.COAL, langConfig.getString(\"item.minecraft.coal\", \"Coal\")));\n itemNames.add(new ItemName(Material.CHARCOAL, langConfig.getString(\"item.minecraft.charcoal\", \"Charcoal\")));\n itemNames.add(new ItemName(Material.DIAMOND, langConfig.getString(\"item.minecraft.diamond\", \"Diamond\")));\n itemNames.add(new ItemName(Material.EMERALD, langConfig.getString(\"item.minecraft.emerald\", \"Emerald\")));\n itemNames.add(new ItemName(Material.IRON_INGOT, langConfig.getString(\"item.minecraft.iron_ingot\", \"Iron Ingot\")));\n itemNames.add(new ItemName(Material.GOLD_INGOT, langConfig.getString(\"item.minecraft.gold_ingot\", \"Gold Ingot\")));\n itemNames.add(new ItemName(Material.IRON_SWORD, langConfig.getString(\"item.minecraft.iron_sword\", \"Iron Sword\")));\n itemNames.add(new ItemName(Material.WOODEN_SWORD, langConfig.getString(\"item.minecraft.wooden_sword\", \"Wooden Sword\")));\n itemNames.add(new ItemName(Material.WOODEN_SHOVEL, langConfig.getString(\"item.minecraft.wooden_shovel\", \"Wooden Shovel\")));\n itemNames.add(new ItemName(Material.WOODEN_PICKAXE, langConfig.getString(\"item.minecraft.wooden_pickaxe\", \"Wooden Pickaxe\")));\n itemNames.add(new ItemName(Material.WOODEN_AXE, langConfig.getString(\"item.minecraft.wooden_axe\", \"Wooden Axe\")));\n itemNames.add(new ItemName(Material.STONE_SWORD, langConfig.getString(\"item.minecraft.stone_sword\", \"Stone Sword\")));\n itemNames.add(new ItemName(Material.STONE_SHOVEL, langConfig.getString(\"item.minecraft.stone_shovel\", \"Stone Shovel\")));\n itemNames.add(new ItemName(Material.STONE_PICKAXE, langConfig.getString(\"item.minecraft.stone_pickaxe\", \"Stone Pickaxe\")));\n itemNames.add(new ItemName(Material.STONE_AXE, langConfig.getString(\"item.minecraft.stone_axe\", \"Stone Axe\")));\n itemNames.add(new ItemName(Material.DIAMOND_SWORD, langConfig.getString(\"item.minecraft.diamond_sword\", \"Diamond Sword\")));\n itemNames.add(new ItemName(Material.DIAMOND_SHOVEL, langConfig.getString(\"item.minecraft.diamond_shovel\", \"Diamond Shovel\")));\n itemNames.add(new ItemName(Material.DIAMOND_PICKAXE, langConfig.getString(\"item.minecraft.diamond_pickaxe\", \"Diamond Pickaxe\")));\n itemNames.add(new ItemName(Material.DIAMOND_AXE, langConfig.getString(\"item.minecraft.diamond_axe\", \"Diamond Axe\")));\n itemNames.add(new ItemName(Material.STICK, langConfig.getString(\"item.minecraft.stick\", \"Stick\")));\n itemNames.add(new ItemName(Material.BOWL, langConfig.getString(\"item.minecraft.bowl\", \"Bowl\")));\n itemNames.add(new ItemName(Material.MUSHROOM_STEW, langConfig.getString(\"item.minecraft.mushroom_stew\", \"Mushroom Stew\")));\n itemNames.add(new ItemName(Material.GOLDEN_SWORD, langConfig.getString(\"item.minecraft.golden_sword\", \"Golden Sword\")));\n itemNames.add(new ItemName(Material.GOLDEN_SHOVEL, langConfig.getString(\"item.minecraft.golden_shovel\", \"Golden Shovel\")));\n itemNames.add(new ItemName(Material.GOLDEN_PICKAXE, langConfig.getString(\"item.minecraft.golden_pickaxe\", \"Golden Pickaxe\")));\n itemNames.add(new ItemName(Material.GOLDEN_AXE, langConfig.getString(\"item.minecraft.golden_axe\", \"Golden Axe\")));\n itemNames.add(new ItemName(Material.STRING, langConfig.getString(\"item.minecraft.string\", \"String\")));\n itemNames.add(new ItemName(Material.FEATHER, langConfig.getString(\"item.minecraft.feather\", \"Feather\")));\n itemNames.add(new ItemName(Material.GUNPOWDER, langConfig.getString(\"item.minecraft.gunpowder\", \"Gunpowder\")));\n itemNames.add(new ItemName(Material.WOODEN_HOE, langConfig.getString(\"item.minecraft.wooden_hoe\", \"Wooden Hoe\")));\n itemNames.add(new ItemName(Material.STONE_HOE, langConfig.getString(\"item.minecraft.stone_hoe\", \"Stone Hoe\")));\n itemNames.add(new ItemName(Material.IRON_HOE, langConfig.getString(\"item.minecraft.iron_hoe\", \"Iron Hoe\")));\n itemNames.add(new ItemName(Material.DIAMOND_HOE, langConfig.getString(\"item.minecraft.diamond_hoe\", \"Diamond Hoe\")));\n itemNames.add(new ItemName(Material.GOLDEN_HOE, langConfig.getString(\"item.minecraft.golden_hoe\", \"Golden Hoe\")));\n itemNames.add(new ItemName(Material.WHEAT_SEEDS, langConfig.getString(\"item.minecraft.wheat_seeds\", \"Wheat Seeds\")));\n itemNames.add(new ItemName(Material.PUMPKIN_SEEDS, langConfig.getString(\"item.minecraft.pumpkin_seeds\", \"Pumpkin Seeds\")));\n itemNames.add(new ItemName(Material.MELON_SEEDS, langConfig.getString(\"item.minecraft.melon_seeds\", \"Melon Seeds\")));\n itemNames.add(new ItemName(Material.MELON_SLICE, langConfig.getString(\"item.minecraft.melon_slice\", \"Melon Slice\")));\n itemNames.add(new ItemName(Material.WHEAT, langConfig.getString(\"item.minecraft.wheat\", \"Wheat\")));\n itemNames.add(new ItemName(Material.BREAD, langConfig.getString(\"item.minecraft.bread\", \"Bread\")));\n itemNames.add(new ItemName(Material.LEATHER_HELMET, langConfig.getString(\"item.minecraft.leather_helmet\", \"Leather Cap\")));\n itemNames.add(new ItemName(Material.LEATHER_CHESTPLATE, langConfig.getString(\"item.minecraft.leather_chestplate\", \"Leather Tunic\")));\n itemNames.add(new ItemName(Material.LEATHER_LEGGINGS, langConfig.getString(\"item.minecraft.leather_leggings\", \"Leather Pants\")));\n itemNames.add(new ItemName(Material.LEATHER_BOOTS, langConfig.getString(\"item.minecraft.leather_boots\", \"Leather Boots\")));\n itemNames.add(new ItemName(Material.CHAINMAIL_HELMET, langConfig.getString(\"item.minecraft.chainmail_helmet\", \"Chainmail Helmet\")));\n itemNames.add(new ItemName(Material.CHAINMAIL_CHESTPLATE, langConfig.getString(\"item.minecraft.chainmail_chestplate\", \"Chainmail Chestplate\")));\n itemNames.add(new ItemName(Material.CHAINMAIL_LEGGINGS, langConfig.getString(\"item.minecraft.chainmail_leggings\", \"Chainmail Leggings\")));\n itemNames.add(new ItemName(Material.CHAINMAIL_BOOTS, langConfig.getString(\"item.minecraft.chainmail_boots\", \"Chainmail Boots\")));\n itemNames.add(new ItemName(Material.IRON_HELMET, langConfig.getString(\"item.minecraft.iron_helmet\", \"Iron Helmet\")));\n itemNames.add(new ItemName(Material.IRON_CHESTPLATE, langConfig.getString(\"item.minecraft.iron_chestplate\", \"Iron Chestplate\")));\n itemNames.add(new ItemName(Material.IRON_LEGGINGS, langConfig.getString(\"item.minecraft.iron_leggings\", \"Iron Leggings\")));\n itemNames.add(new ItemName(Material.IRON_BOOTS, langConfig.getString(\"item.minecraft.iron_boots\", \"Iron Boots\")));\n itemNames.add(new ItemName(Material.DIAMOND_HELMET, langConfig.getString(\"item.minecraft.diamond_helmet\", \"Diamond Helmet\")));\n itemNames.add(new ItemName(Material.DIAMOND_CHESTPLATE, langConfig.getString(\"item.minecraft.diamond_chestplate\", \"Diamond Chestplate\")));\n itemNames.add(new ItemName(Material.DIAMOND_LEGGINGS, langConfig.getString(\"item.minecraft.diamond_leggings\", \"Diamond Leggings\")));\n itemNames.add(new ItemName(Material.DIAMOND_BOOTS, langConfig.getString(\"item.minecraft.diamond_boots\", \"Diamond Boots\")));\n itemNames.add(new ItemName(Material.GOLDEN_HELMET, langConfig.getString(\"item.minecraft.golden_helmet\", \"Golden Helmet\")));\n itemNames.add(new ItemName(Material.GOLDEN_CHESTPLATE, langConfig.getString(\"item.minecraft.golden_chestplate\", \"Golden Chestplate\")));\n itemNames.add(new ItemName(Material.GOLDEN_LEGGINGS, langConfig.getString(\"item.minecraft.golden_leggings\", \"Golden Leggings\")));\n itemNames.add(new ItemName(Material.GOLDEN_BOOTS, langConfig.getString(\"item.minecraft.golden_boots\", \"Golden Boots\")));\n itemNames.add(new ItemName(Material.FLINT, langConfig.getString(\"item.minecraft.flint\", \"Flint\")));\n itemNames.add(new ItemName(Material.PORKCHOP, langConfig.getString(\"item.minecraft.porkchop\", \"Raw Porkchop\")));\n itemNames.add(new ItemName(Material.COOKED_PORKCHOP, langConfig.getString(\"item.minecraft.cooked_porkchop\", \"Cooked Porkchop\")));\n itemNames.add(new ItemName(Material.CHICKEN, langConfig.getString(\"item.minecraft.chicken\", \"Raw Chicken\")));\n itemNames.add(new ItemName(Material.COOKED_CHICKEN, langConfig.getString(\"item.minecraft.cooked_chicken\", \"Cooked Chicken\")));\n itemNames.add(new ItemName(Material.MUTTON, langConfig.getString(\"item.minecraft.mutton\", \"Raw Mutton\")));\n itemNames.add(new ItemName(Material.COOKED_MUTTON, langConfig.getString(\"item.minecraft.cooked_mutton\", \"Cooked Mutton\")));\n itemNames.add(new ItemName(Material.RABBIT, langConfig.getString(\"item.minecraft.rabbit\", \"Raw Rabbit\")));\n itemNames.add(new ItemName(Material.COOKED_RABBIT, langConfig.getString(\"item.minecraft.cooked_rabbit\", \"Cooked Rabbit\")));\n itemNames.add(new ItemName(Material.RABBIT_STEW, langConfig.getString(\"item.minecraft.rabbit_stew\", \"Rabbit Stew\")));\n itemNames.add(new ItemName(Material.RABBIT_FOOT, langConfig.getString(\"item.minecraft.rabbit_foot\", \"Rabbit's Foot\")));\n itemNames.add(new ItemName(Material.RABBIT_HIDE, langConfig.getString(\"item.minecraft.rabbit_hide\", \"Rabbit Hide\")));\n itemNames.add(new ItemName(Material.BEEF, langConfig.getString(\"item.minecraft.beef\", \"Raw Beef\")));\n itemNames.add(new ItemName(Material.COOKED_BEEF, langConfig.getString(\"item.minecraft.cooked_beef\", \"Steak\")));\n itemNames.add(new ItemName(Material.PAINTING, langConfig.getString(\"item.minecraft.painting\", \"Painting\")));\n itemNames.add(new ItemName(Material.ITEM_FRAME, langConfig.getString(\"item.minecraft.item_frame\", \"Item Frame\")));\n itemNames.add(new ItemName(Material.GOLDEN_APPLE, langConfig.getString(\"item.minecraft.golden_apple\", \"Golden Apple\")));\n itemNames.add(new ItemName(Material.ENCHANTED_GOLDEN_APPLE, langConfig.getString(\"item.minecraft.enchanted_golden_apple\", \"Enchanted Golden Apple\")));\n itemNames.add(new ItemName(Material.BUCKET, langConfig.getString(\"item.minecraft.bucket\", \"Bucket\")));\n itemNames.add(new ItemName(Material.WATER_BUCKET, langConfig.getString(\"item.minecraft.water_bucket\", \"Water Bucket\")));\n itemNames.add(new ItemName(Material.LAVA_BUCKET, langConfig.getString(\"item.minecraft.lava_bucket\", \"Lava Bucket\")));\n itemNames.add(new ItemName(Material.PUFFERFISH_BUCKET, langConfig.getString(\"item.minecraft.pufferfish_bucket\", \"Bucket of Pufferfish\")));\n itemNames.add(new ItemName(Material.SALMON_BUCKET, langConfig.getString(\"item.minecraft.salmon_bucket\", \"Bucket of Salmon\")));\n itemNames.add(new ItemName(Material.COD_BUCKET, langConfig.getString(\"item.minecraft.cod_bucket\", \"Bucket of Cod\")));\n itemNames.add(new ItemName(Material.TROPICAL_FISH_BUCKET, langConfig.getString(\"item.minecraft.tropical_fish_bucket\", \"Bucket of Tropical Fish\")));\n itemNames.add(new ItemName(Material.MINECART, langConfig.getString(\"item.minecraft.minecart\", \"Minecart\")));\n itemNames.add(new ItemName(Material.SADDLE, langConfig.getString(\"item.minecraft.saddle\", \"Saddle\")));\n itemNames.add(new ItemName(Material.REDSTONE, langConfig.getString(\"item.minecraft.redstone\", \"Redstone\")));\n itemNames.add(new ItemName(Material.SNOWBALL, langConfig.getString(\"item.minecraft.snowball\", \"Snowball\")));\n itemNames.add(new ItemName(Material.OAK_BOAT, langConfig.getString(\"item.minecraft.oak_boat\", \"Oak Boat\")));\n itemNames.add(new ItemName(Material.SPRUCE_BOAT, langConfig.getString(\"item.minecraft.spruce_boat\", \"Spruce Boat\")));\n itemNames.add(new ItemName(Material.BIRCH_BOAT, langConfig.getString(\"item.minecraft.birch_boat\", \"Birch Boat\")));\n itemNames.add(new ItemName(Material.JUNGLE_BOAT, langConfig.getString(\"item.minecraft.jungle_boat\", \"Jungle Boat\")));\n itemNames.add(new ItemName(Material.ACACIA_BOAT, langConfig.getString(\"item.minecraft.acacia_boat\", \"Acacia Boat\")));\n itemNames.add(new ItemName(Material.DARK_OAK_BOAT, langConfig.getString(\"item.minecraft.dark_oak_boat\", \"Dark Oak Boat\")));\n itemNames.add(new ItemName(Material.LEATHER, langConfig.getString(\"item.minecraft.leather\", \"Leather\")));\n itemNames.add(new ItemName(Material.MILK_BUCKET, langConfig.getString(\"item.minecraft.milk_bucket\", \"Milk Bucket\")));\n itemNames.add(new ItemName(Material.BRICK, langConfig.getString(\"item.minecraft.brick\", \"Brick\")));\n itemNames.add(new ItemName(Material.CLAY, langConfig.getString(\"item.minecraft.clay_ball\", \"Clay\")));\n itemNames.add(new ItemName(Material.PAPER, langConfig.getString(\"item.minecraft.paper\", \"Paper\")));\n itemNames.add(new ItemName(Material.BOOK, langConfig.getString(\"item.minecraft.book\", \"Book\")));\n itemNames.add(new ItemName(Material.SLIME_BALL, langConfig.getString(\"item.minecraft.slime_ball\", \"Slimeball\")));\n itemNames.add(new ItemName(Material.CHEST_MINECART, langConfig.getString(\"item.minecraft.chest_minecart\", \"Minecart with Chest\")));\n itemNames.add(new ItemName(Material.FURNACE_MINECART, langConfig.getString(\"item.minecraft.furnace_minecart\", \"Minecart with Furnace\")));\n itemNames.add(new ItemName(Material.TNT_MINECART, langConfig.getString(\"item.minecraft.tnt_minecart\", \"Minecart with TNT\")));\n itemNames.add(new ItemName(Material.HOPPER_MINECART, langConfig.getString(\"item.minecraft.hopper_minecart\", \"Minecart with Hopper\")));\n itemNames.add(new ItemName(Material.COMMAND_BLOCK_MINECART, langConfig.getString(\"item.minecraft.command_block_minecart\", \"Minecart with Command Block\")));\n itemNames.add(new ItemName(Material.EGG, langConfig.getString(\"item.minecraft.egg\", \"Egg\")));\n itemNames.add(new ItemName(Material.COMPASS, langConfig.getString(\"item.minecraft.compass\", \"Compass\")));\n itemNames.add(new ItemName(Material.FISHING_ROD, langConfig.getString(\"item.minecraft.fishing_rod\", \"Fishing Rod\")));\n itemNames.add(new ItemName(Material.CLOCK, langConfig.getString(\"item.minecraft.clock\", \"Clock\")));\n itemNames.add(new ItemName(Material.GLOWSTONE_DUST, langConfig.getString(\"item.minecraft.glowstone_dust\", \"Glowstone Dust\")));\n itemNames.add(new ItemName(Material.COD, langConfig.getString(\"item.minecraft.cod\", \"Raw Cod\")));\n itemNames.add(new ItemName(Material.SALMON, langConfig.getString(\"item.minecraft.salmon\", \"Raw Salmon\")));\n itemNames.add(new ItemName(Material.PUFFERFISH, langConfig.getString(\"item.minecraft.pufferfish\", \"Pufferfish\")));\n itemNames.add(new ItemName(Material.TROPICAL_FISH, langConfig.getString(\"item.minecraft.tropical_fish\", \"Tropical Fish\")));\n itemNames.add(new ItemName(Material.COOKED_COD, langConfig.getString(\"item.minecraft.cooked_cod\", \"Cooked Cod\")));\n itemNames.add(new ItemName(Material.COOKED_SALMON, langConfig.getString(\"item.minecraft.cooked_salmon\", \"Cooked Salmon\")));\n itemNames.add(new ItemName(Material.MUSIC_DISC_13, langConfig.getString(\"item.minecraft.music_disc_13\", \"Music Disc\")));\n itemNames.add(new ItemName(Material.MUSIC_DISC_CAT, langConfig.getString(\"item.minecraft.music_disc_cat\", \"Music Disc\")));\n itemNames.add(new ItemName(Material.MUSIC_DISC_BLOCKS, langConfig.getString(\"item.minecraft.music_disc_blocks\", \"Music Disc\")));\n itemNames.add(new ItemName(Material.MUSIC_DISC_CHIRP, langConfig.getString(\"item.minecraft.music_disc_chirp\", \"Music Disc\")));\n itemNames.add(new ItemName(Material.MUSIC_DISC_FAR, langConfig.getString(\"item.minecraft.music_disc_far\", \"Music Disc\")));\n itemNames.add(new ItemName(Material.MUSIC_DISC_MALL, langConfig.getString(\"item.minecraft.music_disc_mall\", \"Music Disc\")));\n itemNames.add(new ItemName(Material.MUSIC_DISC_MELLOHI, langConfig.getString(\"item.minecraft.music_disc_mellohi\", \"Music Disc\")));\n itemNames.add(new ItemName(Material.MUSIC_DISC_STAL, langConfig.getString(\"item.minecraft.music_disc_stal\", \"Music Disc\")));\n itemNames.add(new ItemName(Material.MUSIC_DISC_STRAD, langConfig.getString(\"item.minecraft.music_disc_strad\", \"Music Disc\")));\n itemNames.add(new ItemName(Material.MUSIC_DISC_WARD, langConfig.getString(\"item.minecraft.music_disc_ward\", \"Music Disc\")));\n itemNames.add(new ItemName(Material.MUSIC_DISC_11, langConfig.getString(\"item.minecraft.music_disc_11\", \"Music Disc\")));\n itemNames.add(new ItemName(Material.MUSIC_DISC_WAIT, langConfig.getString(\"item.minecraft.music_disc_wait\", \"Music Disc\")));\n itemNames.add(new ItemName(Material.BONE, langConfig.getString(\"item.minecraft.bone\", \"Bone\")));\n itemNames.add(new ItemName(Material.INK_SAC, langConfig.getString(\"item.minecraft.ink_sac\", \"Ink Sac\")));\n itemNames.add(new ItemName(Material.COCOA_BEANS, langConfig.getString(\"item.minecraft.cocoa_beans\", \"Cocoa Beans\")));\n itemNames.add(new ItemName(Material.LAPIS_LAZULI, langConfig.getString(\"item.minecraft.lapis_lazuli\", \"Lapis Lazuli\")));\n itemNames.add(new ItemName(Material.PURPLE_DYE, langConfig.getString(\"item.minecraft.purple_dye\", \"Purple Dye\")));\n itemNames.add(new ItemName(Material.CYAN_DYE, langConfig.getString(\"item.minecraft.cyan_dye\", \"Cyan Dye\")));\n itemNames.add(new ItemName(Material.LIGHT_GRAY_DYE, langConfig.getString(\"item.minecraft.light_gray_dye\", \"Light Gray Dye\")));\n itemNames.add(new ItemName(Material.GRAY_DYE, langConfig.getString(\"item.minecraft.gray_dye\", \"Gray Dye\")));\n itemNames.add(new ItemName(Material.PINK_DYE, langConfig.getString(\"item.minecraft.pink_dye\", \"Pink Dye\")));\n itemNames.add(new ItemName(Material.LIME_DYE, langConfig.getString(\"item.minecraft.lime_dye\", \"Lime Dye\")));\n itemNames.add(new ItemName(Material.LIGHT_BLUE_DYE, langConfig.getString(\"item.minecraft.light_blue_dye\", \"Light Blue Dye\")));\n itemNames.add(new ItemName(Material.MAGENTA_DYE, langConfig.getString(\"item.minecraft.magenta_dye\", \"Magenta Dye\")));\n itemNames.add(new ItemName(Material.ORANGE_DYE, langConfig.getString(\"item.minecraft.orange_dye\", \"Orange Dye\")));\n itemNames.add(new ItemName(Material.BONE_MEAL, langConfig.getString(\"item.minecraft.bone_meal\", \"Bone Meal\")));\n itemNames.add(new ItemName(Material.SUGAR, langConfig.getString(\"item.minecraft.sugar\", \"Sugar\")));\n itemNames.add(new ItemName(Material.BLACK_BED, langConfig.getString(\"block.minecraft.black_bed\", \"Black Bed\")));\n itemNames.add(new ItemName(Material.RED_BED, langConfig.getString(\"block.minecraft.red_bed\", \"Red Bed\")));\n itemNames.add(new ItemName(Material.GREEN_BED, langConfig.getString(\"block.minecraft.green_bed\", \"Green Bed\")));\n itemNames.add(new ItemName(Material.BROWN_BED, langConfig.getString(\"block.minecraft.brown_bed\", \"Brown Bed\")));\n itemNames.add(new ItemName(Material.BLUE_BED, langConfig.getString(\"block.minecraft.blue_bed\", \"Blue Bed\")));\n itemNames.add(new ItemName(Material.PURPLE_BED, langConfig.getString(\"block.minecraft.purple_bed\", \"Purple Bed\")));\n itemNames.add(new ItemName(Material.CYAN_BED, langConfig.getString(\"block.minecraft.cyan_bed\", \"Cyan Bed\")));\n itemNames.add(new ItemName(Material.LIGHT_GRAY_BED, langConfig.getString(\"block.minecraft.light_gray_bed\", \"Light Gray Bed\")));\n itemNames.add(new ItemName(Material.GRAY_BED, langConfig.getString(\"block.minecraft.gray_bed\", \"Gray Bed\")));\n itemNames.add(new ItemName(Material.PINK_BED, langConfig.getString(\"block.minecraft.pink_bed\", \"Pink Bed\")));\n itemNames.add(new ItemName(Material.LIME_BED, langConfig.getString(\"block.minecraft.lime_bed\", \"Lime Bed\")));\n itemNames.add(new ItemName(Material.YELLOW_BED, langConfig.getString(\"block.minecraft.yellow_bed\", \"Yellow Bed\")));\n itemNames.add(new ItemName(Material.LIGHT_BLUE_BED, langConfig.getString(\"block.minecraft.light_blue_bed\", \"Light Blue Bed\")));\n itemNames.add(new ItemName(Material.MAGENTA_BED, langConfig.getString(\"block.minecraft.magenta_bed\", \"Magenta Bed\")));\n itemNames.add(new ItemName(Material.ORANGE_BED, langConfig.getString(\"block.minecraft.orange_bed\", \"Orange Bed\")));\n itemNames.add(new ItemName(Material.WHITE_BED, langConfig.getString(\"block.minecraft.white_bed\", \"White Bed\")));\n itemNames.add(new ItemName(Material.REPEATER, langConfig.getString(\"block.minecraft.repeater\", \"Redstone Repeater\")));\n itemNames.add(new ItemName(Material.COMPARATOR, langConfig.getString(\"block.minecraft.comparator\", \"Redstone Comparator\")));\n itemNames.add(new ItemName(Material.MAP, langConfig.getString(\"item.minecraft.filled_map\", \"Map\")));\n itemNames.add(new ItemName(Material.SHEARS, langConfig.getString(\"item.minecraft.shears\", \"Shears\")));\n itemNames.add(new ItemName(Material.ROTTEN_FLESH, langConfig.getString(\"item.minecraft.rotten_flesh\", \"Rotten Flesh\")));\n itemNames.add(new ItemName(Material.ENDER_PEARL, langConfig.getString(\"item.minecraft.ender_pearl\", \"Ender Pearl\")));\n itemNames.add(new ItemName(Material.BLAZE_ROD, langConfig.getString(\"item.minecraft.blaze_rod\", \"Blaze Rod\")));\n itemNames.add(new ItemName(Material.GHAST_TEAR, langConfig.getString(\"item.minecraft.ghast_tear\", \"Ghast Tear\")));\n itemNames.add(new ItemName(Material.NETHER_WART, langConfig.getString(\"item.minecraft.nether_wart\", \"Nether Wart\")));\n itemNames.add(new ItemName(Material.POTION, langConfig.getString(\"item.minecraft.potion\", \"Potion\")));\n itemNames.add(new ItemName(Material.SPLASH_POTION, langConfig.getString(\"item.minecraft.splash_potion\", \"Splash Potion\")));\n itemNames.add(new ItemName(Material.LINGERING_POTION, langConfig.getString(\"item.minecraft.lingering_potion\", \"Lingering Potion\")));\n itemNames.add(new ItemName(Material.END_CRYSTAL, langConfig.getString(\"item.minecraft.end_crystal\", \"End Crystal\")));\n itemNames.add(new ItemName(Material.GOLD_NUGGET, langConfig.getString(\"item.minecraft.gold_nugget\", \"Gold Nugget\")));\n itemNames.add(new ItemName(Material.GLASS_BOTTLE, langConfig.getString(\"item.minecraft.glass_bottle\", \"Glass Bottle\")));\n itemNames.add(new ItemName(Material.SPIDER_EYE, langConfig.getString(\"item.minecraft.spider_eye\", \"Spider Eye\")));\n itemNames.add(new ItemName(Material.FERMENTED_SPIDER_EYE, langConfig.getString(\"item.minecraft.fermented_spider_eye\", \"Fermented Spider Eye\")));\n itemNames.add(new ItemName(Material.BLAZE_POWDER, langConfig.getString(\"item.minecraft.blaze_powder\", \"Blaze Powder\")));\n itemNames.add(new ItemName(Material.MAGMA_CREAM, langConfig.getString(\"item.minecraft.magma_cream\", \"Magma Cream\")));\n itemNames.add(new ItemName(Material.CAULDRON, langConfig.getString(\"item.minecraft.cauldron\", \"Cauldron\")));\n itemNames.add(new ItemName(Material.BREWING_STAND, langConfig.getString(\"item.minecraft.brewing_stand\", \"Brewing Stand\")));\n itemNames.add(new ItemName(Material.ENDER_EYE, langConfig.getString(\"item.minecraft.ender_eye\", \"Eye of Ender\")));\n itemNames.add(new ItemName(Material.GLISTERING_MELON_SLICE, langConfig.getString(\"item.minecraft.glistering_melon_slice\", \"Glistering Melon Slice\")));\n itemNames.add(new ItemName(Material.BAT_SPAWN_EGG, langConfig.getString(\"item.minecraft.bat_spawn_egg\", \"Bat Spawn Egg\")));\n itemNames.add(new ItemName(Material.BLAZE_SPAWN_EGG, langConfig.getString(\"item.minecraft.blaze_spawn_egg\", \"Blaze Spawn Egg\")));\n itemNames.add(new ItemName(Material.CAVE_SPIDER_SPAWN_EGG, langConfig.getString(\"item.minecraft.cave_spider_spawn_egg\", \"Cave Spider Spawn Egg\")));\n itemNames.add(new ItemName(Material.CHICKEN_SPAWN_EGG, langConfig.getString(\"item.minecraft.chicken_spawn_egg\", \"Chicken Spawn Egg\")));\n itemNames.add(new ItemName(Material.COD_SPAWN_EGG, langConfig.getString(\"item.minecraft.cod_spawn_egg\", \"Cod Spawn Egg\")));\n itemNames.add(new ItemName(Material.COW_SPAWN_EGG, langConfig.getString(\"item.minecraft.cow_spawn_egg\", \"Cow Spawn Egg\")));\n itemNames.add(new ItemName(Material.CREEPER_SPAWN_EGG, langConfig.getString(\"item.minecraft.creeper_spawn_egg\", \"Creeper Spawn Egg\")));\n itemNames.add(new ItemName(Material.DOLPHIN_SPAWN_EGG, langConfig.getString(\"item.minecraft.dolphin_spawn_egg\", \"Dolphin Spawn Egg\")));\n itemNames.add(new ItemName(Material.DONKEY_SPAWN_EGG, langConfig.getString(\"item.minecraft.donkey_spawn_egg\", \"Donkey Spawn Egg\")));\n itemNames.add(new ItemName(Material.DROWNED_SPAWN_EGG, langConfig.getString(\"item.minecraft.drowned_spawn_egg\", \"Drowned Spawn Egg\")));\n itemNames.add(new ItemName(Material.ELDER_GUARDIAN_SPAWN_EGG, langConfig.getString(\"item.minecraft.elder_guardian_spawn_egg\", \"Elder Guardian Spawn Egg\")));\n itemNames.add(new ItemName(Material.ENDERMAN_SPAWN_EGG, langConfig.getString(\"item.minecraft.enderman_spawn_egg\", \"Enderman Spawn Egg\")));\n itemNames.add(new ItemName(Material.ENDERMITE_SPAWN_EGG, langConfig.getString(\"item.minecraft.endermite_spawn_egg\", \"Endermite Spawn Egg\")));\n itemNames.add(new ItemName(Material.EVOKER_SPAWN_EGG, langConfig.getString(\"item.minecraft.evoker_spawn_egg\", \"Evoker Spawn Egg\")));\n itemNames.add(new ItemName(Material.GHAST_SPAWN_EGG, langConfig.getString(\"item.minecraft.ghast_spawn_egg\", \"Ghast Spawn Egg\")));\n itemNames.add(new ItemName(Material.GUARDIAN_SPAWN_EGG, langConfig.getString(\"item.minecraft.guardian_spawn_egg\", \"Guardian Spawn Egg\")));\n itemNames.add(new ItemName(Material.HORSE_SPAWN_EGG, langConfig.getString(\"item.minecraft.horse_spawn_egg\", \"Horse Spawn Egg\")));\n itemNames.add(new ItemName(Material.HUSK_SPAWN_EGG, langConfig.getString(\"item.minecraft.husk_spawn_egg\", \"Husk Spawn Egg\")));\n itemNames.add(new ItemName(Material.LLAMA_SPAWN_EGG, langConfig.getString(\"item.minecraft.llama_spawn_egg\", \"Llama Spawn Egg\")));\n itemNames.add(new ItemName(Material.MAGMA_CUBE_SPAWN_EGG, langConfig.getString(\"item.minecraft.magma_cube_spawn_egg\", \"Magma Cube Spawn Egg\")));\n itemNames.add(new ItemName(Material.MOOSHROOM_SPAWN_EGG, langConfig.getString(\"item.minecraft.mooshroom_spawn_egg\", \"Mooshroom Spawn Egg\")));\n itemNames.add(new ItemName(Material.MULE_SPAWN_EGG, langConfig.getString(\"item.minecraft.mule_spawn_egg\", \"Mule Spawn Egg\")));\n itemNames.add(new ItemName(Material.OCELOT_SPAWN_EGG, langConfig.getString(\"item.minecraft.ocelot_spawn_egg\", \"Ocelot Spawn Egg\")));\n itemNames.add(new ItemName(Material.PARROT_SPAWN_EGG, langConfig.getString(\"item.minecraft.parrot_spawn_egg\", \"Parrot Spawn Egg\")));\n itemNames.add(new ItemName(Material.PIG_SPAWN_EGG, langConfig.getString(\"item.minecraft.pig_spawn_egg\", \"Pig Spawn Egg\")));\n itemNames.add(new ItemName(Material.PHANTOM_SPAWN_EGG, langConfig.getString(\"item.minecraft.phantom_spawn_egg\", \"Phantom Spawn Egg\")));\n itemNames.add(new ItemName(Material.POLAR_BEAR_SPAWN_EGG, langConfig.getString(\"item.minecraft.polar_bear_spawn_egg\", \"Polar Bear Spawn Egg\")));\n itemNames.add(new ItemName(Material.PUFFERFISH_SPAWN_EGG, langConfig.getString(\"item.minecraft.pufferfish_spawn_egg\", \"Pufferfish Spawn Egg\")));\n itemNames.add(new ItemName(Material.RABBIT_SPAWN_EGG, langConfig.getString(\"item.minecraft.rabbit_spawn_egg\", \"Rabbit Spawn Egg\")));\n itemNames.add(new ItemName(Material.SALMON_SPAWN_EGG, langConfig.getString(\"item.minecraft.salmon_spawn_egg\", \"Salmon Spawn Egg\")));\n itemNames.add(new ItemName(Material.SHEEP_SPAWN_EGG, langConfig.getString(\"item.minecraft.sheep_spawn_egg\", \"Sheep Spawn Egg\")));\n itemNames.add(new ItemName(Material.SHULKER_SPAWN_EGG, langConfig.getString(\"item.minecraft.shulker_spawn_egg\", \"Shulker Spawn Egg\")));\n itemNames.add(new ItemName(Material.SILVERFISH_SPAWN_EGG, langConfig.getString(\"item.minecraft.silverfish_spawn_egg\", \"Silverfish Spawn Egg\")));\n itemNames.add(new ItemName(Material.SKELETON_SPAWN_EGG, langConfig.getString(\"item.minecraft.skeleton_spawn_egg\", \"Skeleton Spawn Egg\")));\n itemNames.add(new ItemName(Material.SKELETON_HORSE_SPAWN_EGG, langConfig.getString(\"item.minecraft.skeleton_horse_spawn_egg\", \"Skeleton Horse Spawn Egg\")));\n itemNames.add(new ItemName(Material.SLIME_SPAWN_EGG, langConfig.getString(\"item.minecraft.slime_spawn_egg\", \"Slime Spawn Egg\")));\n itemNames.add(new ItemName(Material.SPIDER_SPAWN_EGG, langConfig.getString(\"item.minecraft.spider_spawn_egg\", \"Spider Spawn Egg\")));\n itemNames.add(new ItemName(Material.SQUID_SPAWN_EGG, langConfig.getString(\"item.minecraft.squid_spawn_egg\", \"Squid Spawn Egg\")));\n itemNames.add(new ItemName(Material.STRAY_SPAWN_EGG, langConfig.getString(\"item.minecraft.stray_spawn_egg\", \"Stray Spawn Egg\")));\n itemNames.add(new ItemName(Material.TROPICAL_FISH_SPAWN_EGG, langConfig.getString(\"item.minecraft.tropical_fish_spawn_egg\", \"Tropical Fish Spawn Egg\")));\n itemNames.add(new ItemName(Material.TURTLE_SPAWN_EGG, langConfig.getString(\"item.minecraft.turtle_spawn_egg\", \"Turtle Spawn Egg\")));\n itemNames.add(new ItemName(Material.VEX_SPAWN_EGG, langConfig.getString(\"item.minecraft.vex_spawn_egg\", \"Vex Spawn Egg\")));\n itemNames.add(new ItemName(Material.VILLAGER_SPAWN_EGG, langConfig.getString(\"item.minecraft.villager_spawn_egg\", \"Villager Spawn Egg\")));\n itemNames.add(new ItemName(Material.VINDICATOR_SPAWN_EGG, langConfig.getString(\"item.minecraft.vindicator_spawn_egg\", \"Vindicator Spawn Egg\")));\n itemNames.add(new ItemName(Material.WITCH_SPAWN_EGG, langConfig.getString(\"item.minecraft.witch_spawn_egg\", \"Witch Spawn Egg\")));\n itemNames.add(new ItemName(Material.WITHER_SKELETON_SPAWN_EGG, langConfig.getString(\"item.minecraft.wither_skeleton_spawn_egg\", \"Wither Skeleton Spawn Egg\")));\n itemNames.add(new ItemName(Material.WOLF_SPAWN_EGG, langConfig.getString(\"item.minecraft.wolf_spawn_egg\", \"Wolf Spawn Egg\")));\n itemNames.add(new ItemName(Material.ZOMBIE_SPAWN_EGG, langConfig.getString(\"item.minecraft.zombie_spawn_egg\", \"Zombie Spawn Egg\")));\n itemNames.add(new ItemName(Material.ZOMBIE_HORSE_SPAWN_EGG, langConfig.getString(\"item.minecraft.zombie_horse_spawn_egg\", \"Zombie Horse Spawn Egg\")));\n itemNames.add(new ItemName(Material.ZOMBIE_VILLAGER_SPAWN_EGG, langConfig.getString(\"item.minecraft.zombie_villager_spawn_egg\", \"Zombie Villager Spawn Egg\")));\n itemNames.add(new ItemName(Material.EXPERIENCE_BOTTLE, langConfig.getString(\"item.minecraft.experience_bottle\", \"Bottle o' Enchanting\")));\n itemNames.add(new ItemName(Material.FIRE_CHARGE, langConfig.getString(\"item.minecraft.fire_charge\", \"Fire Charge\")));\n itemNames.add(new ItemName(Material.WRITABLE_BOOK, langConfig.getString(\"item.minecraft.writable_book\", \"Book and Quill\")));\n itemNames.add(new ItemName(Material.WRITTEN_BOOK, langConfig.getString(\"item.minecraft.written_book\", \"Written Book\")));\n itemNames.add(new ItemName(Material.FLOWER_POT, langConfig.getString(\"item.minecraft.flower_pot\", \"Flower Pot\")));\n itemNames.add(new ItemName(Material.MAP, langConfig.getString(\"item.minecraft.map\", \"Empty Map\")));\n itemNames.add(new ItemName(Material.CARROT, langConfig.getString(\"item.minecraft.carrot\", \"Carrot\")));\n itemNames.add(new ItemName(Material.GOLDEN_CARROT, langConfig.getString(\"item.minecraft.golden_carrot\", \"Golden Carrot\")));\n itemNames.add(new ItemName(Material.POTATO, langConfig.getString(\"item.minecraft.potato\", \"Potato\")));\n itemNames.add(new ItemName(Material.BAKED_POTATO, langConfig.getString(\"item.minecraft.baked_potato\", \"Baked Potato\")));\n itemNames.add(new ItemName(Material.POISONOUS_POTATO, langConfig.getString(\"item.minecraft.poisonous_potato\", \"Poisonous Potato\")));\n itemNames.add(new ItemName(Material.SKELETON_SKULL, langConfig.getString(\"item.minecraft.skeleton_skull\", \"Skeleton Skull\")));\n itemNames.add(new ItemName(Material.WITHER_SKELETON_SKULL, langConfig.getString(\"item.minecraft.wither_skeleton_skull\", \"Wither Skeleton Skull\")));\n itemNames.add(new ItemName(Material.ZOMBIE_HEAD, langConfig.getString(\"item.minecraft.zombie_head\", \"Zombie Head\")));\n itemNames.add(new ItemName(Material.CREEPER_HEAD, langConfig.getString(\"item.minecraft.creeper_head\", \"Creeper Head\")));\n itemNames.add(new ItemName(Material.DRAGON_HEAD, langConfig.getString(\"item.minecraft.dragon_head\", \"Dragon Head\")));\n itemNames.add(new ItemName(Material.CARROT_ON_A_STICK, langConfig.getString(\"item.minecraft.carrot_on_a_stick\", \"Carrot on a Stick\")));\n itemNames.add(new ItemName(Material.NETHER_STAR, langConfig.getString(\"item.minecraft.nether_star\", \"Nether Star\")));\n itemNames.add(new ItemName(Material.PUMPKIN_PIE, langConfig.getString(\"item.minecraft.pumpkin_pie\", \"Pumpkin Pie\")));\n itemNames.add(new ItemName(Material.ENCHANTED_BOOK, langConfig.getString(\"item.minecraft.enchanted_book\", \"Enchanted Book\")));\n itemNames.add(new ItemName(Material.FIREWORK_ROCKET, langConfig.getString(\"item.minecraft.firework_rocket\", \"Firework Rocket\")));\n itemNames.add(new ItemName(Material.FIREWORK_STAR, langConfig.getString(\"item.minecraft.firework_star\", \"Firework Star\")));\n itemNames.add(new ItemName(Material.NETHER_BRICK, langConfig.getString(\"item.minecraft.nether_brick\", \"Nether Brick\")));\n itemNames.add(new ItemName(Material.QUARTZ, langConfig.getString(\"item.minecraft.quartz\", \"Nether Quartz\")));\n itemNames.add(new ItemName(Material.ARMOR_STAND, langConfig.getString(\"item.minecraft.armor_stand\", \"Armor Stand\")));\n itemNames.add(new ItemName(Material.IRON_HORSE_ARMOR, langConfig.getString(\"item.minecraft.iron_horse_armor\", \"Iron Horse Armor\")));\n itemNames.add(new ItemName(Material.GOLDEN_HORSE_ARMOR, langConfig.getString(\"item.minecraft.golden_horse_armor\", \"Golden Horse Armor\")));\n itemNames.add(new ItemName(Material.DIAMOND_HORSE_ARMOR, langConfig.getString(\"item.minecraft.diamond_horse_armor\", \"Diamond Horse Armor\")));\n itemNames.add(new ItemName(Material.PRISMARINE_SHARD, langConfig.getString(\"item.minecraft.prismarine_shard\", \"Prismarine Shard\")));\n itemNames.add(new ItemName(Material.PRISMARINE_CRYSTALS, langConfig.getString(\"item.minecraft.prismarine_crystals\", \"Prismarine Crystals\")));\n itemNames.add(new ItemName(Material.CHORUS_FRUIT, langConfig.getString(\"item.minecraft.chorus_fruit\", \"Chorus Fruit\")));\n itemNames.add(new ItemName(Material.POPPED_CHORUS_FRUIT, langConfig.getString(\"item.minecraft.popped_chorus_fruit\", \"Popped Chorus Fruit\")));\n itemNames.add(new ItemName(Material.BEETROOT, langConfig.getString(\"item.minecraft.beetroot\", \"Beetroot\")));\n itemNames.add(new ItemName(Material.BEETROOT_SEEDS, langConfig.getString(\"item.minecraft.beetroot_seeds\", \"Beetroot Seeds\")));\n itemNames.add(new ItemName(Material.BEETROOT_SOUP, langConfig.getString(\"item.minecraft.beetroot_soup\", \"Beetroot Soup\")));\n itemNames.add(new ItemName(Material.DRAGON_BREATH, langConfig.getString(\"item.minecraft.dragon_breath\", \"Dragon's Breath\")));\n itemNames.add(new ItemName(Material.ELYTRA, langConfig.getString(\"item.minecraft.elytra\", \"Elytra\")));\n itemNames.add(new ItemName(Material.TOTEM_OF_UNDYING, langConfig.getString(\"item.minecraft.totem_of_undying\", \"Totem of Undying\")));\n itemNames.add(new ItemName(Material.SHULKER_SHELL, langConfig.getString(\"item.minecraft.shulker_shell\", \"Shulker Shell\")));\n itemNames.add(new ItemName(Material.IRON_NUGGET, langConfig.getString(\"item.minecraft.iron_nugget\", \"Iron Nugget\")));\n itemNames.add(new ItemName(Material.KNOWLEDGE_BOOK, langConfig.getString(\"item.minecraft.knowledge_book\", \"Knowledge Book\")));\n itemNames.add(new ItemName(Material.DEBUG_STICK, langConfig.getString(\"item.minecraft.debug_stick\", \"Debug Stick\")));\n itemNames.add(new ItemName(Material.TRIDENT, langConfig.getString(\"item.minecraft.trident\", \"Trident\")));\n itemNames.add(new ItemName(Material.SCUTE, langConfig.getString(\"item.minecraft.scute\", \"Scute\")));\n itemNames.add(new ItemName(Material.TURTLE_HELMET, langConfig.getString(\"item.minecraft.turtle_helmet\", \"Turtle Shell\")));\n itemNames.add(new ItemName(Material.PHANTOM_MEMBRANE, langConfig.getString(\"item.minecraft.phantom_membrane\", \"Phantom Membrane\")));\n itemNames.add(new ItemName(Material.NAUTILUS_SHELL, langConfig.getString(\"item.minecraft.nautilus_shell\", \"Nautilus Shell\")));\n itemNames.add(new ItemName(Material.HEART_OF_THE_SEA, langConfig.getString(\"item.minecraft.heart_of_the_sea\", \"Heart of the Sea\")));\n\n if (Utils.getMajorVersion() >= 14) {\n // Add 1.14 item names\n itemNames.add(new ItemName(Material.ACACIA_SIGN, langConfig.getString(\"block.minecraft.acacia_sign\", \"Acacia Sign\")));\n itemNames.add(new ItemName(Material.ACACIA_WALL_SIGN, langConfig.getString(\"block.minecraft.acacia_wall_sign\", \"Acacia Wall Sign\")));\n itemNames.add(new ItemName(Material.ANDESITE_SLAB, langConfig.getString(\"block.minecraft.andesite_slab\", \"Andesite Slab\")));\n itemNames.add(new ItemName(Material.ANDESITE_STAIRS, langConfig.getString(\"block.minecraft.andesite_stairs\", \"Andesite Stairs\")));\n itemNames.add(new ItemName(Material.ANDESITE_WALL, langConfig.getString(\"block.minecraft.andesite_wall\", \"Andesite Wall\")));\n itemNames.add(new ItemName(Material.BAMBOO, langConfig.getString(\"block.minecraft.bamboo\", \"Bamboo\")));\n itemNames.add(new ItemName(Material.BAMBOO_SAPLING, langConfig.getString(\"block.minecraft.bamboo_sapling\", \"Bamboo Sapling\")));\n itemNames.add(new ItemName(Material.BARREL, langConfig.getString(\"block.minecraft.barrel\", \"Barrel\")));\n itemNames.add(new ItemName(Material.BELL, langConfig.getString(\"block.minecraft.bell\", \"Bell\")));\n itemNames.add(new ItemName(Material.BIRCH_SIGN, langConfig.getString(\"block.minecraft.birch_sign\", \"Birch Sign\")));\n itemNames.add(new ItemName(Material.BIRCH_WALL_SIGN, langConfig.getString(\"block.minecraft.birch_wall_sign\", \"Birch Wall Sign\")));\n itemNames.add(new ItemName(Material.BLACK_DYE, langConfig.getString(\"item.minecraft.black_dye\", \"Black Dye\")));\n itemNames.add(new ItemName(Material.BLAST_FURNACE, langConfig.getString(\"block.minecraft.blast_furnace\", \"Blast Furnace\")));\n itemNames.add(new ItemName(Material.BLUE_DYE, langConfig.getString(\"item.minecraft.blue_dye\", \"Blue Dye\")));\n itemNames.add(new ItemName(Material.BRICK_WALL, langConfig.getString(\"block.minecraft.brick_wall\", \"Brick Wall\")));\n itemNames.add(new ItemName(Material.BROWN_DYE, langConfig.getString(\"item.minecraft.brown_dye\", \"Brown Dye\")));\n itemNames.add(new ItemName(Material.CAMPFIRE, langConfig.getString(\"block.minecraft.campfire\", \"Campfire\")));\n itemNames.add(new ItemName(Material.CARTOGRAPHY_TABLE, langConfig.getString(\"block.minecraft.cartography_table\", \"Cartography Table\")));\n itemNames.add(new ItemName(Material.CAT_SPAWN_EGG, langConfig.getString(\"item.minecraft.cat_spawn_egg\", \"Cat Spawn Egg\")));\n itemNames.add(new ItemName(Material.COMPOSTER, langConfig.getString(\"block.minecraft.composter\", \"Composter\")));\n itemNames.add(new ItemName(Material.CORNFLOWER, langConfig.getString(\"block.minecraft.cornflower\", \"Cornflower\")));\n itemNames.add(new ItemName(Material.CREEPER_BANNER_PATTERN, langConfig.getString(\"item.minecraft.creeper_banner_pattern\", \"Banner Pattern\")));\n itemNames.add(new ItemName(Material.CROSSBOW, langConfig.getString(\"item.minecraft.crossbow\", \"Crossbow\")));\n itemNames.add(new ItemName(Material.CUT_RED_SANDSTONE_SLAB, langConfig.getString(\"block.minecraft.cut_red_sandstone_slab\", \"Cut Red Sandstone Slab\")));\n itemNames.add(new ItemName(Material.CUT_SANDSTONE_SLAB, langConfig.getString(\"block.minecraft.cut_sandstone_slab\", \"Cut Sandstone Slab\")));\n itemNames.add(new ItemName(Material.DARK_OAK_SIGN, langConfig.getString(\"block.minecraft.dark_oak_sign\", \"Dark Oak Sign\")));\n itemNames.add(new ItemName(Material.DARK_OAK_WALL_SIGN, langConfig.getString(\"block.minecraft.dark_oak_wall_sign\", \"Dark Oak Wall Sign\")));\n itemNames.add(new ItemName(Material.DEAD_BRAIN_CORAL, langConfig.getString(\"block.minecraft.dead_brain_coral\", \"Dead Brain Coral\")));\n itemNames.add(new ItemName(Material.DEAD_BUBBLE_CORAL, langConfig.getString(\"block.minecraft.dead_bubble_coral\", \"Dead Bubble Coral\")));\n itemNames.add(new ItemName(Material.DEAD_FIRE_CORAL, langConfig.getString(\"block.minecraft.dead_fire_coral\", \"Dead Fire Coral\")));\n itemNames.add(new ItemName(Material.DEAD_HORN_CORAL, langConfig.getString(\"block.minecraft.dead_horn_coral\", \"Dead Horn Coral\")));\n itemNames.add(new ItemName(Material.DEAD_TUBE_CORAL, langConfig.getString(\"block.minecraft.dead_tube_coral\", \"Dead Tube Coral\")));\n itemNames.add(new ItemName(Material.DIORITE_SLAB, langConfig.getString(\"block.minecraft.diorite_slab\", \"Diorite Slab\")));\n itemNames.add(new ItemName(Material.DIORITE_STAIRS, langConfig.getString(\"block.minecraft.diorite_stairs\", \"Diorite Stairs\")));\n itemNames.add(new ItemName(Material.DIORITE_WALL, langConfig.getString(\"block.minecraft.diorite_wall\", \"Diorite Wall\")));\n itemNames.add(new ItemName(Material.END_STONE_BRICK_SLAB, langConfig.getString(\"block.minecraft.end_stone_brick_slab\", \"End Stone Brick Slab\")));\n itemNames.add(new ItemName(Material.END_STONE_BRICK_STAIRS, langConfig.getString(\"block.minecraft.end_stone_brick_stairs\", \"End Stone Brick Stairs\")));\n itemNames.add(new ItemName(Material.END_STONE_BRICK_WALL, langConfig.getString(\"block.minecraft.end_stone_brick_wall\", \"End Stone Brick Wall\")));\n itemNames.add(new ItemName(Material.FLETCHING_TABLE, langConfig.getString(\"block.minecraft.fletching_table\", \"Fletching Table\")));\n itemNames.add(new ItemName(Material.FLOWER_BANNER_PATTERN, langConfig.getString(\"item.minecraft.flower_banner_pattern\", \"Banner Pattern\")));\n itemNames.add(new ItemName(Material.FOX_SPAWN_EGG, langConfig.getString(\"item.minecraft.fox_spawn_egg\", \"Fox Spawn Egg\")));\n itemNames.add(new ItemName(Material.GLOBE_BANNER_PATTERN, langConfig.getString(\"item.minecraft.globe_banner_pattern\", \"Banner Pattern\")));\n itemNames.add(new ItemName(Material.GRANITE_SLAB, langConfig.getString(\"block.minecraft.granite_slab\", \"Granite Slab\")));\n itemNames.add(new ItemName(Material.GRANITE_STAIRS, langConfig.getString(\"block.minecraft.granite_stairs\", \"Granite Stairs\")));\n itemNames.add(new ItemName(Material.GRANITE_WALL, langConfig.getString(\"block.minecraft.granite_wall\", \"Granite Wall\")));\n itemNames.add(new ItemName(Material.GREEN_DYE, langConfig.getString(\"item.minecraft.green_dye\", \"Green Dye\")));\n itemNames.add(new ItemName(Material.GRINDSTONE, langConfig.getString(\"block.minecraft.grindstone\", \"Grindstone\")));\n itemNames.add(new ItemName(Material.JIGSAW, langConfig.getString(\"block.minecraft.jigsaw\", \"Jigsaw\")));\n itemNames.add(new ItemName(Material.JUNGLE_SIGN, langConfig.getString(\"block.minecraft.jungle_sign\", \"Jungle Sign\")));\n itemNames.add(new ItemName(Material.JUNGLE_WALL_SIGN, langConfig.getString(\"block.minecraft.jungle_wall_sign\", \"Jungle Wall Sign\")));\n itemNames.add(new ItemName(Material.LANTERN, langConfig.getString(\"block.minecraft.lantern\", \"Lantern\")));\n itemNames.add(new ItemName(Material.LEATHER_HORSE_ARMOR, langConfig.getString(\"item.minecraft.leather_horse_armor\", \"Leather Horse Armor\")));\n itemNames.add(new ItemName(Material.LECTERN, langConfig.getString(\"block.minecraft.lectern\", \"Lectern\")));\n itemNames.add(new ItemName(Material.LILY_OF_THE_VALLEY, langConfig.getString(\"block.minecraft.lily_of_the_valley\", \"Lily of the Valley\")));\n itemNames.add(new ItemName(Material.LOOM, langConfig.getString(\"block.minecraft.loom\", \"Loom\")));\n itemNames.add(new ItemName(Material.MOJANG_BANNER_PATTERN, langConfig.getString(\"item.minecraft.mojang_banner_pattern\", \"Banner Pattern\")));\n itemNames.add(new ItemName(Material.MOSSY_COBBLESTONE_SLAB, langConfig.getString(\"block.minecraft.mossy_cobblestone_slab\", \"Mossy Cobblestone Slab\")));\n itemNames.add(new ItemName(Material.MOSSY_COBBLESTONE_STAIRS, langConfig.getString(\"block.minecraft.mossy_cobblestone_stairs\", \"Mossy Cobblestone Stairs\")));\n itemNames.add(new ItemName(Material.MOSSY_STONE_BRICK_SLAB, langConfig.getString(\"block.minecraft.mossy_stone_brick_slab\", \"Mossy Stone Brick Slab\")));\n itemNames.add(new ItemName(Material.MOSSY_STONE_BRICK_STAIRS, langConfig.getString(\"block.minecraft.mossy_stone_brick_stairs\", \"Mossy Stone Brick Stairs\")));\n itemNames.add(new ItemName(Material.MOSSY_STONE_BRICK_WALL, langConfig.getString(\"block.minecraft.mossy_stone_brick_wall\", \"Mossy Stone Brick Wall\")));\n itemNames.add(new ItemName(Material.NETHER_BRICK_WALL, langConfig.getString(\"block.minecraft.nether_brick_wall\", \"Nether Brick Wall\")));\n itemNames.add(new ItemName(Material.OAK_SIGN, langConfig.getString(\"block.minecraft.oak_sign\", \"Oak Sign\")));\n itemNames.add(new ItemName(Material.OAK_WALL_SIGN, langConfig.getString(\"block.minecraft.oak_wall_sign\", \"Oak Wall Sign\")));\n itemNames.add(new ItemName(Material.PANDA_SPAWN_EGG, langConfig.getString(\"item.minecraft.panda_spawn_egg\", \"Panda Spawn Egg\")));\n itemNames.add(new ItemName(Material.PILLAGER_SPAWN_EGG, langConfig.getString(\"item.minecraft.pillager_spawn_egg\", \"Pillager Spawn Egg\")));\n itemNames.add(new ItemName(Material.POLISHED_ANDESITE_SLAB, langConfig.getString(\"block.minecraft.polished_andesite_slab\", \"Polished Andesite Slab\")));\n itemNames.add(new ItemName(Material.POLISHED_ANDESITE_STAIRS, langConfig.getString(\"block.minecraft.polished_andesite_stairs\", \"Polished Andesite Stairs\")));\n itemNames.add(new ItemName(Material.POLISHED_DIORITE_SLAB, langConfig.getString(\"block.minecraft.polished_diorite_slab\", \"Polished Diorite Slab\")));\n itemNames.add(new ItemName(Material.POLISHED_DIORITE_STAIRS, langConfig.getString(\"block.minecraft.polished_diorite_stairs\", \"Polished Diorite Stairs\")));\n itemNames.add(new ItemName(Material.POLISHED_GRANITE_SLAB, langConfig.getString(\"block.minecraft.polished_granite_slab\", \"Polished Granite Slab\")));\n itemNames.add(new ItemName(Material.POLISHED_GRANITE_STAIRS, langConfig.getString(\"block.minecraft.polished_granite_stairs\", \"Polished Granite Stairs\")));\n itemNames.add(new ItemName(Material.POTTED_BAMBOO, langConfig.getString(\"block.minecraft.potted_bamboo\", \"Potted Bamboo\")));\n itemNames.add(new ItemName(Material.POTTED_CORNFLOWER, langConfig.getString(\"block.minecraft.potted_cornflower\", \"Potted Cornflower\")));\n itemNames.add(new ItemName(Material.POTTED_LILY_OF_THE_VALLEY, langConfig.getString(\"block.minecraft.potted_lily_of_the_valley\", \"Potted Lily of the Valley\")));\n itemNames.add(new ItemName(Material.POTTED_WITHER_ROSE, langConfig.getString(\"block.minecraft.potted_wither_rose\", \"Potted Wither Rose\")));\n itemNames.add(new ItemName(Material.PRISMARINE_WALL, langConfig.getString(\"block.minecraft.prismarine_wall\", \"Prismarine Wall\")));\n itemNames.add(new ItemName(Material.RAVAGER_SPAWN_EGG, langConfig.getString(\"item.minecraft.ravager_spawn_egg\", \"Ravager Spawn Egg\")));\n itemNames.add(new ItemName(Material.RED_DYE, langConfig.getString(\"item.minecraft.red_dye\", \"Red Dye\")));\n itemNames.add(new ItemName(Material.RED_NETHER_BRICK_SLAB, langConfig.getString(\"block.minecraft.red_nether_brick_slab\", \"Red Nether Brick Slab\")));\n itemNames.add(new ItemName(Material.RED_NETHER_BRICK_STAIRS, langConfig.getString(\"block.minecraft.red_nether_brick_stairs\", \"Red Nether Brick Stairs\")));\n itemNames.add(new ItemName(Material.RED_NETHER_BRICK_WALL, langConfig.getString(\"block.minecraft.red_nether_brick_wall\", \"Red Nether Brick Wall\")));\n itemNames.add(new ItemName(Material.RED_SANDSTONE_WALL, langConfig.getString(\"block.minecraft.red_sandstone_wall\", \"Red Sandstone Wall\")));\n itemNames.add(new ItemName(Material.SANDSTONE_WALL, langConfig.getString(\"block.minecraft.sandstone_wall\", \"Sandstone Wall\")));\n itemNames.add(new ItemName(Material.SCAFFOLDING, langConfig.getString(\"block.minecraft.scaffolding\", \"Scaffolding\")));\n itemNames.add(new ItemName(Material.SKULL_BANNER_PATTERN, langConfig.getString(\"item.minecraft.skull_banner_pattern\", \"Banner Pattern\")));\n itemNames.add(new ItemName(Material.SMITHING_TABLE, langConfig.getString(\"block.minecraft.smithing_table\", \"Smithing Table\")));\n itemNames.add(new ItemName(Material.SMOKER, langConfig.getString(\"block.minecraft.smoker\", \"Smoker\")));\n itemNames.add(new ItemName(Material.SMOOTH_QUARTZ_SLAB, langConfig.getString(\"block.minecraft.smooth_quartz_slab\", \"Smooth Quartz Slab\")));\n itemNames.add(new ItemName(Material.SMOOTH_QUARTZ_STAIRS, langConfig.getString(\"block.minecraft.smooth_quartz_stairs\", \"Smooth Quartz Stairs\")));\n itemNames.add(new ItemName(Material.SMOOTH_RED_SANDSTONE_SLAB, langConfig.getString(\"block.minecraft.smooth_red_sandstone_slab\", \"Smooth Red Sandstone Slab\")));\n itemNames.add(new ItemName(Material.SMOOTH_RED_SANDSTONE_STAIRS, langConfig.getString(\"block.minecraft.smooth_red_sandstone_stairs\", \"Smooth Red Sandstone Stairs\")));\n itemNames.add(new ItemName(Material.SMOOTH_SANDSTONE_SLAB, langConfig.getString(\"block.minecraft.smooth_sandstone_slab\", \"Smooth Sandstone Slab\")));\n itemNames.add(new ItemName(Material.SMOOTH_SANDSTONE_STAIRS, langConfig.getString(\"block.minecraft.smooth_sandstone_stairs\", \"Smooth Sandstone Stairs\")));\n itemNames.add(new ItemName(Material.SMOOTH_STONE_SLAB, langConfig.getString(\"block.minecraft.smooth_stone_slab\", \"Smooth Stone Slab\")));\n itemNames.add(new ItemName(Material.SPRUCE_SIGN, langConfig.getString(\"block.minecraft.spruce_sign\", \"Spruce Sign\")));\n itemNames.add(new ItemName(Material.SPRUCE_WALL_SIGN, langConfig.getString(\"block.minecraft.spruce_wall_sign\", \"Spruce Wall Sign\")));\n itemNames.add(new ItemName(Material.STONE_BRICK_WALL, langConfig.getString(\"block.minecraft.stone_brick_wall\", \"Stone Brick Wall\")));\n itemNames.add(new ItemName(Material.STONECUTTER, langConfig.getString(\"block.minecraft.stonecutter\", \"Stonecutter\")));\n itemNames.add(new ItemName(Material.SUSPICIOUS_STEW, langConfig.getString(\"item.minecraft.suspicious_stew\", \"Suspicious Stew\")));\n itemNames.add(new ItemName(Material.SWEET_BERRIES, langConfig.getString(\"item.minecraft.sweet_berries\", \"Sweet Berries\")));\n itemNames.add(new ItemName(Material.SWEET_BERRY_BUSH, langConfig.getString(\"block.minecraft.sweet_berry_bush\", \"Sweet Berry Bush\")));\n itemNames.add(new ItemName(Material.TRADER_LLAMA_SPAWN_EGG, langConfig.getString(\"item.minecraft.trader_llama_spawn_egg\", \"Trader Llama Spawn Egg\")));\n itemNames.add(new ItemName(Material.WANDERING_TRADER_SPAWN_EGG, langConfig.getString(\"item.minecraft.wandering_trader_spawn_egg\", \"Wandering Trader Spawn Egg\")));\n itemNames.add(new ItemName(Material.WHITE_DYE, langConfig.getString(\"item.minecraft.white_dye\", \"White Dye\")));\n itemNames.add(new ItemName(Material.WITHER_ROSE, langConfig.getString(\"block.minecraft.wither_rose\", \"Wither Rose\")));\n itemNames.add(new ItemName(Material.YELLOW_DYE, langConfig.getString(\"item.minecraft.yellow_dye\", \"Yellow Dye\")));\n } else {\n // Add pre-1.14 item names that don't exist anymore\n itemNames.add(new ItemName(Material.valueOf(\"CACTUS_GREEN\"), langConfig.getString(\"item.minecraft.cactus_green\", \"Cactus Green\")));\n itemNames.add(new ItemName(Material.valueOf(\"DANDELION_YELLOW\"), langConfig.getString(\"item.minecraft.dandelion_yellow\", \"Dandelion Yellow\")));\n itemNames.add(new ItemName(Material.valueOf(\"ROSE_RED\"), langConfig.getString(\"item.minecraft.rose_red\", \"Rose Red\")));\n itemNames.add(new ItemName(Material.valueOf(\"SIGN\"), langConfig.getString(\"item.minecraft.sign\", \"Sign\")));\n itemNames.add(new ItemName(Material.valueOf(\"WALL_SIGN\"), langConfig.getString(\"block.minecraft.wall_sign\", \"Wall Sign\")));\n }\n\n if (Utils.getMajorVersion() >= 15) {\n itemNames.add(new ItemName(Material.BEE_NEST, langConfig.getString(\"block.minecraft.bee_nest\", \"Bee Nest\")));\n itemNames.add(new ItemName(Material.BEE_SPAWN_EGG, langConfig.getString(\"item.minecraft.bee_spawn_egg\", \"Bee Spawn Egg\")));\n itemNames.add(new ItemName(Material.BEEHIVE, langConfig.getString(\"block.minecraft.beehive\", \"Beehive\")));\n itemNames.add(new ItemName(Material.HONEY_BLOCK, langConfig.getString(\"block.minecraft.honey_block\", \"Honey Block\")));\n itemNames.add(new ItemName(Material.HONEY_BOTTLE, langConfig.getString(\"item.minecraft.honey_bottle\", \"Honey Bottle\")));\n itemNames.add(new ItemName(Material.HONEYCOMB, langConfig.getString(\"item.minecraft.honeycomb\", \"Honeycomb\")));\n itemNames.add(new ItemName(Material.HONEYCOMB_BLOCK, langConfig.getString(\"block.minecraft.honeycomb_block\", \"Honeycomb Block\")));\n }\n\n if (Utils.getMajorVersion() >= 16) {\n itemNames.add(new ItemName(Material.ANCIENT_DEBRIS, langConfig.getString(\"block.minecraft.ancient_debris\", \"Ancient Debris\")));\n itemNames.add(new ItemName(Material.BASALT, langConfig.getString(\"block.minecraft.basalt\", \"Basalt\")));\n itemNames.add(new ItemName(Material.BLACKSTONE, langConfig.getString(\"block.minecraft.blackstone\", \"Blackstone\")));\n itemNames.add(new ItemName(Material.BLACKSTONE_SLAB, langConfig.getString(\"block.minecraft.blackstone_slab\", \"Blackstone Slab\")));\n itemNames.add(new ItemName(Material.BLACKSTONE_STAIRS, langConfig.getString(\"block.minecraft.blackstone_stairs\", \"Blackstone Stairs\")));\n itemNames.add(new ItemName(Material.BLACKSTONE_WALL, langConfig.getString(\"block.minecraft.blackstone_wall\", \"Blackstone Wall\")));\n itemNames.add(new ItemName(Material.CHAIN, langConfig.getString(\"block.minecraft.chain\", \"Chain\")));\n itemNames.add(new ItemName(Material.CHISELED_NETHER_BRICKS, langConfig.getString(\"block.minecraft.chiseled_nether_bricks\", \"Chiseled Nether Bricks\")));\n itemNames.add(new ItemName(Material.CHISELED_POLISHED_BLACKSTONE, langConfig.getString(\"block.minecraft.chiseled_polished_blackstone\", \"Chiseled Polished Blackstone\")));\n itemNames.add(new ItemName(Material.CRACKED_NETHER_BRICKS, langConfig.getString(\"block.minecraft.cracked_nether_bricks\", \"Cracked Nether Bricks\")));\n itemNames.add(new ItemName(Material.CRACKED_POLISHED_BLACKSTONE_BRICKS, langConfig.getString(\"block.minecraft.cracked_polished_blackstone_bricks\", \"Cracked Polished Blackstone Bricks\")));\n itemNames.add(new ItemName(Material.CRIMSON_BUTTON, langConfig.getString(\"block.minecraft.crimson_button\", \"Crimson Button\")));\n itemNames.add(new ItemName(Material.CRIMSON_DOOR, langConfig.getString(\"block.minecraft.crimson_door\", \"Crimson Door\")));\n itemNames.add(new ItemName(Material.CRIMSON_FENCE, langConfig.getString(\"block.minecraft.crimson_fence\", \"Crimson Fence\")));\n itemNames.add(new ItemName(Material.CRIMSON_FENCE_GATE, langConfig.getString(\"block.minecraft.crimson_fence_gate\", \"Crimson Fence Gate\")));\n itemNames.add(new ItemName(Material.CRIMSON_FUNGUS, langConfig.getString(\"block.minecraft.crimson_fungus\", \"Crimson Fungus\")));\n itemNames.add(new ItemName(Material.CRIMSON_HYPHAE, langConfig.getString(\"block.minecraft.crimson_hyphae\", \"Crimson Hyphae\")));\n itemNames.add(new ItemName(Material.CRIMSON_NYLIUM, langConfig.getString(\"block.minecraft.crimson_nylium\", \"Crimson Nylium\")));\n itemNames.add(new ItemName(Material.CRIMSON_PLANKS, langConfig.getString(\"block.minecraft.crimson_planks\", \"Crimson Planks\")));\n itemNames.add(new ItemName(Material.CRIMSON_PRESSURE_PLATE, langConfig.getString(\"block.minecraft.crimson_pressure_plate\", \"Crimson Pressure Plate\")));\n itemNames.add(new ItemName(Material.CRIMSON_ROOTS, langConfig.getString(\"block.minecraft.crimson_roots\", \"Crimson Roots\")));\n itemNames.add(new ItemName(Material.CRIMSON_SIGN, langConfig.getString(\"block.minecraft.crimson_sign\", \"Crimson Sign\")));\n itemNames.add(new ItemName(Material.CRIMSON_SLAB, langConfig.getString(\"block.minecraft.crimson_slab\", \"Crimson Slab\")));\n itemNames.add(new ItemName(Material.CRIMSON_STAIRS, langConfig.getString(\"block.minecraft.crimson_stairs\", \"Crimson Stairs\")));\n itemNames.add(new ItemName(Material.CRIMSON_STEM, langConfig.getString(\"block.minecraft.crimson_stem\", \"Crimson Stem\")));\n itemNames.add(new ItemName(Material.CRIMSON_TRAPDOOR, langConfig.getString(\"block.minecraft.crimson_trapdoor\", \"Crimson Trapdoor\")));\n itemNames.add(new ItemName(Material.CRIMSON_WALL_SIGN, langConfig.getString(\"block.minecraft.crimson_wall_sign\", \"Crimson Wall Sign\")));\n itemNames.add(new ItemName(Material.CRYING_OBSIDIAN, langConfig.getString(\"block.minecraft.crying_obsidian\", \"Crying Obsidian\")));\n itemNames.add(new ItemName(Material.GILDED_BLACKSTONE, langConfig.getString(\"block.minecraft.gilded_blackstone\", \"Gilded Blackstone\")));\n itemNames.add(new ItemName(Material.HOGLIN_SPAWN_EGG, langConfig.getString(\"item.minecraft.hoglin_spawn_egg\", \"Hoglin Spawn Egg\")));\n itemNames.add(new ItemName(Material.LODESTONE, langConfig.getString(\"block.minecraft.lodestone\", \"Lodestone\")));\n // itemNames.add(new ItemName(Material.LODESTONE_COMPASS, langConfig.getString(\"item.minecraft.lodestone_compass\", \"Lodestone Compass\")));\n itemNames.add(new ItemName(Material.MUSIC_DISC_PIGSTEP, langConfig.getString(\"item.minecraft.music_disc_pigstep\", \"Music Disc\")));\n itemNames.add(new ItemName(Material.NETHER_GOLD_ORE, langConfig.getString(\"block.minecraft.nether_gold_ore\", \"Nether Gold Ore\")));\n itemNames.add(new ItemName(Material.NETHER_SPROUTS, langConfig.getString(\"block.minecraft.nether_sprouts\", \"Nether Sprouts\")));\n itemNames.add(new ItemName(Material.NETHERITE_AXE, langConfig.getString(\"item.minecraft.netherite_axe\", \"Netherite Axe\")));\n itemNames.add(new ItemName(Material.NETHERITE_BLOCK, langConfig.getString(\"block.minecraft.netherite_block\", \"Netherite Block\")));\n itemNames.add(new ItemName(Material.NETHERITE_BOOTS, langConfig.getString(\"item.minecraft.netherite_boots\", \"Netherite Boots\")));\n itemNames.add(new ItemName(Material.NETHERITE_CHESTPLATE, langConfig.getString(\"item.minecraft.netherite_chestplate\", \"Netherite Chestplate\")));\n itemNames.add(new ItemName(Material.NETHERITE_HELMET, langConfig.getString(\"item.minecraft.netherite_helmet\", \"Netherite Helmet\")));\n itemNames.add(new ItemName(Material.NETHERITE_HOE, langConfig.getString(\"item.minecraft.netherite_hoe\", \"Netherite Hoe\")));\n itemNames.add(new ItemName(Material.NETHERITE_INGOT, langConfig.getString(\"item.minecraft.netherite_ingot\", \"Netherite Ingot\")));\n itemNames.add(new ItemName(Material.NETHERITE_LEGGINGS, langConfig.getString(\"item.minecraft.netherite_leggings\", \"Netherite Leggings\")));\n itemNames.add(new ItemName(Material.NETHERITE_PICKAXE, langConfig.getString(\"item.minecraft.netherite_pickaxe\", \"Netherite Pickaxe\")));\n itemNames.add(new ItemName(Material.NETHERITE_SCRAP, langConfig.getString(\"item.minecraft.netherite_scrap\", \"Netherite Scrap\")));\n itemNames.add(new ItemName(Material.NETHERITE_SHOVEL, langConfig.getString(\"item.minecraft.netherite_shovel\", \"Netherite Shovel\")));\n itemNames.add(new ItemName(Material.NETHERITE_SWORD, langConfig.getString(\"item.minecraft.netherite_sword\", \"Netherite Sword\")));\n itemNames.add(new ItemName(Material.PIGLIN_SPAWN_EGG, langConfig.getString(\"item.minecraft.piglin_spawn_egg\", \"Piglin Spawn Egg\")));\n itemNames.add(new ItemName(Material.POLISHED_BASALT, langConfig.getString(\"block.minecraft.polished_basalt\", \"Polished Basalt\")));\n itemNames.add(new ItemName(Material.POLISHED_BLACKSTONE, langConfig.getString(\"block.minecraft.polished_blackstone\", \"Polished Blackstone\")));\n itemNames.add(new ItemName(Material.POLISHED_BLACKSTONE_BRICK_SLAB, langConfig.getString(\"block.minecraft.polished_blackstone_brick_slab\", \"Polished Blackstone Brick Slab\")));\n itemNames.add(new ItemName(Material.POLISHED_BLACKSTONE_BRICK_STAIRS, langConfig.getString(\"block.minecraft.polished_blackstone_brick_stairs\", \"Polished Blackstone Brick Stairs\")));\n itemNames.add(new ItemName(Material.POLISHED_BLACKSTONE_BRICK_WALL, langConfig.getString(\"block.minecraft.polished_blackstone_brick_wall\", \"Polished Blackstone Brick Wall\")));\n itemNames.add(new ItemName(Material.POLISHED_BLACKSTONE_BRICKS, langConfig.getString(\"block.minecraft.polished_blackstone_bricks\", \"Polished Blackstone Bricks\")));\n itemNames.add(new ItemName(Material.POLISHED_BLACKSTONE_BUTTON, langConfig.getString(\"block.minecraft.polished_blackstone_button\", \"Polished Blackstone Button\")));\n itemNames.add(new ItemName(Material.POLISHED_BLACKSTONE_PRESSURE_PLATE, langConfig.getString(\"block.minecraft.polished_blackstone_pressure_plate\", \"Polished Blackstone Pressure Plate\")));\n itemNames.add(new ItemName(Material.POLISHED_BLACKSTONE_SLAB, langConfig.getString(\"block.minecraft.polished_blackstone_slab\", \"Polished Blackstone Slab\")));\n itemNames.add(new ItemName(Material.POLISHED_BLACKSTONE_STAIRS, langConfig.getString(\"block.minecraft.polished_blackstone_stairs\", \"Polished Blackstone Stairs\")));\n itemNames.add(new ItemName(Material.POLISHED_BLACKSTONE_WALL, langConfig.getString(\"block.minecraft.polished_blackstone_wall\", \"Polished Blackstone Wall\")));\n itemNames.add(new ItemName(Material.POTTED_CRIMSON_FUNGUS, langConfig.getString(\"block.minecraft.potted_crimson_fungus\", \"Potted Crimson Fungus\")));\n itemNames.add(new ItemName(Material.POTTED_CRIMSON_ROOTS, langConfig.getString(\"block.minecraft.potted_crimson_roots\", \"Potted Crimson Roots\")));\n itemNames.add(new ItemName(Material.POTTED_WARPED_FUNGUS, langConfig.getString(\"block.minecraft.potted_warped_fungus\", \"Potted Warped Fungus\")));\n itemNames.add(new ItemName(Material.POTTED_WARPED_ROOTS, langConfig.getString(\"block.minecraft.potted_warped_roots\", \"Potted Warped Roots\")));\n itemNames.add(new ItemName(Material.QUARTZ_BRICKS, langConfig.getString(\"block.minecraft.quartz_bricks\", \"Quartz Bricks\")));\n itemNames.add(new ItemName(Material.RESPAWN_ANCHOR, langConfig.getString(\"block.minecraft.respawn_anchor\", \"Respawn Anchor\")));\n itemNames.add(new ItemName(Material.SHROOMLIGHT, langConfig.getString(\"block.minecraft.shroomlight\", \"Shroomlight\")));\n itemNames.add(new ItemName(Material.SOUL_CAMPFIRE, langConfig.getString(\"block.minecraft.soul_campfire\", \"Soul Campfire\")));\n itemNames.add(new ItemName(Material.SOUL_FIRE, langConfig.getString(\"block.minecraft.soul_fire\", \"Soul Fire\")));\n itemNames.add(new ItemName(Material.SOUL_LANTERN, langConfig.getString(\"block.minecraft.soul_lantern\", \"Soul Lantern\")));\n itemNames.add(new ItemName(Material.SOUL_SOIL, langConfig.getString(\"block.minecraft.soul_soil\", \"Soul Soil\")));\n itemNames.add(new ItemName(Material.SOUL_TORCH, langConfig.getString(\"block.minecraft.soul_torch\", \"Soul Torch\")));\n itemNames.add(new ItemName(Material.SOUL_WALL_TORCH, langConfig.getString(\"block.minecraft.soul_wall_torch\", \"Soul Wall Torch\")));\n itemNames.add(new ItemName(Material.STRIDER_SPAWN_EGG, langConfig.getString(\"item.minecraft.strider_spawn_egg\", \"Strider Spawn Egg\")));\n itemNames.add(new ItemName(Material.STRIPPED_CRIMSON_HYPHAE, langConfig.getString(\"block.minecraft.stripped_crimson_hyphae\", \"Stripped Crimson Hyphae\")));\n itemNames.add(new ItemName(Material.STRIPPED_CRIMSON_STEM, langConfig.getString(\"block.minecraft.stripped_crimson_stem\", \"Stripped Crimson Stem\")));\n itemNames.add(new ItemName(Material.STRIPPED_WARPED_HYPHAE, langConfig.getString(\"block.minecraft.stripped_warped_hyphae\", \"Stripped Warped Hyphae\")));\n itemNames.add(new ItemName(Material.STRIPPED_WARPED_STEM, langConfig.getString(\"block.minecraft.stripped_warped_stem\", \"Stripped Warped Stem\")));\n itemNames.add(new ItemName(Material.TARGET, langConfig.getString(\"block.minecraft.target\", \"Target\")));\n itemNames.add(new ItemName(Material.TWISTING_VINES, langConfig.getString(\"block.minecraft.twisting_vines\", \"Twisting Vines\")));\n itemNames.add(new ItemName(Material.TWISTING_VINES_PLANT, langConfig.getString(\"block.minecraft.twisting_vines_plant\", \"Twisting Vines Plant\")));\n itemNames.add(new ItemName(Material.WARPED_BUTTON, langConfig.getString(\"block.minecraft.warped_button\", \"Warped Button\")));\n itemNames.add(new ItemName(Material.WARPED_DOOR, langConfig.getString(\"block.minecraft.warped_door\", \"Warped Door\")));\n itemNames.add(new ItemName(Material.WARPED_FENCE, langConfig.getString(\"block.minecraft.warped_fence\", \"Warped Fence\")));\n itemNames.add(new ItemName(Material.WARPED_FENCE_GATE, langConfig.getString(\"block.minecraft.warped_fence_gate\", \"Warped Fence Gate\")));\n itemNames.add(new ItemName(Material.WARPED_FUNGUS, langConfig.getString(\"block.minecraft.warped_fungus\", \"Warped Fungus\")));\n itemNames.add(new ItemName(Material.WARPED_FUNGUS_ON_A_STICK, langConfig.getString(\"item.minecraft.warped_fungus_on_a_stick\", \"Warped Fungus on a Stick\")));\n itemNames.add(new ItemName(Material.WARPED_HYPHAE, langConfig.getString(\"block.minecraft.warped_hyphae\", \"Warped Hyphae\")));\n itemNames.add(new ItemName(Material.WARPED_NYLIUM, langConfig.getString(\"block.minecraft.warped_nylium\", \"Warped Nylium\")));\n itemNames.add(new ItemName(Material.WARPED_PLANKS, langConfig.getString(\"block.minecraft.warped_planks\", \"Warped Planks\")));\n itemNames.add(new ItemName(Material.WARPED_PRESSURE_PLATE, langConfig.getString(\"block.minecraft.warped_pressure_plate\", \"Warped Pressure Plate\")));\n itemNames.add(new ItemName(Material.WARPED_ROOTS, langConfig.getString(\"block.minecraft.warped_roots\", \"Warped Roots\")));\n itemNames.add(new ItemName(Material.WARPED_SIGN, langConfig.getString(\"block.minecraft.warped_sign\", \"Warped Sign\")));\n itemNames.add(new ItemName(Material.WARPED_SLAB, langConfig.getString(\"block.minecraft.warped_slab\", \"Warped Slab\")));\n itemNames.add(new ItemName(Material.WARPED_STAIRS, langConfig.getString(\"block.minecraft.warped_stairs\", \"Warped Stairs\")));\n itemNames.add(new ItemName(Material.WARPED_STEM, langConfig.getString(\"block.minecraft.warped_stem\", \"Warped Stem\")));\n itemNames.add(new ItemName(Material.WARPED_TRAPDOOR, langConfig.getString(\"block.minecraft.warped_trapdoor\", \"Warped Trapdoor\")));\n itemNames.add(new ItemName(Material.WARPED_WALL_SIGN, langConfig.getString(\"block.minecraft.warped_wall_sign\", \"Warped Wall Sign\")));\n itemNames.add(new ItemName(Material.WARPED_WART_BLOCK, langConfig.getString(\"block.minecraft.warped_wart_block\", \"Warped Wart Block\")));\n itemNames.add(new ItemName(Material.WEEPING_VINES, langConfig.getString(\"block.minecraft.weeping_vines\", \"Weeping Vines\")));\n itemNames.add(new ItemName(Material.WEEPING_VINES_PLANT, langConfig.getString(\"block.minecraft.weeping_vines_plant\", \"Weeping Vines Plant\")));\n itemNames.add(new ItemName(Material.ZOGLIN_SPAWN_EGG, langConfig.getString(\"item.minecraft.zoglin_spawn_egg\", \"Zoglin Spawn Egg\")));\n itemNames.add(new ItemName(Material.ZOMBIFIED_PIGLIN_SPAWN_EGG, langConfig.getString(\"item.minecraft.zombified_piglin_spawn_egg\", \"Zombified Piglin Spawn Egg\")));\n\n if (Utils.getMajorVersion() > 16 || Utils.getRevision() >= 2) {\n // Add 1.16.2 item names\n itemNames.add(new ItemName(Material.PIGLIN_BRUTE_SPAWN_EGG, langConfig.getString(\"item.minecraft.piglin_brute_spawn_egg\", \"Piglin Brute Spawn Egg\")));\n }\n } else {\n // Add pre-1.16 item names that don't exist anymore\n itemNames.add(new ItemName(Material.valueOf(\"ZOMBIE_PIGMAN_SPAWN_EGG\"), langConfig.getString(\"item.minecraft.zombie_pigman_spawn_egg\", \"Zombie Pigman Spawn Egg\")));\n }\n\n if (Utils.getMajorVersion() >= 17) {\n itemNames.add(new ItemName(Material.AMETHYST_BLOCK, langConfig.getString(\"block.minecraft.amethyst_block\", \"Block of Amethyst\")));\n itemNames.add(new ItemName(Material.AMETHYST_CLUSTER, langConfig.getString(\"block.minecraft.amethyst_cluster\", \"Amethyst Cluster\")));\n itemNames.add(new ItemName(Material.AZALEA, langConfig.getString(\"block.minecraft.azalea\", \"Azalea\")));\n itemNames.add(new ItemName(Material.AZALEA_LEAVES, langConfig.getString(\"block.minecraft.azalea_leaves\", \"Azalea Leaves\")));\n itemNames.add(new ItemName(Material.BIG_DRIPLEAF, langConfig.getString(\"block.minecraft.big_dripleaf\", \"Big Dripleaf\")));\n itemNames.add(new ItemName(Material.BIG_DRIPLEAF_STEM, langConfig.getString(\"block.minecraft.big_dripleaf_stem\", \"Big Dripleaf Stem\")));\n itemNames.add(new ItemName(Material.BLACK_BANNER, langConfig.getString(\"block.minecraft.black_banner\", \"Black Banner\")));\n itemNames.add(new ItemName(Material.BLACK_CANDLE, langConfig.getString(\"block.minecraft.black_candle\", \"Black Candle\")));\n itemNames.add(new ItemName(Material.BLACK_CANDLE_CAKE, langConfig.getString(\"block.minecraft.black_candle_cake\", \"Cake with Black Candle\")));\n itemNames.add(new ItemName(Material.BLUE_BANNER, langConfig.getString(\"block.minecraft.blue_banner\", \"Blue Banner\")));\n itemNames.add(new ItemName(Material.BLUE_CANDLE, langConfig.getString(\"block.minecraft.blue_candle\", \"Blue Candle\")));\n itemNames.add(new ItemName(Material.BLUE_CANDLE_CAKE, langConfig.getString(\"block.minecraft.blue_candle_cake\", \"Cake with Blue Candle\")));\n itemNames.add(new ItemName(Material.BRAIN_CORAL_WALL_FAN, langConfig.getString(\"block.minecraft.brain_coral_wall_fan\", \"Brain Coral Wall Fan\")));\n itemNames.add(new ItemName(Material.BROWN_BANNER, langConfig.getString(\"block.minecraft.brown_banner\", \"Brown Banner\")));\n itemNames.add(new ItemName(Material.BROWN_CANDLE, langConfig.getString(\"block.minecraft.brown_candle\", \"Brown Candle\")));\n itemNames.add(new ItemName(Material.BROWN_CANDLE_CAKE, langConfig.getString(\"block.minecraft.brown_candle_cake\", \"Cake with Brown Candle\")));\n itemNames.add(new ItemName(Material.BUBBLE_CORAL_WALL_FAN, langConfig.getString(\"block.minecraft.bubble_coral_wall_fan\", \"Bubble Coral Wall Fan\")));\n itemNames.add(new ItemName(Material.BUDDING_AMETHYST, langConfig.getString(\"block.minecraft.budding_amethyst\", \"Budding Amethyst\")));\n itemNames.add(new ItemName(Material.CALCITE, langConfig.getString(\"block.minecraft.calcite\", \"Calcite\")));\n itemNames.add(new ItemName(Material.CANDLE, langConfig.getString(\"block.minecraft.candle\", \"Candle\")));\n itemNames.add(new ItemName(Material.CANDLE_CAKE, langConfig.getString(\"block.minecraft.candle_cake\", \"Cake with Candle\")));\n itemNames.add(new ItemName(Material.CAVE_VINES, langConfig.getString(\"block.minecraft.cave_vines\", \"Cave Vines\")));\n itemNames.add(new ItemName(Material.CAVE_VINES_PLANT, langConfig.getString(\"block.minecraft.cave_vines_plant\", \"Cave Vines Plant\")));\n itemNames.add(new ItemName(Material.CHISELED_DEEPSLATE, langConfig.getString(\"block.minecraft.chiseled_deepslate\", \"Chiseled Deepslate\")));\n itemNames.add(new ItemName(Material.COBBLED_DEEPSLATE, langConfig.getString(\"block.minecraft.cobbled_deepslate\", \"Cobbled Deepslate\")));\n itemNames.add(new ItemName(Material.COBBLED_DEEPSLATE_SLAB, langConfig.getString(\"block.minecraft.cobbled_deepslate_slab\", \"Cobbled Deepslate Slab\")));\n itemNames.add(new ItemName(Material.COBBLED_DEEPSLATE_STAIRS, langConfig.getString(\"block.minecraft.cobbled_deepslate_stairs\", \"Cobbled Deepslate Stairs\")));\n itemNames.add(new ItemName(Material.COBBLED_DEEPSLATE_WALL, langConfig.getString(\"block.minecraft.cobbled_deepslate_wall\", \"Cobbled Deepslate Wall\")));\n itemNames.add(new ItemName(Material.COPPER_BLOCK, langConfig.getString(\"block.minecraft.copper_block\", \"Block of Copper\")));\n itemNames.add(new ItemName(Material.COPPER_ORE, langConfig.getString(\"block.minecraft.copper_ore\", \"Copper Ore\")));\n itemNames.add(new ItemName(Material.CRACKED_DEEPSLATE_BRICKS, langConfig.getString(\"block.minecraft.cracked_deepslate_bricks\", \"Cracked Deepslate Bricks\")));\n itemNames.add(new ItemName(Material.CRACKED_DEEPSLATE_TILES, langConfig.getString(\"block.minecraft.cracked_deepslate_tiles\", \"Cracked Deepslate Tiles\")));\n itemNames.add(new ItemName(Material.CUT_COPPER, langConfig.getString(\"block.minecraft.cut_copper\", \"Cut Copper\")));\n itemNames.add(new ItemName(Material.CUT_COPPER_SLAB, langConfig.getString(\"block.minecraft.cut_copper_slab\", \"Cut Copper Slab\")));\n itemNames.add(new ItemName(Material.CUT_COPPER_STAIRS, langConfig.getString(\"block.minecraft.cut_copper_stairs\", \"Cut Copper Stairs\")));\n itemNames.add(new ItemName(Material.CYAN_BANNER, langConfig.getString(\"block.minecraft.cyan_banner\", \"Cyan Banner\")));\n itemNames.add(new ItemName(Material.CYAN_CANDLE, langConfig.getString(\"block.minecraft.cyan_candle\", \"Cyan Candle\")));\n itemNames.add(new ItemName(Material.CYAN_CANDLE_CAKE, langConfig.getString(\"block.minecraft.cyan_candle_cake\", \"Cake with Cyan Candle\")));\n itemNames.add(new ItemName(Material.DEAD_BRAIN_CORAL_FAN, langConfig.getString(\"block.minecraft.dead_brain_coral_fan\", \"Dead Brain Coral Fan\")));\n itemNames.add(new ItemName(Material.DEAD_BRAIN_CORAL_WALL_FAN, langConfig.getString(\"block.minecraft.dead_brain_coral_wall_fan\", \"Dead Brain Coral Wall Fan\")));\n itemNames.add(new ItemName(Material.DEAD_BUBBLE_CORAL_FAN, langConfig.getString(\"block.minecraft.dead_bubble_coral_fan\", \"Dead Bubble Coral Fan\")));\n itemNames.add(new ItemName(Material.DEAD_BUBBLE_CORAL_WALL_FAN, langConfig.getString(\"block.minecraft.dead_bubble_coral_wall_fan\", \"Dead Bubble Coral Wall Fan\")));\n itemNames.add(new ItemName(Material.DEAD_FIRE_CORAL_FAN, langConfig.getString(\"block.minecraft.dead_fire_coral_fan\", \"Dead Fire Coral Fan\")));\n itemNames.add(new ItemName(Material.DEAD_FIRE_CORAL_WALL_FAN, langConfig.getString(\"block.minecraft.dead_fire_coral_wall_fan\", \"Dead Fire Coral Wall Fan\")));\n itemNames.add(new ItemName(Material.DEAD_HORN_CORAL_FAN, langConfig.getString(\"block.minecraft.dead_horn_coral_fan\", \"Dead Horn Coral Fan\")));\n itemNames.add(new ItemName(Material.DEAD_HORN_CORAL_WALL_FAN, langConfig.getString(\"block.minecraft.dead_horn_coral_wall_fan\", \"Dead Horn Coral Wall Fan\")));\n itemNames.add(new ItemName(Material.DEAD_TUBE_CORAL_FAN, langConfig.getString(\"block.minecraft.dead_tube_coral_fan\", \"Dead Tube Coral Fan\")));\n itemNames.add(new ItemName(Material.DEAD_TUBE_CORAL_WALL_FAN, langConfig.getString(\"block.minecraft.dead_tube_coral_wall_fan\", \"Dead Tube Coral Wall Fan\")));\n itemNames.add(new ItemName(Material.DEEPSLATE, langConfig.getString(\"block.minecraft.deepslate\", \"Deepslate\")));\n itemNames.add(new ItemName(Material.DEEPSLATE_BRICK_SLAB, langConfig.getString(\"block.minecraft.deepslate_brick_slab\", \"Deepslate Brick Slab\")));\n itemNames.add(new ItemName(Material.DEEPSLATE_BRICK_STAIRS, langConfig.getString(\"block.minecraft.deepslate_brick_stairs\", \"Deepslate Brick Stairs\")));\n itemNames.add(new ItemName(Material.DEEPSLATE_BRICK_WALL, langConfig.getString(\"block.minecraft.deepslate_brick_wall\", \"Deepslate Brick Wall\")));\n itemNames.add(new ItemName(Material.DEEPSLATE_BRICKS, langConfig.getString(\"block.minecraft.deepslate_bricks\", \"Deepslate Bricks\")));\n itemNames.add(new ItemName(Material.DEEPSLATE_COAL_ORE, langConfig.getString(\"block.minecraft.deepslate_coal_ore\", \"Deepslate Coal Ore\")));\n itemNames.add(new ItemName(Material.DEEPSLATE_COPPER_ORE, langConfig.getString(\"block.minecraft.deepslate_copper_ore\", \"Deepslate Copper Ore\")));\n itemNames.add(new ItemName(Material.DEEPSLATE_DIAMOND_ORE, langConfig.getString(\"block.minecraft.deepslate_diamond_ore\", \"Deepslate Diamond Ore\")));\n itemNames.add(new ItemName(Material.DEEPSLATE_EMERALD_ORE, langConfig.getString(\"block.minecraft.deepslate_emerald_ore\", \"Deepslate Emerald Ore\")));\n itemNames.add(new ItemName(Material.DEEPSLATE_GOLD_ORE, langConfig.getString(\"block.minecraft.deepslate_gold_ore\", \"Deepslate Gold Ore\")));\n itemNames.add(new ItemName(Material.DEEPSLATE_IRON_ORE, langConfig.getString(\"block.minecraft.deepslate_iron_ore\", \"Deepslate Iron Ore\")));\n itemNames.add(new ItemName(Material.DEEPSLATE_LAPIS_ORE, langConfig.getString(\"block.minecraft.deepslate_lapis_ore\", \"Deepslate Lapis Lazuli Ore\")));\n itemNames.add(new ItemName(Material.DEEPSLATE_REDSTONE_ORE, langConfig.getString(\"block.minecraft.deepslate_redstone_ore\", \"Deepslate Redstone Ore\")));\n itemNames.add(new ItemName(Material.DEEPSLATE_TILE_SLAB, langConfig.getString(\"block.minecraft.deepslate_tile_slab\", \"Deepslate Tile Slab\")));\n itemNames.add(new ItemName(Material.DEEPSLATE_TILE_STAIRS, langConfig.getString(\"block.minecraft.deepslate_tile_stairs\", \"Deepslate Tile Stairs\")));\n itemNames.add(new ItemName(Material.DEEPSLATE_TILE_WALL, langConfig.getString(\"block.minecraft.deepslate_tile_wall\", \"Deepslate Tile Wall\")));\n itemNames.add(new ItemName(Material.DEEPSLATE_TILES, langConfig.getString(\"block.minecraft.deepslate_tiles\", \"Deepslate Tiles\")));\n itemNames.add(new ItemName(Material.DIRT_PATH, langConfig.getString(\"block.minecraft.dirt_path\", \"Dirt Path\")));\n itemNames.add(new ItemName(Material.DRIPSTONE_BLOCK, langConfig.getString(\"block.minecraft.dripstone_block\", \"Dripstone Block\")));\n itemNames.add(new ItemName(Material.EXPOSED_COPPER, langConfig.getString(\"block.minecraft.exposed_copper\", \"Exposed Copper\")));\n itemNames.add(new ItemName(Material.EXPOSED_CUT_COPPER, langConfig.getString(\"block.minecraft.exposed_cut_copper\", \"Exposed Cut Copper\")));\n itemNames.add(new ItemName(Material.EXPOSED_CUT_COPPER_SLAB, langConfig.getString(\"block.minecraft.exposed_cut_copper_slab\", \"Exposed Cut Copper Slab\")));\n itemNames.add(new ItemName(Material.EXPOSED_CUT_COPPER_STAIRS, langConfig.getString(\"block.minecraft.exposed_cut_copper_stairs\", \"Exposed Cut Copper Stairs\")));\n itemNames.add(new ItemName(Material.FIRE_CORAL_WALL_FAN, langConfig.getString(\"block.minecraft.fire_coral_wall_fan\", \"Fire Coral Wall Fan\")));\n itemNames.add(new ItemName(Material.FLOWERING_AZALEA, langConfig.getString(\"block.minecraft.flowering_azalea\", \"Flowering Azalea\")));\n itemNames.add(new ItemName(Material.FLOWERING_AZALEA_LEAVES, langConfig.getString(\"block.minecraft.flowering_azalea_leaves\", \"Flowering Azalea Leaves\")));\n itemNames.add(new ItemName(Material.GLOW_LICHEN, langConfig.getString(\"block.minecraft.glow_lichen\", \"Glow Lichen\")));\n itemNames.add(new ItemName(Material.GRAY_BANNER, langConfig.getString(\"block.minecraft.gray_banner\", \"Gray Banner\")));\n itemNames.add(new ItemName(Material.GRAY_CANDLE, langConfig.getString(\"block.minecraft.gray_candle\", \"Gray Candle\")));\n itemNames.add(new ItemName(Material.GRAY_CANDLE_CAKE, langConfig.getString(\"block.minecraft.gray_candle_cake\", \"Cake with Gray Candle\")));\n itemNames.add(new ItemName(Material.GREEN_BANNER, langConfig.getString(\"block.minecraft.green_banner\", \"Green Banner\")));\n itemNames.add(new ItemName(Material.GREEN_CANDLE, langConfig.getString(\"block.minecraft.green_candle\", \"Green Candle\")));\n itemNames.add(new ItemName(Material.GREEN_CANDLE_CAKE, langConfig.getString(\"block.minecraft.green_candle_cake\", \"Cake with Green Candle\")));\n itemNames.add(new ItemName(Material.HANGING_ROOTS, langConfig.getString(\"block.minecraft.hanging_roots\", \"Hanging Roots\")));\n itemNames.add(new ItemName(Material.HORN_CORAL_WALL_FAN, langConfig.getString(\"block.minecraft.horn_coral_wall_fan\", \"Horn Coral Wall Fan\")));\n itemNames.add(new ItemName(Material.INFESTED_DEEPSLATE, langConfig.getString(\"block.minecraft.infested_deepslate\", \"Infested Deepslate\")));\n itemNames.add(new ItemName(Material.LARGE_AMETHYST_BUD, langConfig.getString(\"block.minecraft.large_amethyst_bud\", \"Large Amethyst Bud\")));\n itemNames.add(new ItemName(Material.LAVA_CAULDRON, langConfig.getString(\"block.minecraft.lava_cauldron\", \"Lava Cauldron\")));\n itemNames.add(new ItemName(Material.LIGHT, langConfig.getString(\"block.minecraft.light\", \"Light\")));\n itemNames.add(new ItemName(Material.LIGHT_BLUE_BANNER, langConfig.getString(\"block.minecraft.light_blue_banner\", \"Light Blue Banner\")));\n itemNames.add(new ItemName(Material.LIGHT_BLUE_CANDLE, langConfig.getString(\"block.minecraft.light_blue_candle\", \"Light Blue Candle\")));\n itemNames.add(new ItemName(Material.LIGHT_BLUE_CANDLE_CAKE, langConfig.getString(\"block.minecraft.light_blue_candle_cake\", \"Cake with Light Blue Candle\")));\n itemNames.add(new ItemName(Material.LIGHT_GRAY_BANNER, langConfig.getString(\"block.minecraft.light_gray_banner\", \"Light Gray Banner\")));\n itemNames.add(new ItemName(Material.LIGHT_GRAY_CANDLE, langConfig.getString(\"block.minecraft.light_gray_candle\", \"Light Gray Candle\")));\n itemNames.add(new ItemName(Material.LIGHT_GRAY_CANDLE_CAKE, langConfig.getString(\"block.minecraft.light_gray_candle_cake\", \"Cake with Light Gray Candle\")));\n itemNames.add(new ItemName(Material.LIGHTNING_ROD, langConfig.getString(\"block.minecraft.lightning_rod\", \"Lightning Rod\")));\n itemNames.add(new ItemName(Material.LIME_BANNER, langConfig.getString(\"block.minecraft.lime_banner\", \"Lime Banner\")));\n itemNames.add(new ItemName(Material.LIME_CANDLE, langConfig.getString(\"block.minecraft.lime_candle\", \"Lime Candle\")));\n itemNames.add(new ItemName(Material.LIME_CANDLE_CAKE, langConfig.getString(\"block.minecraft.lime_candle_cake\", \"Cake with Lime Candle\")));\n itemNames.add(new ItemName(Material.MAGENTA_BANNER, langConfig.getString(\"block.minecraft.magenta_banner\", \"Magenta Banner\")));\n itemNames.add(new ItemName(Material.MAGENTA_CANDLE, langConfig.getString(\"block.minecraft.magenta_candle\", \"Magenta Candle\")));\n itemNames.add(new ItemName(Material.MAGENTA_CANDLE_CAKE, langConfig.getString(\"block.minecraft.magenta_candle_cake\", \"Cake with Magenta Candle\")));\n itemNames.add(new ItemName(Material.MEDIUM_AMETHYST_BUD, langConfig.getString(\"block.minecraft.medium_amethyst_bud\", \"Medium Amethyst Bud\")));\n itemNames.add(new ItemName(Material.MOSS_BLOCK, langConfig.getString(\"block.minecraft.moss_block\", \"Moss Block\")));\n itemNames.add(new ItemName(Material.MOSS_CARPET, langConfig.getString(\"block.minecraft.moss_carpet\", \"Moss Carpet\")));\n itemNames.add(new ItemName(Material.ORANGE_BANNER, langConfig.getString(\"block.minecraft.orange_banner\", \"Orange Banner\")));\n itemNames.add(new ItemName(Material.ORANGE_CANDLE, langConfig.getString(\"block.minecraft.orange_candle\", \"Orange Candle\")));\n itemNames.add(new ItemName(Material.ORANGE_CANDLE_CAKE, langConfig.getString(\"block.minecraft.orange_candle_cake\", \"Cake with Orange Candle\")));\n itemNames.add(new ItemName(Material.OXIDIZED_COPPER, langConfig.getString(\"block.minecraft.oxidized_copper\", \"Oxidized Copper\")));\n itemNames.add(new ItemName(Material.OXIDIZED_CUT_COPPER, langConfig.getString(\"block.minecraft.oxidized_cut_copper\", \"Oxidized Cut Copper\")));\n itemNames.add(new ItemName(Material.OXIDIZED_CUT_COPPER_SLAB, langConfig.getString(\"block.minecraft.oxidized_cut_copper_slab\", \"Oxidized Cut Copper Slab\")));\n itemNames.add(new ItemName(Material.OXIDIZED_CUT_COPPER_STAIRS, langConfig.getString(\"block.minecraft.oxidized_cut_copper_stairs\", \"Oxidized Cut Copper Stairs\")));\n itemNames.add(new ItemName(Material.PINK_BANNER, langConfig.getString(\"block.minecraft.pink_banner\", \"Pink Banner\")));\n itemNames.add(new ItemName(Material.PINK_CANDLE, langConfig.getString(\"block.minecraft.pink_candle\", \"Pink Candle\")));\n itemNames.add(new ItemName(Material.PINK_CANDLE_CAKE, langConfig.getString(\"block.minecraft.pink_candle_cake\", \"Cake with Pink Candle\")));\n itemNames.add(new ItemName(Material.POINTED_DRIPSTONE, langConfig.getString(\"block.minecraft.pointed_dripstone\", \"Pointed Dripstone\")));\n itemNames.add(new ItemName(Material.POLISHED_DEEPSLATE, langConfig.getString(\"block.minecraft.polished_deepslate\", \"Polished Deepslate\")));\n itemNames.add(new ItemName(Material.POLISHED_DEEPSLATE_SLAB, langConfig.getString(\"block.minecraft.polished_deepslate_slab\", \"Polished Deepslate Slab\")));\n itemNames.add(new ItemName(Material.POLISHED_DEEPSLATE_STAIRS, langConfig.getString(\"block.minecraft.polished_deepslate_stairs\", \"Polished Deepslate Stairs\")));\n itemNames.add(new ItemName(Material.POLISHED_DEEPSLATE_WALL, langConfig.getString(\"block.minecraft.polished_deepslate_wall\", \"Polished Deepslate Wall\")));\n itemNames.add(new ItemName(Material.POTTED_AZALEA_BUSH, langConfig.getString(\"block.minecraft.potted_azalea_bush\", \"Potted Azalea Bush\")));\n itemNames.add(new ItemName(Material.POTTED_FLOWERING_AZALEA_BUSH, langConfig.getString(\"block.minecraft.potted_flowering_azalea_bush\", \"Potted Flowering Azalea\")));\n itemNames.add(new ItemName(Material.POWDER_SNOW, langConfig.getString(\"block.minecraft.powder_snow\", \"Powder Snow\")));\n itemNames.add(new ItemName(Material.POWDER_SNOW_CAULDRON, langConfig.getString(\"block.minecraft.powder_snow_cauldron\", \"Powder Snow Cauldron\")));\n itemNames.add(new ItemName(Material.PURPLE_BANNER, langConfig.getString(\"block.minecraft.purple_banner\", \"Purple Banner\")));\n itemNames.add(new ItemName(Material.PURPLE_CANDLE, langConfig.getString(\"block.minecraft.purple_candle\", \"Purple Candle\")));\n itemNames.add(new ItemName(Material.PURPLE_CANDLE_CAKE, langConfig.getString(\"block.minecraft.purple_candle_cake\", \"Cake with Purple Candle\")));\n itemNames.add(new ItemName(Material.RAW_COPPER_BLOCK, langConfig.getString(\"block.minecraft.raw_copper_block\", \"Block of Raw Copper\")));\n itemNames.add(new ItemName(Material.RAW_GOLD_BLOCK, langConfig.getString(\"block.minecraft.raw_gold_block\", \"Block of Raw Gold\")));\n itemNames.add(new ItemName(Material.RAW_IRON_BLOCK, langConfig.getString(\"block.minecraft.raw_iron_block\", \"Block of Raw Iron\")));\n itemNames.add(new ItemName(Material.RED_BANNER, langConfig.getString(\"block.minecraft.red_banner\", \"Red Banner\")));\n itemNames.add(new ItemName(Material.RED_CANDLE, langConfig.getString(\"block.minecraft.red_candle\", \"Red Candle\")));\n itemNames.add(new ItemName(Material.RED_CANDLE_CAKE, langConfig.getString(\"block.minecraft.red_candle_cake\", \"Cake with Red Candle\")));\n itemNames.add(new ItemName(Material.ROOTED_DIRT, langConfig.getString(\"block.minecraft.rooted_dirt\", \"Rooted Dirt\")));\n itemNames.add(new ItemName(Material.SCULK_SENSOR, langConfig.getString(\"block.minecraft.sculk_sensor\", \"Sculk Sensor\")));\n itemNames.add(new ItemName(Material.SMALL_AMETHYST_BUD, langConfig.getString(\"block.minecraft.small_amethyst_bud\", \"Small Amethyst Bud\")));\n itemNames.add(new ItemName(Material.SMALL_DRIPLEAF, langConfig.getString(\"block.minecraft.small_dripleaf\", \"Small Dripleaf\")));\n itemNames.add(new ItemName(Material.SMOOTH_BASALT, langConfig.getString(\"block.minecraft.smooth_basalt\", \"Smooth Basalt\")));\n itemNames.add(new ItemName(Material.SPORE_BLOSSOM, langConfig.getString(\"block.minecraft.spore_blossom\", \"Spore Blossom\")));\n itemNames.add(new ItemName(Material.STONE_STAIRS, langConfig.getString(\"block.minecraft.stone_stairs\", \"Stone Stairs\")));\n itemNames.add(new ItemName(Material.TINTED_GLASS, langConfig.getString(\"block.minecraft.tinted_glass\", \"Tinted Glass\")));\n itemNames.add(new ItemName(Material.TUBE_CORAL_WALL_FAN, langConfig.getString(\"block.minecraft.tube_coral_wall_fan\", \"Tube Coral Wall Fan\")));\n itemNames.add(new ItemName(Material.TUFF, langConfig.getString(\"block.minecraft.tuff\", \"Tuff\")));\n itemNames.add(new ItemName(Material.WATER_CAULDRON, langConfig.getString(\"block.minecraft.water_cauldron\", \"Water Cauldron\")));\n itemNames.add(new ItemName(Material.WAXED_COPPER_BLOCK, langConfig.getString(\"block.minecraft.waxed_copper_block\", \"Waxed Block of Copper\")));\n itemNames.add(new ItemName(Material.WAXED_CUT_COPPER, langConfig.getString(\"block.minecraft.waxed_cut_copper\", \"Waxed Cut Copper\")));\n itemNames.add(new ItemName(Material.WAXED_CUT_COPPER_SLAB, langConfig.getString(\"block.minecraft.waxed_cut_copper_slab\", \"Waxed Cut Copper Slab\")));\n itemNames.add(new ItemName(Material.WAXED_CUT_COPPER_STAIRS, langConfig.getString(\"block.minecraft.waxed_cut_copper_stairs\", \"Waxed Cut Copper Stairs\")));\n itemNames.add(new ItemName(Material.WAXED_EXPOSED_COPPER, langConfig.getString(\"block.minecraft.waxed_exposed_copper\", \"Waxed Exposed Copper\")));\n itemNames.add(new ItemName(Material.WAXED_EXPOSED_CUT_COPPER, langConfig.getString(\"block.minecraft.waxed_exposed_cut_copper\", \"Waxed Exposed Cut Copper\")));\n itemNames.add(new ItemName(Material.WAXED_EXPOSED_CUT_COPPER_SLAB, langConfig.getString(\"block.minecraft.waxed_exposed_cut_copper_slab\", \"Waxed Exposed Cut Copper Slab\")));\n itemNames.add(new ItemName(Material.WAXED_EXPOSED_CUT_COPPER_STAIRS, langConfig.getString(\"block.minecraft.waxed_exposed_cut_copper_stairs\", \"Waxed Exposed Cut Copper Stairs\")));\n itemNames.add(new ItemName(Material.WAXED_OXIDIZED_COPPER, langConfig.getString(\"block.minecraft.waxed_oxidized_copper\", \"Waxed Oxidized Copper\")));\n itemNames.add(new ItemName(Material.WAXED_OXIDIZED_CUT_COPPER, langConfig.getString(\"block.minecraft.waxed_oxidized_cut_copper\", \"Waxed Oxidized Cut Copper\")));\n itemNames.add(new ItemName(Material.WAXED_OXIDIZED_CUT_COPPER_SLAB, langConfig.getString(\"block.minecraft.waxed_oxidized_cut_copper_slab\", \"Waxed Oxidized Cut Copper Slab\")));\n itemNames.add(new ItemName(Material.WAXED_OXIDIZED_CUT_COPPER_STAIRS, langConfig.getString(\"block.minecraft.waxed_oxidized_cut_copper_stairs\", \"Waxed Oxidized Cut Copper Stairs\")));\n itemNames.add(new ItemName(Material.WAXED_WEATHERED_COPPER, langConfig.getString(\"block.minecraft.waxed_weathered_copper\", \"Waxed Weathered Copper\")));\n itemNames.add(new ItemName(Material.WAXED_WEATHERED_CUT_COPPER, langConfig.getString(\"block.minecraft.waxed_weathered_cut_copper\", \"Waxed Weathered Cut Copper\")));\n itemNames.add(new ItemName(Material.WAXED_WEATHERED_CUT_COPPER_SLAB, langConfig.getString(\"block.minecraft.waxed_weathered_cut_copper_slab\", \"Waxed Weathered Cut Copper Slab\")));\n itemNames.add(new ItemName(Material.WAXED_WEATHERED_CUT_COPPER_STAIRS, langConfig.getString(\"block.minecraft.waxed_weathered_cut_copper_stairs\", \"Waxed Weathered Cut Copper Stairs\")));\n itemNames.add(new ItemName(Material.WEATHERED_COPPER, langConfig.getString(\"block.minecraft.weathered_copper\", \"Weathered Copper\")));\n itemNames.add(new ItemName(Material.WEATHERED_CUT_COPPER, langConfig.getString(\"block.minecraft.weathered_cut_copper\", \"Weathered Cut Copper\")));\n itemNames.add(new ItemName(Material.WEATHERED_CUT_COPPER_SLAB, langConfig.getString(\"block.minecraft.weathered_cut_copper_slab\", \"Weathered Cut Copper Slab\")));\n itemNames.add(new ItemName(Material.WEATHERED_CUT_COPPER_STAIRS, langConfig.getString(\"block.minecraft.weathered_cut_copper_stairs\", \"Weathered Cut Copper Stairs\")));\n itemNames.add(new ItemName(Material.WHITE_BANNER, langConfig.getString(\"block.minecraft.white_banner\", \"White Banner\")));\n itemNames.add(new ItemName(Material.WHITE_CANDLE, langConfig.getString(\"block.minecraft.white_candle\", \"White Candle\")));\n itemNames.add(new ItemName(Material.WHITE_CANDLE_CAKE, langConfig.getString(\"block.minecraft.white_candle_cake\", \"Cake with White Candle\")));\n itemNames.add(new ItemName(Material.YELLOW_BANNER, langConfig.getString(\"block.minecraft.yellow_banner\", \"Yellow Banner\")));\n itemNames.add(new ItemName(Material.YELLOW_CANDLE, langConfig.getString(\"block.minecraft.yellow_candle\", \"Yellow Candle\")));\n itemNames.add(new ItemName(Material.YELLOW_CANDLE_CAKE, langConfig.getString(\"block.minecraft.yellow_candle_cake\", \"Cake with Yellow Candle\")));\n itemNames.add(new ItemName(Material.AMETHYST_SHARD, langConfig.getString(\"item.minecraft.amethyst_shard\", \"Amethyst Shard\")));\n itemNames.add(new ItemName(Material.AXOLOTL_BUCKET, langConfig.getString(\"item.minecraft.axolotl_bucket\", \"Bucket of Axolotl\")));\n itemNames.add(new ItemName(Material.AXOLOTL_SPAWN_EGG, langConfig.getString(\"item.minecraft.axolotl_spawn_egg\", \"Axolotl Spawn Egg\")));\n itemNames.add(new ItemName(Material.BUNDLE, langConfig.getString(\"item.minecraft.bundle\", \"Bundle\")));\n itemNames.add(new ItemName(Material.COPPER_INGOT, langConfig.getString(\"item.minecraft.copper_ingot\", \"Copper Ingot\")));\n itemNames.add(new ItemName(Material.GLOW_BERRIES, langConfig.getString(\"item.minecraft.glow_berries\", \"Glow Berries\")));\n itemNames.add(new ItemName(Material.GLOW_INK_SAC, langConfig.getString(\"item.minecraft.glow_ink_sac\", \"Glow Ink Sac\")));\n itemNames.add(new ItemName(Material.GLOW_ITEM_FRAME, langConfig.getString(\"item.minecraft.glow_item_frame\", \"Glow Item Frame\")));\n itemNames.add(new ItemName(Material.GLOW_SQUID_SPAWN_EGG, langConfig.getString(\"item.minecraft.glow_squid_spawn_egg\", \"Glow Squid Spawn Egg\")));\n itemNames.add(new ItemName(Material.GOAT_SPAWN_EGG, langConfig.getString(\"item.minecraft.goat_spawn_egg\", \"Goat Spawn Egg\")));\n itemNames.add(new ItemName(Material.PIGLIN_BANNER_PATTERN, langConfig.getString(\"item.minecraft.piglin_banner_pattern\", \"Banner Pattern\")));\n itemNames.add(new ItemName(Material.POWDER_SNOW_BUCKET, langConfig.getString(\"item.minecraft.powder_snow_bucket\", \"Powder Snow Bucket\")));\n itemNames.add(new ItemName(Material.RAW_COPPER, langConfig.getString(\"item.minecraft.raw_copper\", \"Raw Copper\")));\n itemNames.add(new ItemName(Material.RAW_GOLD, langConfig.getString(\"item.minecraft.raw_gold\", \"Raw Gold\")));\n itemNames.add(new ItemName(Material.RAW_IRON, langConfig.getString(\"item.minecraft.raw_iron\", \"Raw Iron\")));\n itemNames.add(new ItemName(Material.SHIELD, langConfig.getString(\"item.minecraft.shield\", \"Shield\")));\n itemNames.add(new ItemName(Material.SPYGLASS, langConfig.getString(\"item.minecraft.spyglass\", \"Spyglass\")));\n } else {\n itemNames.add(new ItemName(Material.valueOf(\"GRASS_PATH\"), langConfig.getString(\"block.minecraft.grass_path\", \"Grass Path\")));\n }\n\n // Add Enchantment Names\n enchantmentNames.add(new EnchantmentName(Enchantment.DAMAGE_ALL, langConfig.getString(\"enchantment.minecraft.sharpness\", \"Sharpness\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.DAMAGE_UNDEAD, langConfig.getString(\"enchantment.minecraft.smite\", \"Smite\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.DAMAGE_ARTHROPODS, langConfig.getString(\"enchantment.minecraft.bane_of_arthropods\", \"Bane of Arthropods\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.KNOCKBACK, langConfig.getString(\"enchantment.minecraft.knockback\", \"Knockback\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.FIRE_ASPECT, langConfig.getString(\"enchantment.minecraft.fire_aspect\", \"Fire Aspect\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.SWEEPING_EDGE, langConfig.getString(\"enchantment.minecraft.sweeping\", \"Sweeping Edge\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.PROTECTION_ENVIRONMENTAL, langConfig.getString(\"enchantment.minecraft.protection\", \"Protection\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.PROTECTION_FIRE, langConfig.getString(\"enchantment.minecraft.fire_protection\", \"Fire Protection\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.PROTECTION_FALL, langConfig.getString(\"enchantment.minecraft.feather_falling\", \"Feather Falling\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.PROTECTION_EXPLOSIONS, langConfig.getString(\"enchantment.minecraft.blast_protection\", \"Blast Protection\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.PROTECTION_PROJECTILE, langConfig.getString(\"enchantment.minecraft.projectile_protection\", \"Projectile Protection\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.OXYGEN, langConfig.getString(\"enchantment.minecraft.respiration\", \"Respiration\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.WATER_WORKER, langConfig.getString(\"enchantment.minecraft.aqua_affinity\", \"Aqua Affinity\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.DEPTH_STRIDER, langConfig.getString(\"enchantment.minecraft.depth_strider\", \"Depth Strider\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.FROST_WALKER, langConfig.getString(\"enchantment.minecraft.frost_walker\", \"Frost Walker\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.DIG_SPEED, langConfig.getString(\"enchantment.minecraft.efficiency\", \"Efficiency\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.SILK_TOUCH, langConfig.getString(\"enchantment.minecraft.silk_touch\", \"Silk Touch\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.DURABILITY, langConfig.getString(\"enchantment.minecraft.unbreaking\", \"Unbreaking\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.LOOT_BONUS_MOBS, langConfig.getString(\"enchantment.minecraft.looting\", \"Looting\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.LOOT_BONUS_BLOCKS, langConfig.getString(\"enchantment.minecraft.fortune\", \"Fortune\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.LUCK, langConfig.getString(\"enchantment.minecraft.luck_of_the_sea\", \"Luck of the Sea\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.LURE, langConfig.getString(\"enchantment.minecraft.lure\", \"Lure\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.ARROW_DAMAGE, langConfig.getString(\"enchantment.minecraft.power\", \"Power\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.ARROW_FIRE, langConfig.getString(\"enchantment.minecraft.flame\", \"Flame\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.ARROW_KNOCKBACK, langConfig.getString(\"enchantment.minecraft.punch\", \"Punch\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.ARROW_INFINITE, langConfig.getString(\"enchantment.minecraft.infinity\", \"Infinity\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.THORNS, langConfig.getString(\"enchantment.minecraft.thorns\", \"Thorns\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.MENDING, langConfig.getString(\"enchantment.minecraft.mending\", \"Mending\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.BINDING_CURSE, langConfig.getString(\"enchantment.minecraft.binding_curse\", \"Curse of Binding\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.VANISHING_CURSE, langConfig.getString(\"enchantment.minecraft.vanishing_curse\", \"Curse of Vanishing\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.LOYALTY, langConfig.getString(\"enchantment.minecraft.loyalty\", \"Loyalty\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.IMPALING, langConfig.getString(\"enchantment.minecraft.impaling\", \"Impaling\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.RIPTIDE, langConfig.getString(\"enchantment.minecraft.riptide\", \"Riptide\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.CHANNELING, langConfig.getString(\"enchantment.minecraft.channeling\", \"Channeling\")));\n\n if (Utils.getMajorVersion() >= 17) {\n // Add 1.17 enchantment name\n enchantmentNames.add(new EnchantmentName(Enchantment.SOUL_SPEED, langConfig.getString(\"enchantment.minecraft.soul_speed\", \"Soul Speed\")));\n }\n\n if (Utils.getMajorVersion() >= 14) {\n // Add 1.14 enchantment names\n enchantmentNames.add(new EnchantmentName(Enchantment.MULTISHOT, langConfig.getString(\"enchantment.minecraft.multishot\", \"Multishot\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.QUICK_CHARGE, langConfig.getString(\"enchantment.minecraft.quick_charge\", \"Quick Charge\")));\n enchantmentNames.add(new EnchantmentName(Enchantment.PIERCING, langConfig.getString(\"enchantment.minecraft.piercing\", \"Piercing\")));\n }\n\n // Add Enchantment Level Names\n enchantmentLevelNames.add(new EnchantmentName.EnchantmentLevelName(1, langConfig.getString(\"enchantment.level.1\", \"I\")));\n enchantmentLevelNames.add(new EnchantmentName.EnchantmentLevelName(2, langConfig.getString(\"enchantment.level.2\", \"II\")));\n enchantmentLevelNames.add(new EnchantmentName.EnchantmentLevelName(3, langConfig.getString(\"enchantment.level.3\", \"II\")));\n enchantmentLevelNames.add(new EnchantmentName.EnchantmentLevelName(4, langConfig.getString(\"enchantment.level.4\", \"IV\")));\n enchantmentLevelNames.add(new EnchantmentName.EnchantmentLevelName(5, langConfig.getString(\"enchantment.level.5\", \"V\")));\n enchantmentLevelNames.add(new EnchantmentName.EnchantmentLevelName(6, langConfig.getString(\"enchantment.level.6\", \"VI\")));\n enchantmentLevelNames.add(new EnchantmentName.EnchantmentLevelName(7, langConfig.getString(\"enchantment.level.7\", \"VII\")));\n enchantmentLevelNames.add(new EnchantmentName.EnchantmentLevelName(8, langConfig.getString(\"enchantment.level.8\", \"VIII\")));\n enchantmentLevelNames.add(new EnchantmentName.EnchantmentLevelName(9, langConfig.getString(\"enchantment.level.9\", \"IX\")));\n enchantmentLevelNames.add(new EnchantmentName.EnchantmentLevelName(10, langConfig.getString(\"enchantment.level.10\", \"X\")));\n\n // Add Potion Effect Names\n potionEffectNames.add(new PotionEffectName(PotionEffectType.SPEED, langConfig.getString(\"effect.minecraft.speed\", \"Speed\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.SLOW, langConfig.getString(\"effect.minecraft.slowness\", \"Slowness\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.FAST_DIGGING, langConfig.getString(\"effect.minecraft.haste\", \"Haste\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.SLOW_DIGGING, langConfig.getString(\"effect.minecraft.mining_fatigue\", \"Mining Fatigue\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.INCREASE_DAMAGE, langConfig.getString(\"effect.minecraft.strength\", \"Strength\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.HEAL, langConfig.getString(\"effect.minecraft.instant_health\", \"Instant Health\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.HARM, langConfig.getString(\"effect.minecraft.instant_damage\", \"Instant Damage\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.JUMP, langConfig.getString(\"effect.minecraft.jump_boost\", \"Jump Boost\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.CONFUSION, langConfig.getString(\"effect.minecraft.nausea\", \"Nausea\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.REGENERATION, langConfig.getString(\"effect.minecraft.regeneration\", \"Regeneration\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.DAMAGE_RESISTANCE, langConfig.getString(\"effect.minecraft.resistance\", \"Resistance\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.FIRE_RESISTANCE, langConfig.getString(\"effect.minecraft.fire_resistance\", \"Fire Resistance\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.WATER_BREATHING, langConfig.getString(\"effect.minecraft.water_breathing\", \"Water Breathing\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.INVISIBILITY, langConfig.getString(\"effect.minecraft.invisibility\", \"Invisibility\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.BLINDNESS, langConfig.getString(\"effect.minecraft.blindness\", \"Blindness\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.NIGHT_VISION, langConfig.getString(\"effect.minecraft.night_vision\", \"Night Vision\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.HUNGER, langConfig.getString(\"effect.minecraft.hunger\", \"Hunger\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.WEAKNESS, langConfig.getString(\"effect.minecraft.weakness\", \"Weakness\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.POISON, langConfig.getString(\"effect.minecraft.poison\", \"Poison\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.WITHER, langConfig.getString(\"effect.minecraft.wither\", \"Wither\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.HEALTH_BOOST, langConfig.getString(\"effect.minecraft.health_boost\", \"Health Boost\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.ABSORPTION, langConfig.getString(\"effect.minecraft.absorption\", \"Absorption\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.SATURATION, langConfig.getString(\"effect.minecraft.saturation\", \"Saturation\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.GLOWING, langConfig.getString(\"effect.minecraft.glowing\", \"Glowing\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.LUCK, langConfig.getString(\"effect.minecraft.luck\", \"Luck\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.UNLUCK, langConfig.getString(\"effect.minecraft.unluck\", \"Bad Luck\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.LEVITATION, langConfig.getString(\"effect.minecraft.levitation\", \"Levitation\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.SLOW_FALLING, langConfig.getString(\"effect.minecraft.slow_falling\", \"Slow Falling\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.CONDUIT_POWER, langConfig.getString(\"effect.minecraft.conduit_power\", \"Conduit Power\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.DOLPHINS_GRACE, langConfig.getString(\"effect.minecraft.dolphins_grace\", \"Dolphin's Grace\")));\n\n\n if (Utils.getMajorVersion() >= 14) {\n // Add 1.14 potion effect names\n potionEffectNames.add(new PotionEffectName(PotionEffectType.BAD_OMEN, langConfig.getString(\"effect.minecraft.bad_omen\", \"Bad Omen\")));\n potionEffectNames.add(new PotionEffectName(PotionEffectType.HERO_OF_THE_VILLAGE, langConfig.getString(\"effect.minecraft.hero_of_the_village\", \"Hero of the Village\")));\n\n }\n\n // Add Potion Names\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.UNCRAFTABLE, langConfig.getString(\"item.minecraft.potion.effect.empty\", \"Uncraftable Potion\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.WATER, langConfig.getString(\"item.minecraft.potion.effect.water\", \"Water Bottle\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.MUNDANE, langConfig.getString(\"item.minecraft.potion.effect.mundane\", \"Mundane Potion\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.THICK, langConfig.getString(\"item.minecraft.potion.effect.thick\", \"Thick Potion\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.AWKWARD, langConfig.getString(\"item.minecraft.potion.effect.awkward\", \"Awkward Potion\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.NIGHT_VISION, langConfig.getString(\"item.minecraft.potion.effect.night_vision\", \"Potion of Night Vision\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.INVISIBILITY, langConfig.getString(\"item.minecraft.potion.effect.invisibility\", \"Potion of Invisibility\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.JUMP, langConfig.getString(\"item.minecraft.potion.effect.leaping\", \"Potion of Leaping\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.FIRE_RESISTANCE, langConfig.getString(\"item.minecraft.potion.effect.fire_resistance\", \"Potion of Fire Resistance\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.SPEED, langConfig.getString(\"item.minecraft.potion.effect.swiftness\", \"Potion of Swiftness\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.SLOWNESS, langConfig.getString(\"item.minecraft.potion.effect.slowness\", \"Potion of Slowness\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.WATER_BREATHING, langConfig.getString(\"item.minecraft.potion.effect.water_breathing\", \"Potion of Water Breathing\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.INSTANT_HEAL, langConfig.getString(\"item.minecraft.potion.effect.healing\", \"Potion of Healing\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.INSTANT_DAMAGE, langConfig.getString(\"item.minecraft.potion.effect.harming\", \"Potion of Harming\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.POISON, langConfig.getString(\"item.minecraft.potion.effect.poison\", \"Potion of Poison\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.REGEN, langConfig.getString(\"item.minecraft.potion.effect.regeneration\", \"Potion of Regeneration\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.STRENGTH, langConfig.getString(\"item.minecraft.potion.effect.strength\", \"Potion of Strength\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.WEAKNESS, langConfig.getString(\"item.minecraft.potion.effect.weakness\", \"Potion of Weakness\")));\n //potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.LEVITATION, langConfig.getString(\"item.minecraft.potion.effect.levitation\", \"Potion of Levitation\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.LUCK, langConfig.getString(\"item.minecraft.potion.effect.luck\", \"Potion of Luck\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.TURTLE_MASTER, langConfig.getString(\"item.minecraft.potion.effect.turtle_master\", \"Potion of the Turtle Master\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.POTION, PotionType.SLOW_FALLING, langConfig.getString(\"item.minecraft.potion.effect.slow_falling\", \"Potion of Slow Falling\")));\n\n // Add Splash Potion Names\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.UNCRAFTABLE, langConfig.getString(\"item.minecraft.splash_potion.effect.empty\", \"Splash Uncraftable Potion\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.WATER, langConfig.getString(\"item.minecraft.splash_potion.effect.water\", \"Splash Water Bottle\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.MUNDANE, langConfig.getString(\"item.minecraft.splash_potion.effect.mundane\", \"Mundane Splash Potion\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.THICK, langConfig.getString(\"item.minecraft.splash_potion.effect.thick\", \"Thick Splash Potion\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.AWKWARD, langConfig.getString(\"item.minecraft.splash_potion.effect.awkward\", \"Awkward Splash Potion\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.NIGHT_VISION, langConfig.getString(\"item.minecraft.splash_potion.effect.night_vision\", \"Splash Potion of Night Vision\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.INVISIBILITY, langConfig.getString(\"item.minecraft.splash_potion.effect.invisibility\", \"Splash Potion of Invisibility\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.JUMP, langConfig.getString(\"item.minecraft.splash_potion.effect.leaping\", \"Splash Potion of Leaping\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.FIRE_RESISTANCE, langConfig.getString(\"item.minecraft.splash_potion.effect.fire_resistance\", \"Splash Potion of Fire Resistance\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.SPEED, langConfig.getString(\"item.minecraft.splash_potion.effect.swiftness\", \"Splash Potion of Swiftness\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.SLOWNESS, langConfig.getString(\"item.minecraft.splash_potion.effect.slowness\", \"Splash Potion of Slowness\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.WATER_BREATHING, langConfig.getString(\"item.minecraft.splash_potion.effect.water_breathing\", \"Splash Potion of Water Breathing\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.INSTANT_HEAL, langConfig.getString(\"item.minecraft.splash_potion.effect.healing\", \"Splash Potion of Healing\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.INSTANT_DAMAGE, langConfig.getString(\"item.minecraft.splash_potion.effect.harming\", \"Splash Potion of Harming\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.POISON, langConfig.getString(\"item.minecraft.splash_potion.effect.poison\", \"Splash Potion of Poison\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.REGEN, langConfig.getString(\"item.minecraft.splash_potion.effect.regeneration\", \"Splash Potion of Regeneration\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.STRENGTH, langConfig.getString(\"item.minecraft.splash_potion.effect.strength\", \"Splash Potion of Strength\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.WEAKNESS, langConfig.getString(\"item.minecraft.splash_potion.effect.weakness\", \"Splash Potion of Weakness\")));\n //potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.LEVITATION, langConfig.getString(\"item.minecraft.splash_potion.effect.levitation\", \"Splash Potion of Levitation\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.LUCK, langConfig.getString(\"item.minecraft.splash_potion.effect.luck\", \"Splash Potion of Luck\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.TURTLE_MASTER, langConfig.getString(\"item.minecraft.splash_potion.effect.turtle_master\", \"Splash Potion of the Turtle Master\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.SPLASH_POTION, PotionType.SLOW_FALLING, langConfig.getString(\"item.minecraft.splash_potion.effect.slow_falling\", \"Splash Potion of Slow Falling\")));\n\n // Add Lingering Potion Names\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.UNCRAFTABLE, langConfig.getString(\"item.minecraft.lingering_potion.effect.empty\", \"Lingering Uncraftable Potion\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.WATER, langConfig.getString(\"item.minecraft.lingering_potion.effect.water\", \"Lingering Water Bottle\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.MUNDANE, langConfig.getString(\"item.minecraft.lingering_potion.effect.mundane\", \"Mundane Lingering Potion\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.THICK, langConfig.getString(\"item.minecraft.lingering_potion.effect.thick\", \"Thick Lingering Potion\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.AWKWARD, langConfig.getString(\"item.minecraft.lingering_potion.effect.awkward\", \"Awkward Lingering Potion\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.NIGHT_VISION, langConfig.getString(\"item.minecraft.lingering_potion.effect.night_vision\", \"Lingering Potion of Night Vision\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.INVISIBILITY, langConfig.getString(\"item.minecraft.lingering_potion.effect.invisibility\", \"Lingering Potion of Invisibility\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.JUMP, langConfig.getString(\"item.minecraft.lingering_potion.effect.leaping\", \"Lingering Potion of Leaping\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.FIRE_RESISTANCE, langConfig.getString(\"item.minecraft.lingering_potion.effect.fire_resistance\", \"Lingering Potion of Fire Resistance\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.SPEED, langConfig.getString(\"item.minecraft.lingering_potion.effect.swiftness\", \"Lingering Potion of Swiftness\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.SLOWNESS, langConfig.getString(\"item.minecraft.lingering_potion.effect.slowness\", \"Lingering Potion of Slowness\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.WATER_BREATHING, langConfig.getString(\"item.minecraft.lingering_potion.effect.water_breathing\", \"Lingering Potion of Water Breathing\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.INSTANT_HEAL, langConfig.getString(\"item.minecraft.lingering_potion.effect.healing\", \"Lingering Potion of Healing\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.INSTANT_DAMAGE, langConfig.getString(\"item.minecraft.lingering_potion.effect.harming\", \"Lingering Potion of Harming\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.POISON, langConfig.getString(\"item.minecraft.lingering_potion.effect.poison\", \"Lingering Potion of Poison\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.REGEN, langConfig.getString(\"item.minecraft.lingering_potion.effect.regeneration\", \"Lingering Potion of Regeneration\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.STRENGTH, langConfig.getString(\"item.minecraft.lingering_potion.effect.strength\", \"Lingering Potion of Strength\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.WEAKNESS, langConfig.getString(\"item.minecraft.lingering_potion.effect.weakness\", \"Lingering Potion of Weakness\")));\n //potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.LEVITATION, langConfig.getString(\"item.minecraft.lingering_potion.effect.levitation\", \"Lingering Potion of Levitation\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.LUCK, langConfig.getString(\"item.minecraft.lingering_potion.effect.luck\", \"Lingering Potion of Luck\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.TURTLE_MASTER, langConfig.getString(\"item.minecraft.lingering_potion.effect.turtle_master\", \"Lingering Potion of the Turtle Master\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.LINGERING_POTION, PotionType.SLOW_FALLING, langConfig.getString(\"item.minecraft.lingering_potion.effect.slow_falling\", \"Lingering Potion of Slow Falling\")));\n \n // Add Tipped Arrow Names\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.UNCRAFTABLE, langConfig.getString(\"item.minecraft.tipped_arrow.effect.empty\", \"Uncraftable Tipped Arrow\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.WATER, langConfig.getString(\"item.minecraft.tipped_arrow.effect.water\", \"Arrow of Splashing\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.MUNDANE, langConfig.getString(\"item.minecraft.tipped_arrow.effect.mundane\", \"Tipped Arrow\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.THICK, langConfig.getString(\"item.minecraft.tipped_arrow.effect.thick\", \"Tipped Arrow\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.AWKWARD, langConfig.getString(\"item.minecraft.tipped_arrow.effect.awkward\", \"Tipped Arrow\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.NIGHT_VISION, langConfig.getString(\"item.minecraft.tipped_arrow.effect.night_vision\", \"Arrow of Night Vision\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.INVISIBILITY, langConfig.getString(\"item.minecraft.tipped_arrow.effect.invisibility\", \"Arrow of Invisibility\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.JUMP, langConfig.getString(\"item.minecraft.tipped_arrow.effect.leaping\", \"Arrow of Leaping\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.FIRE_RESISTANCE, langConfig.getString(\"item.minecraft.tipped_arrow.effect.fire_resistance\", \"Arrow of Fire Resistance\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.SPEED, langConfig.getString(\"item.minecraft.tipped_arrow.effect.swiftness\", \"Arrow of Swiftness\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.SLOWNESS, langConfig.getString(\"item.minecraft.tipped_arrow.effect.slowness\", \"Arrow of Slowness\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.WATER_BREATHING, langConfig.getString(\"item.minecraft.tipped_arrow.effect.water_breathing\", \"Arrow of Water Breathing\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.INSTANT_HEAL, langConfig.getString(\"item.minecraft.tipped_arrow.effect.healing\", \"Arrow of Healing\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.INSTANT_DAMAGE, langConfig.getString(\"item.minecraft.tipped_arrow.effect.harming\", \"Arrow of Harming\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.POISON, langConfig.getString(\"item.minecraft.tipped_arrow.effect.poison\", \"Arrow of Poison\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.REGEN, langConfig.getString(\"item.minecraft.tipped_arrow.effect.regeneration\", \"Arrow of Regeneration\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.STRENGTH, langConfig.getString(\"item.minecraft.tipped_arrow.effect.strength\", \"Arrow of Strength\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.WEAKNESS, langConfig.getString(\"item.minecraft.tipped_arrow.effect.weakness\", \"Arrow of Weakness\")));\n //potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.LEVITATION, langConfig.getString(\"item.minecraft.tipped_arrow.effect.levitation\", \"Arrow of Levitation\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.LUCK, langConfig.getString(\"item.minecraft.tipped_arrow.effect.luck\", \"Arrow of Luck\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.TURTLE_MASTER, langConfig.getString(\"item.minecraft.tipped_arrow.effect.turtle_master\", \"Arrow of the Turtle Master\")));\n potionNames.add(new PotionName(PotionName.PotionItemType.TIPPED_ARROW, PotionType.SLOW_FALLING, langConfig.getString(\"item.minecraft.tipped_arrow.effect.slow_falling\", \"Arrow of Slow Falling\")));\n \n // Add Music Disc Titles\n musicDiscNames.add(new MusicDiscName(Material.MUSIC_DISC_13, langConfig.getString(\"item.minecraft.music_disc_13.desc\", \"C418 - 13\")));\n musicDiscNames.add(new MusicDiscName(Material.MUSIC_DISC_CAT, langConfig.getString(\"item.minecraft.music_disc_cat.desc\", \"C418 - cat\")));\n musicDiscNames.add(new MusicDiscName(Material.MUSIC_DISC_BLOCKS, langConfig.getString(\"item.minecraft.music_disc_blocks.desc\", \"C418 - blocks\")));\n musicDiscNames.add(new MusicDiscName(Material.MUSIC_DISC_CHIRP, langConfig.getString(\"item.minecraft.music_disc_chirp.desc\", \"C418 - chirp\")));\n musicDiscNames.add(new MusicDiscName(Material.MUSIC_DISC_FAR, langConfig.getString(\"item.minecraft.music_disc_far.desc\", \"C418 - far\")));\n musicDiscNames.add(new MusicDiscName(Material.MUSIC_DISC_MALL, langConfig.getString(\"item.minecraft.music_disc_mall.desc\", \"C418 - mall\")));\n musicDiscNames.add(new MusicDiscName(Material.MUSIC_DISC_MELLOHI, langConfig.getString(\"item.minecraft.music_disc_mellohi.desc\", \"C418 - mellohi\")));\n musicDiscNames.add(new MusicDiscName(Material.MUSIC_DISC_STAL, langConfig.getString(\"item.minecraft.music_disc_stal.desc\", \"C418 - stal\")));\n musicDiscNames.add(new MusicDiscName(Material.MUSIC_DISC_STRAD, langConfig.getString(\"item.minecraft.music_disc_strad.desc\", \"C418 - strad\")));\n musicDiscNames.add(new MusicDiscName(Material.MUSIC_DISC_WARD, langConfig.getString(\"item.minecraft.music_disc_ward.desc\", \"C418 - ward\")));\n musicDiscNames.add(new MusicDiscName(Material.MUSIC_DISC_11, langConfig.getString(\"item.minecraft.music_disc_11.desc\", \"C418 - 11\")));\n musicDiscNames.add(new MusicDiscName(Material.MUSIC_DISC_WAIT, langConfig.getString(\"item.minecraft.music_disc_wait.desc\", \"C418 - wait\")));\n\n if (Utils.getMajorVersion() >= 16) {\n musicDiscNames.add(new MusicDiscName(Material.MUSIC_DISC_PIGSTEP, langConfig.getString(\"item.minecraft.music_disc_pigstep.desc\", \"Lena Raine - Pigstep\")));\n }\n\n if (Utils.getMajorVersion() >= 14) {\n // Add Banner Pattern Names\n bannerPatternNames.add(new BannerPatternName(Material.CREEPER_BANNER_PATTERN, langConfig.getString(\"item.minecraft.creeper_banner_pattern.desc\", \"Creeper Charge\")));\n bannerPatternNames.add(new BannerPatternName(Material.SKULL_BANNER_PATTERN, langConfig.getString(\"item.minecraft.skull_banner_pattern.desc\", \"Skull Charge\")));\n bannerPatternNames.add(new BannerPatternName(Material.FLOWER_BANNER_PATTERN, langConfig.getString(\"item.minecraft.flower_banner_pattern.desc\", \"Flower Charge\")));\n bannerPatternNames.add(new BannerPatternName(Material.MOJANG_BANNER_PATTERN, langConfig.getString(\"item.minecraft.mojang_banner_pattern.desc\", \"Thing\")));\n bannerPatternNames.add(new BannerPatternName(Material.GLOBE_BANNER_PATTERN, langConfig.getString(\"item.minecraft.globe_banner_pattern.desc\", \"Globe\")));\n\n if (Utils.getMajorVersion() >= 16) {\n bannerPatternNames.add(new BannerPatternName(Material.PIGLIN_BANNER_PATTERN, langConfig.getString(\"item.minecraft.piglin_banner_pattern.desc\", \"Snout\")));\n }\n }\n\n // Add Book Generation Names\n generationNames.add(new BookGenerationName(CustomBookMeta.Generation.ORIGINAL, langConfig.getString(\"book.generation.0\", \"Original\")));\n generationNames.add(new BookGenerationName(CustomBookMeta.Generation.COPY_OF_ORIGINAL, langConfig.getString(\"book.generation.1\", \"Copy of original\")));\n generationNames.add(new BookGenerationName(CustomBookMeta.Generation.COPY_OF_COPY, langConfig.getString(\"book.generation.2\", \"Copy of a copy\")));\n generationNames.add(new BookGenerationName(CustomBookMeta.Generation.TATTERED, langConfig.getString(\"book.generation.3\", \"Tattered\")));\n\n loadMessages();\n }\n\n private static void loadMessages() {\n // Add ShopChest Messages\n messages.add(new LocalizedMessage(Message.SHOP_CREATED, langConfig.getString(\"message.shop-created\", \"&6You were withdrawn &c%CREATION-PRICE% &6to create this shop.\")));\n messages.add(new LocalizedMessage(Message.ADMIN_SHOP_CREATED, langConfig.getString(\"message.admin-shop-created\", \"&6You were withdrawn &c%CREATION-PRICE% &6to create this admin shop.\")));\n messages.add(new LocalizedMessage(Message.CHEST_ALREADY_SHOP, langConfig.getString(\"message.chest-already-shop\", \"&cChest already shop.\")));\n messages.add(new LocalizedMessage(Message.CHEST_BLOCKED, langConfig.getString(\"message.chest-blocked\", \"&cThere must not be a block above the chest.\")));\n messages.add(new LocalizedMessage(Message.DOUBLE_CHEST_BLOCKED, langConfig.getString(\"message.double-chest-blocked\", \"&cThere must not be a block above the chest.\")));\n messages.add(new LocalizedMessage(Message.SHOP_REMOVED, langConfig.getString(\"message.shop-removed\", \"&6Shop removed.\")));\n messages.add(new LocalizedMessage(Message.SHOP_REMOVED_REFUND, langConfig.getString(\"message.shop-removed-refund\", \"&6Shop removed. You were refunded &c%CREATION-PRICE%&6.\")));\n messages.add(new LocalizedMessage(Message.ALL_SHOPS_REMOVED, langConfig.getString(\"message.all-shops-removed\", \"&6Removed all (&c%AMOUNT%&6) shop/s of &c%VENDOR%&6.\")));\n messages.add(new LocalizedMessage(Message.CHEST_NO_SHOP, langConfig.getString(\"message.chest-no-shop\", \"&cChest is not a shop.\")));\n messages.add(new LocalizedMessage(Message.SHOP_CREATE_NOT_ENOUGH_MONEY, langConfig.getString(\"message.shop-create-not-enough-money\", \"&cNot enough money. You need &6%CREATION-PRICE% &cto create a shop.\")));\n messages.add(new LocalizedMessage(Message.SHOP_INFO_VENDOR, langConfig.getString(\"message.shopInfo.vendor\", \"&6Vendor: &e%VENDOR%\")));\n messages.add(new LocalizedMessage(Message.SHOP_INFO_PRODUCT, langConfig.getString(\"message.shopInfo.product\", \"&6Product: &e%AMOUNT% x %ITEMNAME%\")));\n messages.add(new LocalizedMessage(Message.SHOP_INFO_STOCK, langConfig.getString(\"message.shopInfo.stock\", \"&6In Stock: &e%STOCK%\")));\n messages.add(new LocalizedMessage(Message.SHOP_INFO_CHEST_SPACE, langConfig.getString(\"message.shopInfo.chest-space\", \"&6Space in chest: &e%CHEST-SPACE%\")));\n messages.add(new LocalizedMessage(Message.SHOP_INFO_PRICE, langConfig.getString(\"message.shopInfo.price\", \"&6Price: Buy: &e%BUY-PRICE%&6 Sell: &e%SELL-PRICE%\")));\n messages.add(new LocalizedMessage(Message.SHOP_INFO_DISABLED, langConfig.getString(\"message.shopInfo.disabled\", \"&7Disabled\")));\n messages.add(new LocalizedMessage(Message.SHOP_INFO_NORMAL, langConfig.getString(\"message.shopInfo.is-normal\", \"&6Type: &eNormal\")));\n messages.add(new LocalizedMessage(Message.SHOP_INFO_ADMIN, langConfig.getString(\"message.shopInfo.is-admin\", \"&6Type: &eAdmin\")));\n messages.add(new LocalizedMessage(Message.BUY_SELL_DISABLED, langConfig.getString(\"message.buy-and-sell-disabled\", \"&cYou can't create a shop with buying and selling disabled.\")));\n messages.add(new LocalizedMessage(Message.BUY_SUCCESS, langConfig.getString(\"message.buy-success\", \"&aYou bought &6%AMOUNT% x %ITEMNAME%&a for &6%BUY-PRICE%&a from &6%VENDOR%&a.\")));\n messages.add(new LocalizedMessage(Message.BUY_SUCCESS_ADMIN, langConfig.getString(\"message.buy-success-admin\", \"&aYou bought &6%AMOUNT% x %ITEMNAME%&a for &6%BUY-PRICE%&a.\")));\n messages.add(new LocalizedMessage(Message.SELL_SUCCESS, langConfig.getString(\"message.sell-success\", \"&aYou sold &6%AMOUNT% x %ITEMNAME%&a for &6%SELL-PRICE%&a to &6%VENDOR%&a.\")));\n messages.add(new LocalizedMessage(Message.SELL_SUCCESS_ADMIN, langConfig.getString(\"message.sell-success-admin\", \"&aYou sold &6%AMOUNT% x %ITEMNAME%&a for &6%SELL-PRICE%&a.\")));\n messages.add(new LocalizedMessage(Message.SOMEONE_BOUGHT, langConfig.getString(\"message.someone-bought\", \"&6%PLAYER% &abought &6%AMOUNT% x %ITEMNAME%&a for &6%BUY-PRICE%&a from your shop.\")));\n messages.add(new LocalizedMessage(Message.SOMEONE_SOLD, langConfig.getString(\"message.someone-sold\", \"&6%PLAYER% &asold &6%AMOUNT% x %ITEMNAME%&a for &6%SELL-PRICE%&a to your shop.\")));\n messages.add(new LocalizedMessage(Message.REVENUE_WHILE_OFFLINE, langConfig.getString(\"message.revenue-while-offline\", \"&6While you were offline, your shops have made a revenue of &c%REVENUE%&6.\")));\n messages.add(new LocalizedMessage(Message.NOT_ENOUGH_INVENTORY_SPACE, langConfig.getString(\"message.not-enough-inventory-space\", \"&cNot enough space in inventory.\")));\n messages.add(new LocalizedMessage(Message.CHEST_NOT_ENOUGH_INVENTORY_SPACE, langConfig.getString(\"message.chest-not-enough-inventory-space\", \"&cShop is full.\")));\n messages.add(new LocalizedMessage(Message.NOT_ENOUGH_MONEY, langConfig.getString(\"message.not-enough-money\", \"&cNot enough money.\")));\n messages.add(new LocalizedMessage(Message.NOT_ENOUGH_ITEMS, langConfig.getString(\"message.not-enough-items\", \"&cNot enough items.\")));\n messages.add(new LocalizedMessage(Message.VENDOR_NOT_ENOUGH_MONEY, langConfig.getString(\"message.vendor-not-enough-money\", \"&cVendor has not enough money.\")));\n messages.add(new LocalizedMessage(Message.OUT_OF_STOCK, langConfig.getString(\"message.out-of-stock\", \"&cShop out of stock.\")));\n messages.add(new LocalizedMessage(Message.VENDOR_OUT_OF_STOCK, langConfig.getString(\"message.vendor-out-of-stock\", \"&cYour shop that sells &6%AMOUNT% x %ITEMNAME% &cis out of stock.\")));\n messages.add(new LocalizedMessage(Message.ERROR_OCCURRED, langConfig.getString(\"message.error-occurred\", \"&cAn error occurred: %ERROR%\")));\n messages.add(new LocalizedMessage(Message.AMOUNT_PRICE_NOT_NUMBER, langConfig.getString(\"message.amount-and-price-not-number\", \"&cAmount and price must be a number.\")));\n messages.add(new LocalizedMessage(Message.AMOUNT_IS_ZERO, langConfig.getString(\"message.amount-is-zero\", \"&cAmount must be greater than 0.\")));\n messages.add(new LocalizedMessage(Message.PRICES_CONTAIN_DECIMALS, langConfig.getString(\"message.prices-contain-decimals\", \"&cPrices must not contain decimals.\")));\n messages.add(new LocalizedMessage(Message.NO_ITEM_IN_HAND, langConfig.getString(\"message.no-item-in-hand\", \"&cNo item in hand\")));\n messages.add(new LocalizedMessage(Message.CLICK_CHEST_CREATE, langConfig.getString(\"message.click-chest-to-create-shop\", \"&aClick a chest within 15 seconds to create a shop.\")));\n messages.add(new LocalizedMessage(Message.CLICK_CHEST_REMOVE, langConfig.getString(\"message.click-chest-to-remove-shop\", \"&aClick a shop within 15 seconds to remove it.\")));\n messages.add(new LocalizedMessage(Message.CLICK_CHEST_INFO, langConfig.getString(\"message.click-chest-for-info\", \"&aClick a shop within 15 seconds to retrieve information.\")));\n messages.add(new LocalizedMessage(Message.CLICK_CHEST_OPEN, langConfig.getString(\"message.click-chest-to-open-shop\", \"&aClick a shop within 15 seconds to open it.\")));\n messages.add(new LocalizedMessage(Message.CLICK_TO_CONFIRM, langConfig.getString(\"message.click-to-confirm\", \"&aClick again to confirm.\")));\n messages.add(new LocalizedMessage(Message.OPENED_SHOP, langConfig.getString(\"message.opened-shop\", \"&aYou opened %VENDOR%'s shop.\")));\n messages.add(new LocalizedMessage(Message.CANNOT_BREAK_SHOP, langConfig.getString(\"message.cannot-break-shop\", \"&cYou can't break a shop.\")));\n messages.add(new LocalizedMessage(Message.CANNOT_SELL_BROKEN_ITEM, langConfig.getString(\"message.cannot-sell-broken-item\", \"&cYou can't sell a broken item.\")));\n messages.add(new LocalizedMessage(Message.BUY_PRICE_TOO_LOW, langConfig.getString(\"message.buy-price-too-low\", \"&cThe buy price must be higher than %MIN-PRICE%.\")));\n messages.add(new LocalizedMessage(Message.SELL_PRICE_TOO_LOW, langConfig.getString(\"message.sell-price-too-low\", \"&cThe sell price must be higher than %MIN-PRICE%.\")));\n messages.add(new LocalizedMessage(Message.BUY_PRICE_TOO_HIGH, langConfig.getString(\"message.buy-price-too-high\", \"&cThe buy price must be lower than %MAX-PRICE%.\")));\n messages.add(new LocalizedMessage(Message.SELL_PRICE_TOO_HIGH, langConfig.getString(\"message.sell-price-too-high\", \"&cThe sell price must be lower than %MAX-PRICE%.\")));\n messages.add(new LocalizedMessage(Message.BUYING_DISABLED, langConfig.getString(\"message.buying-disabled\", \"&cBuying is disabled at this shop.\")));\n messages.add(new LocalizedMessage(Message.SELLING_DISABLED, langConfig.getString(\"message.selling-disabled\", \"&cSelling is disabled at this shop.\")));\n messages.add(new LocalizedMessage(Message.RELOADED_SHOPS, langConfig.getString(\"message.reloaded-shops\", \"&aSuccessfully reloaded %AMOUNT% shop/s.\")));\n messages.add(new LocalizedMessage(Message.SHOP_LIMIT_REACHED, langConfig.getString(\"message.shop-limit-reached\", \"&cYou reached your limit of &6%LIMIT% &cshop/s.\")));\n messages.add(new LocalizedMessage(Message.OCCUPIED_SHOP_SLOTS, langConfig.getString(\"message.occupied-shop-slots\", \"&6You have &c%AMOUNT%/%LIMIT% &6shop slot/s occupied.\")));\n messages.add(new LocalizedMessage(Message.CANNOT_SELL_ITEM, langConfig.getString(\"message.cannot-sell-item\", \"&cYou cannot create a shop with this item.\")));\n messages.add(new LocalizedMessage(Message.USE_IN_CREATIVE, langConfig.getString(\"message.use-in-creative\", \"&cYou cannot use a shop in creative mode.\")));\n messages.add(new LocalizedMessage(Message.SELECT_ITEM, langConfig.getString(\"message.select-item\", \"&aOpen your inventory, and drop an item to select it.\")));\n messages.add(new LocalizedMessage(Message.ITEM_SELECTED, langConfig.getString(\"message.item-selected\", \"&aItem has been selected: &6%ITEMNAME%\")));\n messages.add(new LocalizedMessage(Message.CREATION_CANCELLED, langConfig.getString(\"message.creation-cancelled\", \"&cShop creation has been cancelled.\")));\n messages.add(new LocalizedMessage(Message.UPDATE_AVAILABLE, langConfig.getString(\"message.update.update-available\", \"&6&lVersion &c%VERSION% &6of &cShopChest &6is available &chere.\")));\n messages.add(new LocalizedMessage(Message.UPDATE_CLICK_TO_DOWNLOAD, langConfig.getString(\"message.update.click-to-download\", \"Click to download\")));\n messages.add(new LocalizedMessage(Message.UPDATE_NO_UPDATE, langConfig.getString(\"message.update.no-update\", \"&6&lNo new update available.\")));\n messages.add(new LocalizedMessage(Message.UPDATE_CHECKING, langConfig.getString(\"message.update.checking\", \"&6&lChecking for updates...\")));\n messages.add(new LocalizedMessage(Message.UPDATE_ERROR, langConfig.getString(\"message.update.error\", \"&c&lError while checking for updates.\")));\n messages.add(new LocalizedMessage(Message.NO_PERMISSION_CREATE, langConfig.getString(\"message.noPermission.create\", \"&cYou don't have permission to create a shop.\")));\n messages.add(new LocalizedMessage(Message.NO_PERMISSION_CREATE_ADMIN, langConfig.getString(\"message.noPermission.create-admin\", \"&cYou don't have permission to create an admin shop.\")));\n messages.add(new LocalizedMessage(Message.NO_PERMISSION_CREATE_PROTECTED, langConfig.getString(\"message.noPermission.create-protected\", \"&cYou don't have permission to create a shop on a protected chest.\")));\n messages.add(new LocalizedMessage(Message.NO_PERMISSION_OPEN_OTHERS, langConfig.getString(\"message.noPermission.open-others\", \"&cYou don't have permission to open this chest.\")));\n messages.add(new LocalizedMessage(Message.NO_PERMISSION_BUY, langConfig.getString(\"message.noPermission.buy\", \"&cYou don't have permission to buy something.\")));\n messages.add(new LocalizedMessage(Message.NO_PERMISSION_SELL, langConfig.getString(\"message.noPermission.sell\", \"&cYou don't have permission to sell something.\")));\n messages.add(new LocalizedMessage(Message.NO_PERMISSION_BUY_HERE, langConfig.getString(\"message.noPermission.buy-here\", \"&cYou don't have permission to buy something here.\")));\n messages.add(new LocalizedMessage(Message.NO_PERMISSION_SELL_HERE, langConfig.getString(\"message.noPermission.sell-here\", \"&cYou don't have permission to sell something here.\")));\n messages.add(new LocalizedMessage(Message.NO_PERMISSION_REMOVE_OTHERS, langConfig.getString(\"message.noPermission.remove-others\", \"&cYou don't have permission to remove this shop.\")));\n messages.add(new LocalizedMessage(Message.NO_PERMISSION_REMOVE_ADMIN, langConfig.getString(\"message.noPermission.remove-admin\", \"&cYou don't have permission to remove an admin shop.\")));\n messages.add(new LocalizedMessage(Message.NO_PERMISSION_RELOAD, langConfig.getString(\"message.noPermission.reload\", \"&cYou don't have permission to reload the shops.\")));\n messages.add(new LocalizedMessage(Message.NO_PERMISSION_UPDATE, langConfig.getString(\"message.noPermission.update\", \"&cYou don't have permission to check for updates.\")));\n messages.add(new LocalizedMessage(Message.NO_PERMISSION_CONFIG, langConfig.getString(\"message.noPermission.config\", \"&cYou don't have permission to change configuration values.\")));\n messages.add(new LocalizedMessage(Message.NO_PERMISSION_EXTEND_OTHERS, langConfig.getString(\"message.noPermission.extend-others\", \"&cYou don't have permission to extend this chest.\")));\n messages.add(new LocalizedMessage(Message.NO_PERMISSION_EXTEND_PROTECTED, langConfig.getString(\"message.noPermission.extend-protected\", \"&cYou don't have permission to extend this chest to here.\")));\n messages.add(new LocalizedMessage(Message.COMMAND_DESC_HEADER, langConfig.getString(\"message.commandDescription.header\", \"&6==== &c/%COMMAND% &6Help\")));\n messages.add(new LocalizedMessage(Message.COMMAND_DESC_FOOTER, langConfig.getString(\"message.commandDescription.footer\", \"&6==== End\")));\n messages.add(new LocalizedMessage(Message.COMMAND_DESC_CREATE, langConfig.getString(\"message.commandDescription.create\", \"&a/%COMMAND% create <amount> <buy-price> <sell-price> - Create a shop.\")));\n messages.add(new LocalizedMessage(Message.COMMAND_DESC_CREATE_ADMIN, langConfig.getString(\"message.commandDescription.create-admin\", \"&a/%COMMAND% create <amount> <buy-price> <sell-price> [admin] - Create a shop.\")));\n messages.add(new LocalizedMessage(Message.COMMAND_DESC_REMOVE, langConfig.getString(\"message.commandDescription.remove\", \"&a/%COMMAND% remove - Remove a shop.\")));\n messages.add(new LocalizedMessage(Message.COMMAND_DESC_INFO, langConfig.getString(\"message.commandDescription.info\", \"&a/%COMMAND% info - Retrieve shop information.\")));\n messages.add(new LocalizedMessage(Message.COMMAND_DESC_REMOVEALL, langConfig.getString(\"message.commandDescription.removeall\", \"&a/%COMMAND% removeall - Remove all shops of a player.\")));\n messages.add(new LocalizedMessage(Message.COMMAND_DESC_RELOAD, langConfig.getString(\"message.commandDescription.reload\", \"&a/%COMMAND% reload - Reload shops.\")));\n messages.add(new LocalizedMessage(Message.COMMAND_DESC_UPDATE, langConfig.getString(\"message.commandDescription.update\", \"&a/%COMMAND% update - Check for Updates.\")));\n messages.add(new LocalizedMessage(Message.COMMAND_DESC_LIMITS, langConfig.getString(\"message.commandDescription.limits\", \"&a/%COMMAND% limits - View shop limits.\")));\n messages.add(new LocalizedMessage(Message.COMMAND_DESC_OPEN, langConfig.getString(\"message.commandDescription.open\", \"&a/%COMMAND% open - Open a shop.\")));\n messages.add(new LocalizedMessage(Message.COMMAND_DESC_CONFIG, langConfig.getString(\"message.commandDescription.config\", \"&a/%COMMAND% config <set|add|remove> <property> <value> - Change configuration values.\")));\n messages.add(new LocalizedMessage(Message.CHANGED_CONFIG_SET, langConfig.getString(\"message.config.set\", \"&6Changed &a%PROPERTY% &6to &a%VALUE%&6.\")));\n messages.add(new LocalizedMessage(Message.CHANGED_CONFIG_REMOVED, langConfig.getString(\"message.config.removed\", \"&6Removed &a%VALUE% &6from &a%PROPERTY%&6.\")));\n messages.add(new LocalizedMessage(Message.CHANGED_CONFIG_ADDED, langConfig.getString(\"message.config.added\", \"&6Added &a%VALUE% &6to &a%PROPERTY%&6.\")));\n }\n\n /**\n * @param stack Item whose name to lookup\n * @return Localized Name of the Item, the custom name, or if <i>stack</i> is a book, the title of the book\n */\n public static String getItemName(ItemStack stack) {\n if (stack == null) return null;\n \n if (stack.hasItemMeta()) {\n ItemMeta meta = stack.getItemMeta();\n if (meta.getDisplayName() != null && !meta.getDisplayName().isEmpty()) {\n return meta.getDisplayName();\n } else if (meta instanceof BookMeta && ((BookMeta) meta).hasTitle()) {\n return ((BookMeta) meta).getTitle();\n } else if (meta instanceof SkullMeta) {\n if (((SkullMeta) meta).hasOwner()) {\n if (Utils.getMajorVersion() >= 13) {\n return String.format(langConfig.getString(\"block.minecraft.player_head.named\", \"%s's Head\"), ((SkullMeta) meta).getOwningPlayer().getName());\n } else {\n return String.format(langConfig.getString(\"item.skull.player.name\", \"%s's Head\"), ((SkullMeta) meta).getOwner());\n }\n }\n }\n }\n\n Material material = stack.getType();\n\n if (stack.getItemMeta() instanceof PotionMeta) {\n PotionMeta meta = (PotionMeta) stack.getItemMeta();\n PotionType potionType;\n String upgradeString;\n\n if (Utils.getMajorVersion() < 9) {\n Potion potion = Potion.fromItemStack(stack);\n potionType = potion.getType();\n upgradeString = potion.getLevel() == 2 && Config.appendPotionLevelToItemName ? \" II\" : \"\";\n } else {\n potionType = meta.getBasePotionData().getType();\n upgradeString = (meta.getBasePotionData().isUpgraded() && Config.appendPotionLevelToItemName ? \" II\" : \"\");\n }\n\n for (PotionName potionName : potionNames) {\n if (material == Material.POTION) {\n if (Utils.getMajorVersion() < 9) {\n if (Potion.fromItemStack(stack).isSplash()) {\n if (potionName.getPotionItemType() == PotionName.PotionItemType.SPLASH_POTION && potionName.getPotionType() == potionType) {\n return potionName.getLocalizedName() + upgradeString;\n }\n } else {\n if (potionName.getPotionItemType() == PotionName.PotionItemType.POTION && potionName.getPotionType() == potionType) {\n return potionName.getLocalizedName() + upgradeString;\n }\n }\n } else {\n if (potionName.getPotionItemType() == PotionName.PotionItemType.POTION && potionName.getPotionType() == potionType) {\n return potionName.getLocalizedName() + upgradeString;\n }\n }\n } else {\n if (Utils.getMajorVersion() >= 9) {\n if (material == Material.LINGERING_POTION) {\n if (potionName.getPotionItemType() == PotionName.PotionItemType.LINGERING_POTION && potionName.getPotionType() == potionType) {\n return potionName.getLocalizedName() + upgradeString;\n }\n } else if (material == Material.TIPPED_ARROW) {\n if (potionName.getPotionItemType() == PotionName.PotionItemType.TIPPED_ARROW && potionName.getPotionType() == potionType) {\n return potionName.getLocalizedName() + upgradeString;\n }\n } else if (material == Material.SPLASH_POTION) {\n if (potionName.getPotionItemType() == PotionName.PotionItemType.SPLASH_POTION && potionName.getPotionType() == potionType) {\n return potionName.getLocalizedName() + upgradeString;\n }\n }\n }\n }\n }\n }\n\n for (ItemName itemName : itemNames) {\n if (itemName.getMaterial() != material) {\n continue;\n }\n\n if (Utils.getMajorVersion() < 13) {\n if (material.toString().equals(\"MONSTER_EGG\")) {\n EntityType spawnedType = SpawnEggMeta.getEntityTypeFromItemStack(plugin, stack);\n\n for (EntityName entityName : entityNames) {\n if (entityName.getEntityType() == spawnedType) {\n return itemName.getLocalizedName() + \" \" + entityName.getLocalizedName();\n }\n }\n\n return itemName.getLocalizedName() + \" \" + formatDefaultString(String.valueOf(spawnedType));\n } \n \n if (itemName.getSubId() == stack.getDurability()) {\n return itemName.getLocalizedName();\n }\n } else {\n return itemName.getLocalizedName();\n }\n }\n\n return formatDefaultString(String.valueOf(material));\n }\n\n /**\n * @param enchantment Enchantment whose name should be looked up\n * @param level Level of the enchantment\n * @return Localized Name of the enchantment with the given level afterwards\n */\n public static String getEnchantmentName(Enchantment enchantment, int level) {\n if (enchantment == null) return null;\n\n String levelString = langConfig.getString(\"enchantment.level.\" + level, String.valueOf(level));\n String enchantmentString = formatDefaultString(Utils.getMajorVersion() < 13\n ? enchantment.getName() : enchantment.getKey().getKey());\n\n for (EnchantmentName enchantmentName : enchantmentNames) {\n if (enchantmentName.getEnchantment().equals(enchantment)) {\n enchantmentString = enchantmentName.getLocalizedName();\n }\n }\n\n for (EnchantmentName.EnchantmentLevelName enchantmentLevelName : enchantmentLevelNames) {\n if (enchantmentLevelName.getLevel() == level) {\n levelString = enchantmentLevelName.getLocalizedName();\n }\n }\n\n return enchantmentString + \" \" + levelString;\n }\n\n /**\n * @param enchantmentMap Map of enchantments of an item\n * @return Comma separated list of localized enchantments\n */\n public static String getEnchantmentString(Map<Enchantment, Integer> enchantmentMap) {\n if (enchantmentMap == null) return null;\n StringJoiner joiner = new StringJoiner(\", \");\n\n for (Enchantment enchantment : enchantmentMap.keySet()) {\n joiner.add(LanguageUtils.getEnchantmentName(enchantment, enchantmentMap.get(enchantment)));\n }\n\n return joiner.toString();\n }\n\n /**\n * @param itemStack Potion Item whose base effect name should be looked up\n * @return Localized name of the base potion effect\n */\n public static String getPotionEffectName(ItemStack itemStack) {\n if (itemStack == null) return null;\n if (!(itemStack.getItemMeta() instanceof PotionMeta)) return \"\";\n\n PotionMeta potionMeta = (PotionMeta) itemStack.getItemMeta();\n PotionEffectType potionEffect;\n boolean upgraded;\n\n if (Utils.getMajorVersion() < 9) {\n Potion potion = Potion.fromItemStack(itemStack);\n potionEffect = potion.getType().getEffectType();\n upgraded = potion.getLevel() == 2;\n } else {\n potionEffect = potionMeta.getBasePotionData().getType().getEffectType();\n upgraded = potionMeta.getBasePotionData().isUpgraded();\n }\n\n String potionEffectString = formatDefaultString(String.valueOf(potionEffect));\n\n for (PotionEffectName potionEffectName : potionEffectNames) {\n if (potionEffectName.getEffect() == potionEffect) {\n potionEffectString = potionEffectName.getLocalizedName();\n }\n }\n\n return potionEffectString + (upgraded ? \" II\" : \"\");\n }\n\n /**\n * @param musicDiscMaterial Material of the Music Disc whose name should be looked up\n * @return Localized title of the Music Disc\n */\n public static String getMusicDiscName(Material musicDiscMaterial) {\n if (musicDiscMaterial == null) return null;\n for (MusicDiscName musicDiscName : musicDiscNames) {\n if (musicDiscMaterial == musicDiscName.getMusicDiscMaterial()) {\n return musicDiscName.getLocalizedName();\n }\n }\n\n return \"\";\n }\n\n /**\n * @param bannerPatternMaterial Material of the Music Disc whose name should be looked up\n * @return Localized title of the Music Disc\n */\n public static String getBannerPatternName(Material bannerPatternMaterial) {\n if (bannerPatternMaterial == null) return null;\n for (BannerPatternName bannerPatternName : bannerPatternNames) {\n if (bannerPatternMaterial == bannerPatternName.getBannerPatternMaterial()) {\n return bannerPatternName.getLocalizedName();\n }\n }\n\n return \"\";\n }\n\n /**\n * @param is ItemStack that should be of type {@link Material#WRITTEN_BOOK}\n * @return Localized name of the generation or {@code null} if the item is not a written book\n */\n public static String getBookGenerationName(ItemStack is) {\n if (is.getType() != Material.WRITTEN_BOOK) {\n return null;\n }\n\n BookMeta meta = (BookMeta) is.getItemMeta();\n CustomBookMeta.Generation generation = null;\n\n if ((Utils.getMajorVersion() == 9 && Utils.getRevision() == 1) || Utils.getMajorVersion() == 8) {\n generation = CustomBookMeta.getGeneration(is);\n } else if (meta.getGeneration() != null) {\n generation = CustomBookMeta.Generation.valueOf(meta.getGeneration().toString());\n }\n\n if (generation == null) {\n generation = CustomBookMeta.Generation.ORIGINAL;\n }\n\n for (BookGenerationName generationName : generationNames) {\n if (generation == generationName.getGeneration()) {\n return generationName.getLocalizedName();\n }\n }\n\n return formatDefaultString(String.valueOf(generation));\n }\n\n /**\n * @param message Message which should be translated\n * @param replacements Replacements of placeholders which might be required to be replaced in the message\n * @return Localized Message\n */\n public static String getMessage(Message message, Replacement... replacements) {\n String finalMessage = ChatColor.RED + \"An error occurred: Message not found: \" + message.toString();\n\n for (LocalizedMessage localizedMessage : messages) {\n if (localizedMessage.getMessage() == message) {\n finalMessage = localizedMessage.getLocalizedString();\n\n for (Replacement replacement : replacements) {\n Placeholder placeholder = replacement.getPlaceholder();\n String toReplace = replacement.getReplacement();\n\n if (placeholder == Placeholder.BUY_PRICE || placeholder == Placeholder.SELL_PRICE || placeholder == Placeholder.MIN_PRICE || placeholder == Placeholder.CREATION_PRICE || placeholder == Placeholder.REVENUE) {\n if (!toReplace.equals(getMessage(Message.SHOP_INFO_DISABLED))) {\n double price = Double.parseDouble(toReplace);\n toReplace = plugin.getEconomy().format(price);\n }\n }\n\n finalMessage = finalMessage.replace(placeholder.toString(), toReplace);\n }\n }\n }\n\n return finalMessage;\n }\n\n /**\n * Underscores will be replaced by spaces and the first letter of each word will be capitalized\n *\n * @param string String to format\n * @return Formatted String with underscores replaced by spaces and the first letter of each word capitalized\n */\n private static String formatDefaultString(String string) {\n string = string.replace(\"_\", \" \");\n String newString = \"\";\n\n if (string.contains(\" \")) {\n for (int i = 0; i < string.split(\" \").length; i++) {\n String part = string.split(\" \")[i].toLowerCase();\n part = part.substring(0, 1).toUpperCase() + part.substring(1);\n newString = newString + part + (i == string.split(\" \").length - 1 ? \"\" : \" \");\n }\n\n return newString;\n } else {\n newString = string.substring(0, 1).toUpperCase() + string.substring(1).toLowerCase();\n }\n\n return newString;\n }\n\n\n}", "public abstract class Database {\n private final SimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n\n private boolean initialized;\n\n String tableShops;\n String tableLogs;\n String tableLogouts;\n String tableFields;\n\n ShopChest plugin;\n HikariDataSource dataSource;\n\n protected Database(ShopChest plugin) {\n this.plugin = plugin;\n }\n\n abstract HikariDataSource getDataSource();\n\n abstract String getQueryCreateTableShops();\n\n abstract String getQueryCreateTableLog();\n\n abstract String getQueryCreateTableLogout();\n\n abstract String getQueryCreateTableFields();\n\n abstract String getQueryGetTable();\n\n private int getDatabaseVersion() throws SQLException {\n try (Connection con = dataSource.getConnection()) {\n try (Statement s = con.createStatement()) {\n ResultSet rs = s.executeQuery(\"SELECT value FROM \" + tableFields + \" WHERE field='version'\");\n if (rs.next()) {\n return rs.getInt(\"value\");\n }\n }\n }\n return 0;\n }\n\n private void setDatabaseVersion(int version) throws SQLException {\n String queryUpdateVersion = \"REPLACE INTO \" + tableFields + \" VALUES ('version', ?)\";\n try (Connection con = dataSource.getConnection()) {\n try (PreparedStatement ps = con.prepareStatement(queryUpdateVersion)) {\n ps.setInt(1, version);\n ps.executeUpdate();\n }\n }\n }\n\n private boolean update() throws SQLException {\n String queryGetTable = getQueryGetTable();\n\n try (Connection con = dataSource.getConnection()) {\n boolean needsUpdate1 = false; // update \"shop_log\" to \"economy_logs\" and update \"shops\" with prefixes\n boolean needsUpdate2 = false; // create field table and set database version\n\n try (PreparedStatement ps = con.prepareStatement(queryGetTable)) {\n ps.setString(1, \"shop_log\");\n ResultSet rs = ps.executeQuery();\n if (rs.next()) {\n needsUpdate1 = true;\n }\n }\n\n try (PreparedStatement ps = con.prepareStatement(queryGetTable)) {\n ps.setString(1, tableFields);\n ResultSet rs = ps.executeQuery();\n if (!rs.next()) {\n needsUpdate2 = true;\n }\n }\n\n if (needsUpdate1) {\n String queryRenameTableLogouts = \"ALTER TABLE player_logout RENAME TO \" + tableLogouts;\n String queryRenameTableLogs = \"ALTER TABLE shop_log RENAME TO backup_shop_log\"; // for backup\n String queryRenameTableShops = \"ALTER TABLE shops RENAME TO backup_shops\"; // for backup\n\n plugin.getLogger().info(\"Updating database... (#1)\");\n\n // Rename logout table\n try (Statement s = con.createStatement()) {\n s.executeUpdate(queryRenameTableLogouts);\n }\n\n // Backup shops table\n try (Statement s = con.createStatement()) {\n s.executeUpdate(queryRenameTableShops);\n }\n\n // Backup log table\n try (Statement s = con.createStatement()) {\n s.executeUpdate(queryRenameTableLogs);\n }\n\n // Create new shops table\n try (Statement s = con.createStatement()) {\n s.executeUpdate(getQueryCreateTableShops());\n }\n\n // Create new log table\n try (Statement s = con.createStatement()) {\n s.executeUpdate(getQueryCreateTableLog());\n }\n\n // Convert shop table\n try (Statement s = con.createStatement()) {\n ResultSet rs = s.executeQuery(\"SELECT id,product FROM backup_shops\");\n while (rs.next()) {\n ItemStack is = Utils.decode(rs.getString(\"product\"));\n int amount = is.getAmount();\n is.setAmount(1);\n String product = Utils.encode(is);\n \n String insertQuery = \"INSERT INTO \" + tableShops + \" SELECT id,vendor,?,?,world,x,y,z,buyprice,sellprice,shoptype FROM backup_shops WHERE id = ?\";\n try (PreparedStatement ps = con.prepareStatement(insertQuery)) {\n ps.setString(1, product);\n ps.setInt(2, amount);\n ps.setInt(3, rs.getInt(\"id\"));\n ps.executeUpdate();\n }\n }\n }\n\n // Convert log table\n try (Statement s = con.createStatement()) {\n ResultSet rs = s.executeQuery(\"SELECT id,timestamp,executor,product,vendor FROM backup_shop_log\");\n while (rs.next()) {\n String timestamp = rs.getString(\"timestamp\");\n long time = 0L;\n\n try {\n time = dateFormat.parse(timestamp).getTime();\n } catch (ParseException e) {\n plugin.debug(\"Failed to parse timestamp '\" + timestamp + \"': Time is set to 0\");\n plugin.debug(e);\n }\n\n String player = rs.getString(\"executor\");\n String playerUuid = player.substring(0, 36);\n String playerName = player.substring(38, player.length() - 1);\n\n String oldProduct = rs.getString(\"product\");\n String product = oldProduct.split(\" x \")[1];\n int amount = Integer.valueOf(oldProduct.split(\" x \")[0]);\n\n String vendor = rs.getString(\"vendor\");\n String vendorUuid = vendor.substring(0, 36);\n String vendorName = vendor.substring(38).replaceAll(\"\\\\)( \\\\(ADMIN\\\\))?\", \"\");\n boolean admin = vendor.endsWith(\"(ADMIN)\");\n \n String insertQuery = \"INSERT INTO \" + tableLogs + \" SELECT id,-1,timestamp,?,?,?,?,'Unknown',?,?,?,?,world,x,y,z,price,type FROM backup_shop_log WHERE id = ?\";\n try (PreparedStatement ps = con.prepareStatement(insertQuery)) {\n ps.setLong(1, time);\n ps.setString(2, playerName);\n ps.setString(3, playerUuid);\n ps.setString(4, product);\n ps.setInt(5, amount);\n ps.setString(6, vendorName);\n ps.setString(7, vendorUuid);\n ps.setBoolean(8, admin);\n ps.setInt(9, rs.getInt(\"id\"));\n ps.executeUpdate();\n }\n }\n }\n }\n\n if (needsUpdate2) {\n plugin.getLogger().info(\"Updating database... (#2)\");\n\n // Create fields table\n try (Statement s = con.createStatement()) {\n s.executeUpdate(getQueryCreateTableFields());\n }\n\n setDatabaseVersion(2);\n }\n \n int databaseVersion = getDatabaseVersion();\n\n if (databaseVersion < 3) {\n // plugin.getLogger().info(\"Updating database... (#3)\");\n\n // Update database structure...\n\n // setDatabaseVersion(3);\n }\n\n int newDatabaseVersion = getDatabaseVersion();\n return needsUpdate1 || needsUpdate2 || newDatabaseVersion > databaseVersion;\n }\n }\n\n /**\n * <p>(Re-)Connects to the the database and initializes it.</p>\n * \n * All tables are created if necessary and if the database\n * structure has to be updated, that is done as well.\n * \n * @param callback Callback that - if succeeded - returns the amount of shops\n * that were found (as {@code int})\n */\n public void connect(final Callback<Integer> callback) {\n if (!Config.databaseTablePrefix.matches(\"^([a-zA-Z0-9\\\\-\\\\_]+)?$\")) {\n // Only letters, numbers dashes and underscores are allowed\n plugin.getLogger().severe(\"Database table prefix contains illegal letters, using 'shopchest_' prefix.\");\n Config.databaseTablePrefix = \"shopchest_\";\n }\n\n this.tableShops = Config.databaseTablePrefix + \"shops\";\n this.tableLogs = Config.databaseTablePrefix + \"economy_logs\";\n this.tableLogouts = Config.databaseTablePrefix + \"player_logouts\";\n this.tableFields = Config.databaseTablePrefix + \"fields\";\n\n new BukkitRunnable() {\n @Override\n public void run() {\n disconnect();\n\n try {\n dataSource = getDataSource();\n } catch (Exception e) {\n callback.onError(e);\n plugin.debug(e);\n return;\n }\n\n if (dataSource == null) {\n Exception e = new IllegalStateException(\"Data source is null\");\n callback.onError(e);\n plugin.debug(e);\n return;\n }\n\n try (Connection con = dataSource.getConnection()) {\n // Update database structure if necessary\n if (update()) {\n plugin.getLogger().info(\"Updating database finished\");\n }\n\n // Create shop table\n try (Statement s = con.createStatement()) {\n s.executeUpdate(getQueryCreateTableShops());\n }\n\n // Create log table\n try (Statement s = con.createStatement()) {\n s.executeUpdate(getQueryCreateTableLog());\n }\n\n // Create logout table\n try (Statement s = con.createStatement()) {\n s.executeUpdate(getQueryCreateTableLogout());\n }\n\n // Create fields table\n try (Statement s = con.createStatement()) {\n s.executeUpdate(getQueryCreateTableFields());\n }\n\n // Clean up economy log\n if (Config.cleanupEconomyLogDays > 0) {\n cleanUpEconomy(false);\n }\n\n // Count shops entries in database\n try (Statement s = con.createStatement()) {\n ResultSet rs = s.executeQuery(\"SELECT COUNT(id) FROM \" + tableShops);\n if (rs.next()) {\n int count = rs.getInt(1);\n initialized = true;\n \n plugin.debug(\"Initialized database with \" + count + \" entries\");\n\n if (callback != null) {\n callback.callSyncResult(count);\n }\n } else {\n throw new SQLException(\"Count result set has no entries\");\n }\n }\n } catch (SQLException e) {\n if (callback != null) {\n callback.callSyncError(e);\n }\n \n plugin.getLogger().severe(\"Failed to initialize or connect to database\");\n plugin.debug(\"Failed to initialize or connect to database\");\n plugin.debug(e);\n }\n }\n }.runTaskAsynchronously(plugin);\n }\n\n /**\n * Remove a shop from the database\n *\n * @param shop Shop to remove\n * @param callback Callback that - if succeeded - returns {@code null}\n */\n public void removeShop(final Shop shop, final Callback<Void> callback) {\n new BukkitRunnable() {\n @Override\n public void run() {\n try (Connection con = dataSource.getConnection();\n PreparedStatement ps = con.prepareStatement(\"DELETE FROM \" + tableShops + \" WHERE id = ?\")) {\n ps.setInt(1, shop.getID());\n ps.executeUpdate();\n\n plugin.debug(\"Removing shop from database (#\" + shop.getID() + \")\");\n\n if (callback != null) {\n callback.callSyncResult(null);\n }\n } catch (SQLException ex) {\n if (callback != null) {\n callback.callSyncError(ex);\n }\n\n plugin.getLogger().severe(\"Failed to remove shop from database\");\n plugin.debug(\"Failed to remove shop from database (#\" + shop.getID() + \")\");\n plugin.debug(ex);\n }\n }\n }.runTaskAsynchronously(plugin);\n }\n\n /**\n * Get shop amounts for each player\n * \n * @param callback Callback that returns a map of each player's shop amount\n */\n public void getShopAmounts(final Callback<Map<UUID, Integer>> callback) {\n new BukkitRunnable(){\n @Override\n public void run() {\n try (Connection con = dataSource.getConnection();\n Statement s = con.createStatement()) {\n ResultSet rs = s.executeQuery(\"SELECT vendor, COUNT(*) AS count FROM \" + tableShops + \" WHERE shoptype = 'NORMAL' GROUP BY vendor\");\n\n plugin.debug(\"Getting shop amounts from database\");\n\n Map<UUID, Integer> result = new HashMap<>();\n while (rs.next()) {\n UUID uuid = UUID.fromString(rs.getString(\"vendor\"));\n result.put(uuid, rs.getInt(\"count\"));\n }\n\n if (callback != null) {\n callback.callSyncResult(result);\n }\n } catch (SQLException ex) {\n if (callback != null) {\n callback.callSyncError(ex);\n }\n\n plugin.getLogger().severe(\"Failed to get shop amounts from database\");\n plugin.debug(\"Failed to get shop amounts from database\");\n plugin.debug(ex);\n } \n }\n }.runTaskAsynchronously(plugin);\n }\n\n /**\n * Get all shops of a player, including admin shops\n * \n * @param callback Callback that returns a set of shops of the given player\n */\n public void getShops(UUID playerUuid, final Callback<Collection<Shop>> callback) {\n new BukkitRunnable(){\n @Override\n public void run() {\n try (Connection con = dataSource.getConnection();\n PreparedStatement ps = con.prepareStatement(\"SELECT * FROM \" + tableShops + \" WHERE vendor = ?\")) {\n ps.setString(1, playerUuid.toString());\n ResultSet rs = ps.executeQuery();\n\n plugin.debug(\"Getting a player's shops from database\");\n\n Set<Shop> result = new HashSet<>();\n while (rs.next()) {\n int id = rs.getInt(\"id\");\n\n plugin.debug(\"Getting Shop... (#\" + id + \")\");\n\n int x = rs.getInt(\"x\");\n int y = rs.getInt(\"y\");\n int z = rs.getInt(\"z\");\n\n World world = plugin.getServer().getWorld(rs.getString(\"world\"));\n Location location = new Location(world, x, y, z);\n OfflinePlayer vendor = Bukkit.getOfflinePlayer(UUID.fromString(rs.getString(\"vendor\")));\n ItemStack itemStack = Utils.decode(rs.getString(\"product\"));\n int amount = rs.getInt(\"amount\");\n ShopProduct product = new ShopProduct(itemStack, amount);\n double buyPrice = rs.getDouble(\"buyprice\");\n double sellPrice = rs.getDouble(\"sellprice\");\n ShopType shopType = ShopType.valueOf(rs.getString(\"shoptype\"));\n\n plugin.debug(\"Initializing new shop... (#\" + id + \")\");\n\n result.add(new Shop(id, plugin, vendor, product, location, buyPrice, sellPrice, shopType));\n }\n\n if (callback != null) {\n callback.callSyncResult(result);\n }\n } catch (SQLException ex) {\n if (callback != null) {\n callback.callSyncError(ex);\n }\n\n plugin.getLogger().severe(\"Failed to get player's shops from database\");\n plugin.debug(\"Failed to get player's shops from database\");\n plugin.debug(ex);\n } \n }\n }.runTaskAsynchronously(plugin);\n }\n\n /**\n * Get all shops from the database that are located in the given chunks\n * \n * @param chunks Shops in these chunks are retrieved\n * @param callback Callback that returns an immutable collection of shops if succeeded\n */\n public void getShopsInChunks(final Chunk[] chunks, final Callback<Collection<Shop>> callback) {\n // Split chunks into packages containing each {splitSize} chunks at max\n int splitSize = 80;\n int parts = (int) Math.ceil(chunks.length / (double) splitSize);\n Chunk[][] splitChunks = new Chunk[parts][];\n for (int i = 0; i < parts; i++) {\n int size = i < parts - 1 ? splitSize : chunks.length % splitSize;\n Chunk[] tmp = new Chunk[size];\n System.arraycopy(chunks, i * splitSize, tmp, 0, size);\n splitChunks[i] = tmp;\n }\n\n new BukkitRunnable(){\n @Override\n public void run() {\n List<Shop> shops = new ArrayList<>();\n\n // Send a request for each chunk package\n for (Chunk[] newChunks : splitChunks) {\n\n // Map chunks by world\n Map<String, Set<Chunk>> chunksByWorld = new HashMap<>();\n for (Chunk chunk : newChunks) {\n String world = chunk.getWorld().getName();\n Set<Chunk> chunksForWorld = chunksByWorld.getOrDefault(world, new HashSet<>());\n chunksForWorld.add(chunk);\n chunksByWorld.put(world, chunksForWorld);\n }\n \n // Create query dynamically\n String query = \"SELECT * FROM \" + tableShops + \" WHERE \";\n for (String world : chunksByWorld.keySet()) {\n query += \"(world = ? AND (\";\n int chunkNum = chunksByWorld.get(world).size();\n for (int i = 0; i < chunkNum; i++) {\n query += \"((x BETWEEN ? AND ?) AND (z BETWEEN ? AND ?)) OR \";\n }\n query += \"1=0)) OR \";\n }\n query += \"1=0\";\n \n try (Connection con = dataSource.getConnection();\n PreparedStatement ps = con.prepareStatement(query)) {\n int index = 0;\n for (String world : chunksByWorld.keySet()) {\n ps.setString(++index, world);\n for (Chunk chunk : chunksByWorld.get(world)) {\n int minX = chunk.getX() * 16;\n int minZ = chunk.getZ() * 16;\n ps.setInt(++index, minX);\n ps.setInt(++index, minX + 15);\n ps.setInt(++index, minZ);\n ps.setInt(++index, minZ + 15);\n }\n }\n \n ResultSet rs = ps.executeQuery();\n while (rs.next()) {\n int id = rs.getInt(\"id\");\n \n plugin.debug(\"Getting Shop... (#\" + id + \")\");\n \n int x = rs.getInt(\"x\");\n int y = rs.getInt(\"y\");\n int z = rs.getInt(\"z\");\n \n World world = plugin.getServer().getWorld(rs.getString(\"world\"));\n Location location = new Location(world, x, y, z);\n OfflinePlayer vendor = Bukkit.getOfflinePlayer(UUID.fromString(rs.getString(\"vendor\")));\n ItemStack itemStack = Utils.decode(rs.getString(\"product\"));\n int amount = rs.getInt(\"amount\");\n ShopProduct product = new ShopProduct(itemStack, amount);\n double buyPrice = rs.getDouble(\"buyprice\");\n double sellPrice = rs.getDouble(\"sellprice\");\n ShopType shopType = ShopType.valueOf(rs.getString(\"shoptype\"));\n \n plugin.debug(\"Initializing new shop... (#\" + id + \")\");\n \n shops.add(new Shop(id, plugin, vendor, product, location, buyPrice, sellPrice, shopType));\n }\n } catch (SQLException ex) {\n if (callback != null) {\n callback.callSyncError(ex);\n }\n \n plugin.getLogger().severe(\"Failed to get shops from database\");\n plugin.debug(\"Failed to get shops\");\n plugin.debug(ex);\n\n return;\n }\n }\n \n if (callback != null) {\n callback.callSyncResult(Collections.unmodifiableCollection(shops));\n }\n };\n }.runTaskAsynchronously(plugin);\n }\n\n /**\n * Adds a shop to the database\n * \n * @param shop Shop to add\n * @param callback Callback that - if succeeded - returns the ID the shop was\n * given (as {@code int})\n */\n public void addShop(final Shop shop, final Callback<Integer> callback) {\n final String queryNoId = \"REPLACE INTO \" + tableShops + \" (vendor,product,amount,world,x,y,z,buyprice,sellprice,shoptype) VALUES(?,?,?,?,?,?,?,?,?,?)\";\n final String queryWithId = \"REPLACE INTO \" + tableShops + \" (id,vendor,product,amount,world,x,y,z,buyprice,sellprice,shoptype) VALUES(?,?,?,?,?,?,?,?,?,?,?)\";\n\n new BukkitRunnable() {\n @Override\n public void run() {\n String query = shop.hasId() ? queryWithId : queryNoId;\n\n try (Connection con = dataSource.getConnection();\n PreparedStatement ps = con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) {\n int i = 0;\n if (shop.hasId()) {\n i = 1;\n ps.setInt(1, shop.getID());\n }\n\n ps.setString(i+1, shop.getVendor().getUniqueId().toString());\n ps.setString(i+2, Utils.encode(shop.getProduct().getItemStack()));\n ps.setInt(i+3, shop.getProduct().getAmount());\n ps.setString(i+4, shop.getLocation().getWorld().getName());\n ps.setInt(i+5, shop.getLocation().getBlockX());\n ps.setInt(i+6, shop.getLocation().getBlockY());\n ps.setInt(i+7, shop.getLocation().getBlockZ());\n ps.setDouble(i+8, shop.getBuyPrice());\n ps.setDouble(i+9, shop.getSellPrice());\n ps.setString(i+10, shop.getShopType().toString());\n ps.executeUpdate();\n\n if (!shop.hasId()) {\n int shopId = -1;\n ResultSet rs = ps.getGeneratedKeys();\n if (rs.next()) {\n shopId = rs.getInt(1);\n }\n\n shop.setId(shopId);\n }\n\n if (callback != null) {\n callback.callSyncResult(shop.getID());\n }\n\n plugin.debug(\"Adding shop to database (#\" + shop.getID() + \")\");\n } catch (SQLException ex) {\n if (callback != null) {\n callback.callSyncError(ex);\n }\n\n plugin.getLogger().severe(\"Failed to add shop to database\");\n plugin.debug(\"Failed to add shop to database (#\" + shop.getID() + \")\");\n plugin.debug(ex);\n }\n }\n }.runTaskAsynchronously(plugin);\n }\n\n /**\n * Log an economy transaction to the database\n * \n * @param executor Player who bought/sold something\n * @param shop The {@link Shop} the player bought from or sold to\n * @param product The {@link ItemStack} that was bought/sold\n * @param price The price the product was bought or sold for\n * @param type Whether the executor bought or sold\n * @param callback Callback that - if succeeded - returns {@code null}\n */\n public void logEconomy(final Player executor, Shop shop, ShopProduct product, double price, Type type, final Callback<Void> callback) {\n final String query = \"INSERT INTO \" + tableLogs + \" (shop_id,timestamp,time,player_name,player_uuid,product_name,product,amount,\"\n + \"vendor_name,vendor_uuid,admin,world,x,y,z,price,type) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)\";\n\n if (Config.enableEconomyLog) {\n new BukkitRunnable() {\n @Override\n public void run() {\n try (Connection con = dataSource.getConnection();\n PreparedStatement ps = con.prepareStatement(query)) {\n\n long millis = System.currentTimeMillis();\n\n ps.setInt(1, shop.getID());\n ps.setString(2, dateFormat.format(millis));\n ps.setLong(3, millis);\n ps.setString(4, executor.getName());\n ps.setString(5, executor.getUniqueId().toString());\n ps.setString(6, product.getLocalizedName());\n ps.setString(7, Utils.encode(product.getItemStack()));\n ps.setInt(8, product.getAmount());\n ps.setString(9, shop.getVendor().getName());\n ps.setString(10, shop.getVendor().getUniqueId().toString());\n ps.setBoolean(11, shop.getShopType() == ShopType.ADMIN);\n ps.setString(12, shop.getLocation().getWorld().getName());\n ps.setInt(13, shop.getLocation().getBlockX());\n ps.setInt(14, shop.getLocation().getBlockY());\n ps.setInt(15, shop.getLocation().getBlockZ());\n ps.setDouble(16, price);\n ps.setString(17, type.toString());\n ps.executeUpdate();\n\n if (callback != null) {\n callback.callSyncResult(null);\n }\n\n plugin.debug(\"Logged economy transaction to database\");\n } catch (SQLException ex) {\n if (callback != null) {\n callback.callSyncError(ex);\n }\n\n plugin.getLogger().severe(\"Failed to log economy transaction to database\");\n plugin.debug(\"Failed to log economy transaction to database\");\n plugin.debug(ex);\n }\n }\n }.runTaskAsynchronously(plugin);\n } else {\n if (callback != null) {\n callback.callSyncResult(null);\n }\n }\n }\n\n /**\n * Cleans up the economy log to reduce file size\n * \n * @param async Whether the call should be executed asynchronously\n */\n public void cleanUpEconomy(boolean async) {\n BukkitRunnable runnable = new BukkitRunnable() {\n @Override\n public void run() {\n long time = System.currentTimeMillis() - Config.cleanupEconomyLogDays * 86400000L;\n String queryCleanUpLog = \"DELETE FROM \" + tableLogs + \" WHERE time < \" + time;\n String queryCleanUpPlayers = \"DELETE FROM \" + tableLogouts + \" WHERE time < \" + time;\n\n try (Connection con = dataSource.getConnection();\n Statement s = con.createStatement();\n Statement s2 = con.createStatement()) {\n s.executeUpdate(queryCleanUpLog);\n s2.executeUpdate(queryCleanUpPlayers);\n\n plugin.getLogger().info(\"Cleaned up economy log\");\n plugin.debug(\"Cleaned up economy log\");\n } catch (SQLException ex) {\n plugin.getLogger().severe(\"Failed to clean up economy log\");\n plugin.debug(\"Failed to clean up economy log\");\n plugin.debug(ex);\n }\n }\n };\n\n if (async) {\n runnable.runTaskAsynchronously(plugin);\n } else {\n runnable.run();\n }\n }\n\n /**\n * Get the revenue a player got while he was offline\n * \n * @param player Player whose revenue to get\n * @param logoutTime Time in milliseconds when he logged out the last time\n * @param callback Callback that - if succeeded - returns the revenue the\n * player made while offline (as {@code double})\n */\n public void getRevenue(final Player player, final long logoutTime, final Callback<Double> callback) {\n new BukkitRunnable() {\n @Override\n public void run() {\n double revenue = 0;\n\n try (Connection con = dataSource.getConnection();\n PreparedStatement ps = con.prepareStatement(\"SELECT * FROM \" + tableLogs + \" WHERE vendor_uuid = ?\")) {\n ps.setString(1, player.getUniqueId().toString());\n ResultSet rs = ps.executeQuery();\n\n while (rs.next()) {\n long timestamp = rs.getLong(\"time\");\n double singleRevenue = rs.getDouble(\"price\");\n ShopBuySellEvent.Type type = ShopBuySellEvent.Type.valueOf(rs.getString(\"type\"));\n\n if (type == ShopBuySellEvent.Type.SELL) {\n singleRevenue = -singleRevenue;\n }\n\n if (timestamp > logoutTime) {\n revenue += singleRevenue;\n }\n }\n\n if (callback != null) {\n callback.callSyncResult(revenue);\n }\n } catch (SQLException ex) {\n if (callback != null) {\n callback.callSyncError(ex);\n }\n\n plugin.getLogger().severe(\"Failed to get revenue from database\");\n plugin.debug(\"Failed to get revenue from player \\\"\" + player.getUniqueId().toString() + \"\\\"\");\n plugin.debug(ex);\n }\n }\n }.runTaskAsynchronously(plugin);\n }\n\n /**\n * Log a logout to the database\n * \n * @param player Player who logged out\n * @param callback Callback that - if succeeded - returns {@code null}\n */\n public void logLogout(final Player player, final Callback<Void> callback) {\n new BukkitRunnable() {\n @Override\n public void run() {\n try (Connection con = dataSource.getConnection();\n PreparedStatement ps = con.prepareStatement(\"REPLACE INTO \" + tableLogouts + \" (player,time) VALUES(?,?)\")) {\n ps.setString(1, player.getUniqueId().toString());\n ps.setLong(2, System.currentTimeMillis());\n ps.executeUpdate();\n\n if (callback != null) {\n callback.callSyncResult(null);\n }\n\n plugin.debug(\"Logged logout to database\");\n } catch (final SQLException ex) {\n if (callback != null) {\n callback.callSyncError(ex);\n }\n\n plugin.getLogger().severe(\"Failed to log last logout to database\");\n plugin.debug(\"Failed to log logout to database\");\n plugin.debug(ex);\n }\n }\n }.runTaskAsynchronously(plugin);\n }\n\n /**\n * Get the last logout of a player\n * \n * @param player Player who logged out\n * @param callback Callback that - if succeeded - returns the time in\n * milliseconds the player logged out (as {@code long})\n * or {@code -1} if the player has not logged out yet.\n */\n public void getLastLogout(final Player player, final Callback<Long> callback) {\n new BukkitRunnable() {\n @Override\n public void run() {\n try (Connection con = dataSource.getConnection();\n PreparedStatement ps = con.prepareStatement(\"SELECT * FROM \" + tableLogouts + \" WHERE player = ?\")) {\n ps.setString(1, player.getUniqueId().toString());\n ResultSet rs = ps.executeQuery();\n\n if (rs.next()) {\n if (callback != null) {\n callback.callSyncResult(rs.getLong(\"time\"));\n }\n }\n\n if (callback != null) {\n callback.callSyncResult(-1L);\n }\n } catch (SQLException ex) {\n if (callback != null) {\n callback.callSyncError(ex);\n }\n\n plugin.getLogger().severe(\"Failed to get last logout from database\");\n plugin.debug(\"Failed to get last logout from player \\\"\" + player.getName() + \"\\\"\");\n plugin.debug(ex);\n }\n }\n }.runTaskAsynchronously(plugin);\n }\n\n /**\n * Closes the data source\n */\n public void disconnect() {\n if (dataSource != null) {\n dataSource.close();\n dataSource = null;\n }\n }\n\n /**\n * Returns whether a connection to the database has been established\n */\n public boolean isInitialized() {\n return initialized;\n }\n\n public enum DatabaseType {\n SQLite, MySQL\n }\n}", "public class ItemUtils {\n\n public static Map<Enchantment, Integer> getEnchantments(ItemStack itemStack) {\n if (itemStack.getItemMeta() instanceof EnchantmentStorageMeta) {\n EnchantmentStorageMeta esm = (EnchantmentStorageMeta) itemStack.getItemMeta();\n return esm.getStoredEnchants();\n } else {\n return itemStack.getEnchantments();\n }\n }\n\n public static PotionType getPotionEffect(ItemStack itemStack) {\n if (itemStack.getItemMeta() instanceof PotionMeta) { \n if (Utils.getMajorVersion() < 9) {\n return Potion.fromItemStack(itemStack).getType();\n } else {\n return ((PotionMeta) itemStack.getItemMeta()).getBasePotionData().getType();\n }\n }\n\n return null;\n }\n\n public static boolean isExtendedPotion(ItemStack itemStack) {\n if (itemStack.getItemMeta() instanceof PotionMeta) {\n if (Utils.getMajorVersion() < 9) {\n return Potion.fromItemStack(itemStack).hasExtendedDuration();\n } else {\n return ((PotionMeta) itemStack.getItemMeta()).getBasePotionData().isExtended();\n }\n }\n\n return false;\n }\n\n public static boolean isBannerPattern(ItemStack itemStack) {\n return itemStack.getType().name().endsWith(\"BANNER_PATTERN\");\n }\n\n public static boolean isAir(Material type) {\n return Arrays.asList(\"AIR\", \"CAVE_AIR\", \"VOID_AIR\").contains(type.name());\n }\n\n /**\n * Get the {@link ItemStack} from a String\n * @param item Serialized ItemStack e.g. {@code \"STONE\"} or {@code \"STONE:1\"}\n * @return The de-serialized ItemStack or {@code null} if the serialized item is invalid\n */\n public static ItemStack getItemStack(String item) {\n if (item.trim().isEmpty()) return null;\n\n if (item.contains(\":\")) {\n Material mat = Material.getMaterial(item.split(\":\")[0]);\n if (mat == null) return null;\n return new ItemStack(mat, 1, Short.parseShort(item.split(\":\")[1]));\n } else {\n Material mat = Material.getMaterial(item);\n if (mat == null) return null;\n return new ItemStack(mat, 1);\n }\n }\n\n}", "public class Utils {\n static NMSClassResolver nmsClassResolver = new NMSClassResolver();\n static Class<?> entityClass = nmsClassResolver.resolveSilent(\"world.entity.Entity\");\n static Class<?> entityArmorStandClass = nmsClassResolver.resolveSilent(\"world.entity.decoration.EntityArmorStand\");\n static Class<?> entityItemClass = nmsClassResolver.resolveSilent(\"world.entity.item.EntityItem\");\n static Class<?> dataWatcherClass = nmsClassResolver.resolveSilent(\"network.syncher.DataWatcher\");\n static Class<?> dataWatcherObjectClass = nmsClassResolver.resolveSilent(\"network.syncher.DataWatcherObject\");\n static Class<?> chatSerializerClass = nmsClassResolver.resolveSilent(\"ChatSerializer\", \"network.chat.IChatBaseComponent$ChatSerializer\");\n\n private Utils() {}\n\n /**\n * Check if two items are similar to each other\n * @param itemStack1 The first item\n * @param itemStack2 The second item\n * @return {@code true} if the given items are similar or {@code false} if not\n */\n public static boolean isItemSimilar(ItemStack itemStack1, ItemStack itemStack2) {\n if (itemStack1 == null || itemStack2 == null) {\n return false;\n }\n\n ItemMeta itemMeta1 = itemStack1.getItemMeta();\n ItemMeta itemMeta2 = itemStack2.getItemMeta();\n\n if (itemMeta1 instanceof BookMeta && itemMeta2 instanceof BookMeta) {\n BookMeta bookMeta1 = (BookMeta) itemStack1.getItemMeta();\n BookMeta bookMeta2 = (BookMeta) itemStack2.getItemMeta();\n\n if ((getMajorVersion() == 9 && getRevision() == 1) || getMajorVersion() == 8) {\n CustomBookMeta.Generation generation1 = CustomBookMeta.getGeneration(itemStack1);\n CustomBookMeta.Generation generation2 = CustomBookMeta.getGeneration(itemStack2);\n\n if (generation1 == null) CustomBookMeta.setGeneration(itemStack1, CustomBookMeta.Generation.ORIGINAL);\n if (generation2 == null) CustomBookMeta.setGeneration(itemStack2, CustomBookMeta.Generation.ORIGINAL);\n } else {\n if (bookMeta1.getGeneration() == null) bookMeta1.setGeneration(BookMeta.Generation.ORIGINAL);\n if (bookMeta2.getGeneration() == null) bookMeta2.setGeneration(BookMeta.Generation.ORIGINAL);\n }\n\n itemStack1.setItemMeta(bookMeta1);\n itemStack2.setItemMeta(bookMeta2);\n\n itemStack1 = decode(encode(itemStack1));\n itemStack2 = decode(encode(itemStack2));\n }\n\n return itemStack1.isSimilar(itemStack2);\n }\n\n /**\n * Gets the amount of items in an inventory\n *\n * @param inventory The inventory, in which the items are counted\n * @param itemStack The items to count\n * @return Amount of given items in the given inventory\n */\n public static int getAmount(Inventory inventory, ItemStack itemStack) {\n int amount = 0;\n\n ArrayList<ItemStack> inventoryItems = new ArrayList<>();\n\n if (inventory instanceof PlayerInventory) {\n for (int i = 0; i < 37; i++) {\n if (i == 36) {\n if (getMajorVersion() < 9) {\n break;\n }\n i = 40;\n }\n inventoryItems.add(inventory.getItem(i));\n }\n } else {\n for (int i = 0; i < inventory.getSize(); i++) {\n inventoryItems.add(inventory.getItem(i));\n }\n }\n\n for (ItemStack item : inventoryItems) {\n if (isItemSimilar(item, itemStack)) {\n amount += item.getAmount();\n }\n }\n\n return amount;\n }\n\n /**\n * Get the amount of the given item, that fits in the given inventory\n *\n * @param inventory Inventory, where to search for free space\n * @param itemStack Item, of which the amount that fits in the inventory should be returned\n * @return Amount of the given item, that fits in the given inventory\n */\n public static int getFreeSpaceForItem(Inventory inventory, ItemStack itemStack) {\n HashMap<Integer, Integer> slotFree = new HashMap<>();\n\n if (inventory instanceof PlayerInventory) {\n for (int i = 0; i < 37; i++) {\n if (i == 36) {\n if (getMajorVersion() < 9) {\n break;\n }\n i = 40;\n }\n\n ItemStack item = inventory.getItem(i);\n if (item == null || item.getType() == Material.AIR) {\n slotFree.put(i, itemStack.getMaxStackSize());\n } else {\n if (isItemSimilar(item, itemStack)) {\n int amountInSlot = item.getAmount();\n int amountToFullStack = itemStack.getMaxStackSize() - amountInSlot;\n slotFree.put(i, amountToFullStack);\n }\n }\n }\n } else {\n for (int i = 0; i < inventory.getSize(); i++) {\n ItemStack item = inventory.getItem(i);\n if (item == null || item.getType() == Material.AIR) {\n slotFree.put(i, itemStack.getMaxStackSize());\n } else {\n if (isItemSimilar(item, itemStack)) {\n int amountInSlot = item.getAmount();\n int amountToFullStack = itemStack.getMaxStackSize() - amountInSlot;\n slotFree.put(i, amountToFullStack);\n }\n }\n }\n }\n\n int freeAmount = 0;\n for (int value : slotFree.values()) {\n freeAmount += value;\n }\n\n return freeAmount;\n }\n\n /**\n * @param p Player whose item in his main hand should be returned\n * @return {@link ItemStack} in his main hand, or {@code null} if he doesn't hold one\n */\n public static ItemStack getItemInMainHand(Player p) {\n if (getMajorVersion() < 9) {\n if (p.getItemInHand().getType() == Material.AIR)\n return null;\n else\n return p.getItemInHand();\n }\n\n if (p.getInventory().getItemInMainHand().getType() == Material.AIR)\n return null;\n else\n return p.getInventory().getItemInMainHand();\n }\n\n /**\n * @param p Player whose item in his off hand should be returned\n * @return {@link ItemStack} in his off hand, or {@code null} if he doesn't hold one or the server version is below 1.9\n */\n public static ItemStack getItemInOffHand(Player p) {\n if (getMajorVersion() < 9)\n return null;\n else if (p.getInventory().getItemInOffHand().getType() == Material.AIR)\n return null;\n else\n return p.getInventory().getItemInOffHand();\n }\n\n /**\n * @param p Player whose item in his hand should be returned\n * @return Item in his main hand, or the item in his off if he doesn't have one in this main hand, or {@code null}\n * if he doesn't have one in both hands\n */\n public static ItemStack getPreferredItemInHand(Player p) {\n if (getMajorVersion() < 9)\n return getItemInMainHand(p);\n else if (getItemInMainHand(p) != null)\n return getItemInMainHand(p);\n else\n return getItemInOffHand(p);\n }\n\n /**\n * @param p Player to check if he has an axe in one of his hands\n * @return Whether a player has an axe in one of his hands\n */\n public static boolean hasAxeInHand(Player p) {\n List<String> axes;\n if (Utils.getMajorVersion() < 13)\n axes = Arrays.asList(\"WOOD_AXE\", \"STONE_AXE\", \"IRON_AXE\", \"GOLD_AXE\", \"DIAMOND_AXE\");\n else \n axes = Arrays.asList(\"WOODEN_AXE\", \"STONE_AXE\", \"IRON_AXE\", \"GOLDEN_AXE\", \"DIAMOND_AXE\");\n\n ItemStack item = getItemInMainHand(p);\n if (item == null || !axes.contains(item.getType().toString())) {\n item = getItemInOffHand(p);\n }\n\n return item != null && axes.contains(item.getType().toString());\n }\n\n /**\n * <p>Check if a player is allowed to create a shop that sells or buys the given item.</p>\n * @param player Player to check\n * @param item Item to be sold or bought\n * @param buy Whether buying should be enabled\n * @param sell Whether selling should be enabled\n * @return Whether the player is allowed\n */\n public static boolean hasPermissionToCreateShop(Player player, ItemStack item, boolean buy, boolean sell) {\n if (hasPermissionToCreateShop(player, item, Permissions.CREATE)) {\n return true;\n } else if (!sell && buy && hasPermissionToCreateShop(player, item,Permissions.CREATE_BUY)) {\n return true;\n } else if (!buy && sell && hasPermissionToCreateShop(player, item, Permissions.CREATE_SELL)) {\n return true;\n } else if (buy && sell && hasPermissionToCreateShop(player, item, Permissions.CREATE_BUY, Permissions.CREATE_SELL)) {\n return true;\n }\n\n return false;\n }\n\n private static boolean hasPermissionToCreateShop(Player player, ItemStack item, String... permissions) {\n for (String permission : permissions) {\n boolean b1 = false;\n boolean b2 = false;\n boolean b3 = false;\n\n if (player.hasPermission(permission)) {\n b1 = true;\n }\n\n if (item != null) {\n if (item.getDurability() == 0) {\n String perm1 = permission + \".\" + item.getType().toString();\n String perm2 = permission + \".\" + item.getType().toString() + \".0\";\n\n if (player.hasPermission(perm1) || player.hasPermission(perm2)) {\n b2 = true;\n }\n }\n\n if (player.hasPermission(permission + \".\" + item.getType().toString() + \".\" + item.getDurability())) {\n b3 = true;\n }\n }\n\n if (!(b1 || b2 || b3)) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Get a set for the location(s) of the shop's chest(s)\n * @param shop The shop\n * @return A set of 1 or 2 locations\n */\n public static Set<Location> getChestLocations(Shop shop) {\n Set<Location> chestLocations = new HashSet<>();\n InventoryHolder ih = shop.getInventoryHolder();\n if (ih instanceof DoubleChest) {\n DoubleChest dc = (DoubleChest) ih;\n chestLocations.add(((Chest) dc.getLeftSide()).getLocation());\n chestLocations.add(((Chest) dc.getRightSide()).getLocation());\n } else {\n chestLocations.add(shop.getLocation());\n }\n return chestLocations;\n }\n\n /**\n * Send a clickable update notification to the given player.\n * @param plugin An instance of the {@link ShopChest} plugin\n * @param p The player to receive the notification\n */\n public static void sendUpdateMessage(ShopChest plugin, Player p) {\n JsonBuilder jb = new JsonBuilder(plugin);\n Map<String, JsonBuilder.Part> hoverEvent = new HashMap<>();\n hoverEvent.put(\"action\", new JsonBuilder.Part(\"show_text\"));\n hoverEvent.put(\"value\", new JsonBuilder.Part(LanguageUtils.getMessage(Message.UPDATE_CLICK_TO_DOWNLOAD)));\n\n Map<String, JsonBuilder.Part> clickEvent = new HashMap<>();\n clickEvent.put(\"action\", new JsonBuilder.Part(\"open_url\"));\n clickEvent.put(\"value\", new JsonBuilder.Part(plugin.getDownloadLink()));\n\n JsonBuilder.PartMap rootPart = JsonBuilder.parse(LanguageUtils.getMessage(Message.UPDATE_AVAILABLE,\n new Replacement(Placeholder.VERSION, plugin.getLatestVersion()))).toMap();\n \n rootPart.setValue(\"hoverEvent\", new JsonBuilder.PartMap(hoverEvent));\n rootPart.setValue(\"clickEvent\", new JsonBuilder.PartMap(clickEvent));\n \n jb.setRootPart(rootPart);\n jb.sendJson(p);\n }\n\n /**\n * Create a NMS data watcher object to send via a {@code PacketPlayOutEntityMetadata} packet.\n * Gravity will be disabled and the custom name will be displayed if available.\n * @param customName Custom Name of the entity or {@code null}\n * @param nmsItemStack NMS ItemStack or {@code null} if armor stand\n */\n public static Object createDataWatcher(String customName, Object nmsItemStack) {\n String version = getServerVersion();\n int majorVersion = getMajorVersion();\n\n try {\n byte entityFlags = nmsItemStack == null ? (byte) 0b100000 : 0; // invisible if armor stand\n byte armorStandFlags = nmsItemStack == null ? (byte) 0b10000 : 0; // marker (since 1.8_R2)\n\n Object dataWatcher = dataWatcherClass.getConstructor(entityClass).newInstance((Object) null);\n if (majorVersion < 9) {\n if (getRevision() == 1) armorStandFlags = 0; // Marker not supported on 1.8_R1\n\n Method a = dataWatcherClass.getMethod(\"a\", int.class, Object.class);\n a.invoke(dataWatcher, 0, entityFlags); // flags\n a.invoke(dataWatcher, 1, (short) 300); // air ticks (?)\n a.invoke(dataWatcher, 3, (byte) (customName != null ? 1 : 0)); // custom name visible\n a.invoke(dataWatcher, 2, customName != null ? customName : \"\"); // custom name\n a.invoke(dataWatcher, 4, (byte) 1); // silent\n a.invoke(dataWatcher, 10, nmsItemStack == null ? armorStandFlags : nmsItemStack); // item / armor stand flags\n } else {\n Method register = dataWatcherClass.getMethod(\"register\", dataWatcherObjectClass, Object.class);\n String[] dataWatcherObjectFieldNames;\n\n if (\"v1_9_R1\".equals(version)) {\n dataWatcherObjectFieldNames = new String[] {\"ax\", \"ay\", \"aA\", \"az\", \"aB\", null, \"c\", \"a\"};\n } else if (\"v1_9_R2\".equals(version)){\n dataWatcherObjectFieldNames = new String[] {\"ay\", \"az\", \"aB\", \"aA\", \"aC\", null, \"c\", \"a\"};\n } else if (\"v1_10_R1\".equals(version)) {\n dataWatcherObjectFieldNames = new String[] {\"aa\", \"az\", \"aB\", \"aA\", \"aC\", \"aD\", \"c\", \"a\"};\n } else if (\"v1_11_R1\".equals(version)) {\n dataWatcherObjectFieldNames = new String[] {\"Z\", \"az\", \"aB\", \"aA\", \"aC\", \"aD\", \"c\", \"a\"};\n } else if (\"v1_12_R1\".equals(version) || \"v1_12_R2\".equals(version)) {\n dataWatcherObjectFieldNames = new String[] {\"Z\", \"aA\", \"aC\", \"aB\", \"aD\", \"aE\", \"c\", \"a\"};\n } else if (\"v1_13_R1\".equals(version) || \"v1_13_R2\".equals(version)) {\n dataWatcherObjectFieldNames = new String[] {\"ac\", \"aD\", \"aF\", \"aE\", \"aG\", \"aH\", \"b\", \"a\"};\n } else if (\"v1_14_R1\".equals(version)) {\n dataWatcherObjectFieldNames = new String[] {\"W\", \"AIR_TICKS\", \"aA\", \"az\", \"aB\", \"aC\", \"ITEM\", \"b\"};\n } else if (\"v1_15_R1\".equals(version)) {\n dataWatcherObjectFieldNames = new String[] {\"T\", \"AIR_TICKS\", \"aA\", \"az\", \"aB\", \"aC\", \"ITEM\", \"b\"};\n } else if (\"v1_16_R1\".equals(version)) {\n dataWatcherObjectFieldNames = new String[] {\"T\", \"AIR_TICKS\", \"ay\", \"ax\", \"az\", \"aA\", \"ITEM\", \"b\"};\n } else if (\"v1_16_R2\".equals(version) || \"v1_16_R3\".equals(version)) {\n dataWatcherObjectFieldNames = new String[] {\"S\", \"AIR_TICKS\", \"ar\", \"aq\", \"as\", \"at\", \"ITEM\", \"b\"};\n } else if (\"v1_17_R1\".equals(version)) {\n dataWatcherObjectFieldNames = new String[] {\"Z\", \"aI\", \"aK\", \"aJ\", \"aL\", \"aM\", \"c\", \"bG\"};\n } else {\n return null;\n }\n\n Field fEntityFlags = entityClass.getDeclaredField(dataWatcherObjectFieldNames[0]);\n Field fAirTicks = entityClass.getDeclaredField(dataWatcherObjectFieldNames[1]);\n Field fNameVisible = entityClass.getDeclaredField(dataWatcherObjectFieldNames[2]);\n Field fCustomName = entityClass.getDeclaredField(dataWatcherObjectFieldNames[3]);\n Field fSilent = entityClass.getDeclaredField(dataWatcherObjectFieldNames[4]);\n Field fNoGravity = majorVersion >= 10 ? entityClass.getDeclaredField(dataWatcherObjectFieldNames[5]) : null;\n Field fItem = entityItemClass.getDeclaredField(dataWatcherObjectFieldNames[6]);\n Field fArmorStandFlags = entityArmorStandClass.getDeclaredField(dataWatcherObjectFieldNames[7]);\n\n fEntityFlags.setAccessible(true);\n fAirTicks.setAccessible(true);\n fNameVisible.setAccessible(true);\n fCustomName.setAccessible(true);\n fSilent.setAccessible(true);\n if (majorVersion >= 10) fNoGravity.setAccessible(true);\n fItem.setAccessible(true);\n fArmorStandFlags.setAccessible(true);\n \n register.invoke(dataWatcher, fEntityFlags.get(null), entityFlags);\n register.invoke(dataWatcher, fAirTicks.get(null), 300);\n register.invoke(dataWatcher, fNameVisible.get(null), customName != null);\n register.invoke(dataWatcher, fSilent.get(null), true);\n if (majorVersion < 13) register.invoke(dataWatcher, fCustomName.get(null), customName != null ? customName : \"\");\n \n if (nmsItemStack != null) {\n register.invoke(dataWatcher, fItem.get(null), majorVersion < 11 ? com.google.common.base.Optional.of(nmsItemStack) : nmsItemStack);\n } else {\n register.invoke(dataWatcher, fArmorStandFlags.get(null), armorStandFlags);\n }\n\n if (majorVersion >= 10) {\n register.invoke(dataWatcher, fNoGravity.get(null), true);\n if (majorVersion >= 13) {\n if (customName != null) {\n Object iChatBaseComponent = chatSerializerClass.getMethod(\"a\", String.class).invoke(null, JsonBuilder.parse(customName).toString());\n register.invoke(dataWatcher, fCustomName.get(null), Optional.of(iChatBaseComponent));\n } else {\n register.invoke(dataWatcher, fCustomName.get(null), Optional.empty());\n }\n }\n }\n }\n return dataWatcher;\n } catch (InstantiationException | InvocationTargetException | NoSuchFieldException | IllegalAccessException | NoSuchMethodException e) {\n ShopChest.getInstance().getLogger().severe(\"Failed to create data watcher!\");\n ShopChest.getInstance().debug(\"Failed to create data watcher\");\n ShopChest.getInstance().debug(e);\n }\n return null;\n }\n\n /**\n * Get a free entity ID for use in {@link #createPacketSpawnEntity(ShopChest, int, UUID, Location, Vector, EntityType)}\n * \n * @return The id or {@code -1} if a free entity ID could not be retrieved.\n */\n public static int getFreeEntityId() {\n try {\n Field entityCountField = new FieldResolver(entityClass).resolve(\"entityCount\", \"b\");\n entityCountField.setAccessible(true);\n if (entityCountField.getType() == int.class) {\n int id = entityCountField.getInt(null);\n entityCountField.setInt(null, id+1);\n return id;\n } else if (entityCountField.getType() == AtomicInteger.class) {\n return ((AtomicInteger) entityCountField.get(null)).incrementAndGet();\n }\n\n return -1;\n } catch (Exception e) {\n return -1;\n }\n }\n\n /**\n * Create a {@code PacketPlayOutSpawnEntity} object.\n * Only {@link EntityType#ARMOR_STAND} and {@link EntityType#DROPPED_ITEM} are supported! \n */\n public static Object createPacketSpawnEntity(ShopChest plugin, int id, UUID uuid, Location loc, EntityType type) {\n try {\n Class<?> packetPlayOutSpawnEntityClass = nmsClassResolver.resolveSilent(\"network.protocol.game.PacketPlayOutSpawnEntity\");\n Class<?> entityTypesClass = nmsClassResolver.resolveSilent(\"world.entity.EntityTypes\");\n Class<?> vec3dClass = nmsClassResolver.resolveSilent(\"world.phys.Vec3D\");\n\n boolean isPre9 = getMajorVersion() < 9;\n boolean isPre14 = getMajorVersion() < 14;\n\n double y = loc.getY();\n if (type == EntityType.ARMOR_STAND && !getServerVersion().equals(\"v1_8_R1\")) {\n // Marker armor stand => lift by normal armor stand height\n y += 1.975;\n }\n\n if (getMajorVersion() >= 17) {\n // Empty packet constructor does not exist anymore in 1.17+\n Constructor<?> c = packetPlayOutSpawnEntityClass.getConstructor(int.class, UUID.class, double.class, double.class, double.class,\n float.class, float.class, entityTypesClass, int.class, vec3dClass);\n\n Object vec3d = vec3dClass.getField(\"a\").get(null);\n Object entityType = entityTypesClass.getField(type == EntityType.ARMOR_STAND ? \"c\" : \"Q\").get(null);\n\n return c.newInstance(id, uuid, loc.getX(), y, loc.getZ(), 0f, 0f, entityType, 0, vec3d);\n }\n \n Object packet = packetPlayOutSpawnEntityClass.getConstructor().newInstance();\n\n Field[] fields = new Field[12];\n fields[0] = packetPlayOutSpawnEntityClass.getDeclaredField(\"a\"); // ID\n fields[1] = packetPlayOutSpawnEntityClass.getDeclaredField(\"b\"); // UUID (Only 1.9+)\n fields[2] = packetPlayOutSpawnEntityClass.getDeclaredField(isPre9 ? \"b\" : \"c\"); // Loc X\n fields[3] = packetPlayOutSpawnEntityClass.getDeclaredField(isPre9 ? \"c\" : \"d\"); // Loc Y\n fields[4] = packetPlayOutSpawnEntityClass.getDeclaredField(isPre9 ? \"d\" : \"e\"); // Loc Z\n fields[5] = packetPlayOutSpawnEntityClass.getDeclaredField(isPre9 ? \"e\" : \"f\"); // Mot X\n fields[6] = packetPlayOutSpawnEntityClass.getDeclaredField(isPre9 ? \"f\" : \"g\"); // Mot Y\n fields[7] = packetPlayOutSpawnEntityClass.getDeclaredField(isPre9 ? \"g\" : \"h\"); // Mot Z\n fields[8] = packetPlayOutSpawnEntityClass.getDeclaredField(isPre9 ? \"h\" : \"i\"); // Pitch\n fields[9] = packetPlayOutSpawnEntityClass.getDeclaredField(isPre9 ? \"i\" : \"j\"); // Yaw\n fields[10] = packetPlayOutSpawnEntityClass.getDeclaredField(isPre9 ? \"j\" : \"k\"); // Type\n fields[11] = packetPlayOutSpawnEntityClass.getDeclaredField(isPre9 ? \"k\" : \"l\"); // Data\n\n for (Field field : fields) {\n field.setAccessible(true);\n }\n\n Object entityType = null;\n if (!isPre14) {\n entityType = entityTypesClass.getField(type == EntityType.ARMOR_STAND ? \"ARMOR_STAND\" : \"ITEM\").get(null);\n }\n\n fields[0].set(packet, id);\n if (!isPre9) fields[1].set(packet, uuid);\n if (isPre9) {\n fields[2].set(packet, (int)(loc.getX() * 32));\n fields[3].set(packet, (int)(y * 32));\n fields[4].set(packet, (int)(loc.getZ() * 32));\n } else {\n fields[2].set(packet, loc.getX());\n fields[3].set(packet, y);\n fields[4].set(packet, loc.getZ());\n }\n fields[5].set(packet, 0);\n fields[6].set(packet, 0);\n fields[7].set(packet, 0);\n fields[8].set(packet, 0);\n fields[9].set(packet, 0);\n if (isPre14) fields[10].set(packet, type == EntityType.ARMOR_STAND ? 78 : 2);\n else fields[10].set(packet, entityType);\n fields[11].set(packet, 0);\n\n return packet;\n } catch (NoSuchMethodException | NoSuchFieldException | IllegalAccessException | InvocationTargetException | InstantiationException e) {\n plugin.getLogger().severe(\"Failed to create packet to spawn entity!\");\n plugin.debug(\"Failed to create packet to spawn entity!\");\n plugin.debug(e);\n return null;\n }\n }\n\n /**\n * Send a packet to a player\n * @param plugin An instance of the {@link ShopChest} plugin\n * @param packet Packet to send\n * @param player Player to which the packet should be sent\n * @return {@code true} if the packet was sent, or {@code false} if an exception was thrown\n */\n public static boolean sendPacket(ShopChest plugin, Object packet, Player player) {\n try {\n if (packet == null) {\n plugin.debug(\"Failed to send packet: Packet is null\");\n return false;\n }\n\n Class<?> packetClass = nmsClassResolver.resolveSilent(\"network.protocol.Packet\");\n if (packetClass == null) {\n plugin.debug(\"Failed to send packet: Could not find Packet class\");\n return false;\n }\n\n Object nmsPlayer = player.getClass().getMethod(\"getHandle\").invoke(player);\n Field fConnection = (new FieldResolver(nmsPlayer.getClass())).resolve(\"playerConnection\", \"b\");\n Object playerConnection = fConnection.get(nmsPlayer);\n\n playerConnection.getClass().getMethod(\"sendPacket\", packetClass).invoke(playerConnection, packet);\n\n return true;\n } catch (NoSuchMethodException | NoSuchFieldException | IllegalAccessException | InvocationTargetException e) {\n plugin.getLogger().severe(\"Failed to send packet \" + packet.getClass().getName());\n plugin.debug(\"Failed to send packet \" + packet.getClass().getName());\n plugin.debug(e);\n return false;\n }\n }\n\n /**\n * @return The current server version with revision number (e.g. v1_9_R2, v1_10_R1)\n */\n public static String getServerVersion() {\n String packageName = Bukkit.getServer().getClass().getPackage().getName();\n\n return packageName.substring(packageName.lastIndexOf('.') + 1);\n }\n\n /**\n * @return The revision of the current server version (e.g. <i>2</i> for v1_9_R2, <i>1</i> for v1_10_R1)\n */\n public static int getRevision() {\n return Integer.parseInt(getServerVersion().substring(getServerVersion().length() - 1));\n }\n\n /**\n * @return The major version of the server (e.g. <i>9</i> for 1.9.2, <i>10</i> for 1.10)\n */\n public static int getMajorVersion() {\n return Integer.parseInt(getServerVersion().split(\"_\")[1]);\n }\n\n /**\n * Encodes an {@link ItemStack} in a Base64 String\n * @param itemStack {@link ItemStack} to encode\n * @return Base64 encoded String\n */\n public static String encode(ItemStack itemStack) {\n YamlConfiguration config = new YamlConfiguration();\n config.set(\"i\", itemStack);\n return Base64.getEncoder().encodeToString(config.saveToString().getBytes(StandardCharsets.UTF_8));\n }\n\n /**\n * Decodes an {@link ItemStack} from a Base64 String\n * @param string Base64 encoded String to decode\n * @return Decoded {@link ItemStack}\n */\n public static ItemStack decode(String string) {\n YamlConfiguration config = new YamlConfiguration();\n try {\n config.loadFromString(new String(Base64.getDecoder().decode(string), StandardCharsets.UTF_8));\n } catch (IllegalArgumentException | InvalidConfigurationException e) {\n e.printStackTrace();\n return null;\n }\n return config.getItemStack(\"i\", null);\n }\n\n\n}" ]
import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.Reader; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.inventory.ItemStack; import de.epiceric.shopchest.ShopChest; import de.epiceric.shopchest.language.LanguageUtils; import de.epiceric.shopchest.sql.Database; import de.epiceric.shopchest.utils.ItemUtils; import de.epiceric.shopchest.utils.Utils;
package de.epiceric.shopchest.config; public class Config { /** * The item with which a player can click a shop to retrieve information **/ public static ItemStack shopInfoItem; /** * The default value for the custom WorldGuard flag 'create-shop' **/ public static boolean wgAllowCreateShopDefault; /** * The default value for the custom WorldGuard flag 'use-admin-shop' **/ public static boolean wgAllowUseAdminShopDefault; /** * The default value for the custom WorldGuard flag 'use-shop' **/ public static boolean wgAllowUseShopDefault; /** * The types of town plots residents are allowed to create shops in **/ public static List<String> townyShopPlotsResidents; /** * The types of town plots the mayor is allowed to create shops in **/ public static List<String> townyShopPlotsMayor; /** * The types of town plots the king is allowed to create shops in **/ public static List<String> townyShopPlotsKing; /** * The events of AreaShop when shops in that region should be removed **/ public static List<String> areashopRemoveShopEvents; /** * The hostname used in ShopChest's MySQL database **/ public static String databaseMySqlHost; /** * The port used for ShopChest's MySQL database **/ public static int databaseMySqlPort; /** * The database used for ShopChest's MySQL database **/ public static String databaseMySqlDatabase; /** * The username used in ShopChest's MySQL database **/ public static String databaseMySqlUsername; /** * The password used in ShopChest's MySQL database **/ public static String databaseMySqlPassword; /** * The prefix to be used for database tables */ public static String databaseTablePrefix; /** * The database type used for ShopChest **/
public static Database.DatabaseType databaseType;
2
packetpirate/Generic-Zombie-Shooter
GenericZombieShooter/src/genericzombieshooter/structures/weapons/Landmine.java
[ "public class Player extends Rectangle2D.Double {\r\n // Final variables.\r\n public static final int DEFAULT_HEALTH = 150;\r\n public static final long INVINCIBILITY_LENGTH = 3000;\r\n private static final double MOVE_SPEED = 2; // How many pixels per tick the player moves.\r\n public static final double AUDIO_RANGE = 500;\r\n \r\n public static final int MAX_HEALTH_ID = 1;\r\n private static final int MAX_HEALTH_INC = 50;\r\n public static final int DAMAGE_ID = 2;\r\n private static final double DAMAGE_INC = 0.2;\r\n public static final int SPEED_ID = 3;\r\n private static final double SPEED_INC = 0.2;\r\n \r\n // Member variables.\r\n private AffineTransform af;\r\n private double theta;\r\n private BufferedImage img;\r\n private LightSource light;\r\n \r\n private int health;\r\n private int maxHealth;\r\n private double damageBonus;\r\n private double speed;\r\n private double speedBonus;\r\n private int cash;\r\n \r\n private int experience;\r\n private int experienceMultiplier;\r\n private int level;\r\n private int skillPoints;\r\n \r\n private int lives;\r\n \r\n private boolean blink;\r\n private long nextBlinkChange;\r\n \r\n private HashMap<String, StatusEffect> statusEffects;\r\n private long lastPoisoned;\r\n \r\n private String currentWeaponName;\r\n private HashMap<String, Weapon> weaponsMap;\r\n \r\n // Statistic Variables\r\n private long deathTime;\r\n public int killCount;\r\n public int medkitsUsed;\r\n public int ammoCratesUsed;\r\n\r\n public Player(double x_, double y_, double w_, double h_) {\r\n super(x_, y_, w_, h_);\r\n this.af = new AffineTransform();\r\n this.theta = 0;\r\n this.img = Images.PLAYER;\r\n \r\n {\r\n int xLoc = (int)this.getCenterX();\r\n int yLoc = (int)this.getCenterY();\r\n float intensity = 64.0f;\r\n float [] distance = {0.0f, 0.6f, 0.8f, 1.0f};\r\n Color [] colors = {new Color(0.0f, 0.0f, 0.0f, 0.0f),\r\n new Color(0.0f, 0.0f, 0.0f, 0.75f),\r\n new Color(0.0f, 0.0f, 0.0f, 0.9f),\r\n Color.BLACK};\r\n this.light = new LightSource(new Point2D.Double(xLoc, yLoc), 0, intensity, distance, colors);\r\n }\r\n\r\n this.health = Player.DEFAULT_HEALTH;\r\n this.maxHealth = Player.DEFAULT_HEALTH;\r\n this.damageBonus = 0;\r\n this.speed = Player.MOVE_SPEED;\r\n this.speedBonus = 0;\r\n this.cash = 0;\r\n \r\n this.experience = 0;\r\n this.experienceMultiplier = 1;\r\n this.level = 1;\r\n this.skillPoints = 0;\r\n \r\n this.lives = 3;\r\n \r\n this.blink = false;\r\n this.nextBlinkChange = Globals.gameTime.getElapsedMillis();\r\n \r\n this.statusEffects = new HashMap<String, StatusEffect>();\r\n \r\n this.lastPoisoned = Globals.gameTime.getElapsedMillis();\r\n \r\n this.deathTime = Globals.gameTime.getElapsedMillis();\r\n this.killCount = 0;\r\n this.medkitsUsed = 0;\r\n this.ammoCratesUsed = 0;\r\n \r\n this.weaponsMap = new HashMap<String, Weapon>();\r\n this.addWeapon(Globals.HANDGUN);\r\n this.currentWeaponName = Globals.HANDGUN.getName();\r\n }\r\n\r\n // Getter/Setter methods.\r\n public AffineTransform getTransform() { return this.af; }\r\n public double getTheta() { return this.theta; }\r\n public BufferedImage getImage() { return this.img; }\r\n public LightSource getLightSource() { return this.light; }\r\n\r\n public int getHealth() { return this.health; }\r\n public int getMaxHealth() { return this.maxHealth; }\r\n public double getDamageBonus() { return this.damageBonus; }\r\n public double getSpeed() { return (this.speed + this.speedBonus); }\r\n public int getCash() { return this.cash; }\r\n public void addCash(int amount) { this.cash += amount; }\r\n public void removeCash(int amount) { this.cash -= amount; }\r\n public int getExp() { return this.experience; }\r\n public void addExp(int amount) { this.experience += (amount * this.experienceMultiplier); }\r\n public int getNextLevelExp() {\r\n return ((this.level * 1000) + (((int)(this.level / 4)) * 2000));\r\n }\r\n public int getLevel() { return this.level; }\r\n public int getSkillPoints() { return this.skillPoints; }\r\n public void addKill() { this.killCount++; }\r\n public void takeDamage(int damage_) { this.health -= damage_; }\r\n public void addHealth(int amount) { \r\n if((this.health + amount) > this.maxHealth) this.health = this.maxHealth;\r\n else this.health += amount;\r\n }\r\n public boolean isAlive() { return this.health > 0; }\r\n public long getDeathTime() { return this.deathTime; }\r\n public int getLives() { return this.lives; }\r\n public void addLife() { this.lives++; }\r\n public void die() { \r\n this.lives--;\r\n if(this.lives > 0) reset();\r\n }\r\n public int spendPoint(int id, int currentLevel) {\r\n if(id == Player.MAX_HEALTH_ID) {\r\n // Determine if player has enough points to buy the next upgrade.;\r\n if(this.skillPoints >= (currentLevel + 1)) {\r\n // Determine if the player has already maxed out this skill.\r\n if(currentLevel < 5) {\r\n // Deduct the appropriate number of skill points and raise the skill to the next level.\r\n this.skillPoints -= (currentLevel + 1);\r\n this.maxHealth += Player.MAX_HEALTH_INC;\r\n this.addHealth(Player.MAX_HEALTH_INC);\r\n synchronized(Globals.GAME_MESSAGES) { Globals.GAME_MESSAGES.add(new Message(\"Max Health increased!\", 5000)); }\r\n return 1;\r\n }\r\n }\r\n } else if(id == Player.DAMAGE_ID) {\r\n // Determine if player has enough points to buy the next upgrade.\r\n if(this.skillPoints >= (currentLevel + 1)) {\r\n // Determine if the player has already maxed out this skill.\r\n if(currentLevel < 5) {\r\n // Deduct the appropriate number of skill points and raise the skill to the next level.\r\n this.skillPoints -= (currentLevel + 1);\r\n this.damageBonus += Player.DAMAGE_INC;\r\n synchronized(Globals.GAME_MESSAGES) { Globals.GAME_MESSAGES.add(new Message(\"Damage increased!\", 5000)); }\r\n return 1;\r\n }\r\n }\r\n } else if(id == Player.SPEED_ID) {\r\n // Determine if player has enough points to buy the next upgrade.\r\n if(this.skillPoints >= (currentLevel + 1)) {\r\n // Determine if the player has already maxed out this skill.\r\n if(currentLevel < 5) {\r\n // Deduct the appropriate number of skill points and raise the skill to the next level.\r\n this.skillPoints -= (currentLevel + 1);\r\n this.speedBonus += Player.SPEED_INC;\r\n synchronized(Globals.GAME_MESSAGES) { Globals.GAME_MESSAGES.add(new Message(\"Speed increased!\", 5000)); }\r\n return 1;\r\n }\r\n }\r\n }\r\n return 0;\r\n }\r\n public void reset() {\r\n this.statusEffects.clear();\r\n \r\n if(this.lives == 0) {\r\n this.maxHealth = Player.DEFAULT_HEALTH;\r\n this.damageBonus = 0;\r\n this.speedBonus = 0;\r\n this.cash = 0;\r\n \r\n this.experience = 0;\r\n this.level = 1;\r\n this.skillPoints = 0;\r\n \r\n this.lives = 3;\r\n \r\n this.deathTime = Globals.gameTime.getElapsedMillis();\r\n this.weaponsMap = new HashMap<String, Weapon>();\r\n this.weaponsMap.put(Globals.HANDGUN.getName(), Globals.HANDGUN);\r\n }\r\n else {\r\n this.addStatusEffect(Invulnerability.ID, Invulnerability.EFFECT_NAME, Images.INVULNERABILITY, 3000, 0);\r\n this.blink = true;\r\n this.nextBlinkChange = Globals.gameTime.getElapsedMillis() + 300;\r\n }\r\n if(this.hasEffect(\"Poison\")) this.removeEffect(\"Poison\");\r\n this.lastPoisoned = Globals.gameTime.getElapsedMillis();\r\n \r\n this.health = this.maxHealth;\r\n this.speed = Player.MOVE_SPEED;\r\n this.experienceMultiplier = 1;\r\n this.currentWeaponName = Globals.HANDGUN.getName();\r\n this.x = (Globals.W_WIDTH / 2) - (this.width / 2);\r\n this.y = (Globals.W_HEIGHT / 2) - (this.height / 2);\r\n this.light.move(new Point2D.Double((int)this.getCenterX(), (int)this.getCenterY()));\r\n }\r\n public void resetStatistics() {\r\n this.killCount = 0;\r\n this.medkitsUsed = 0;\r\n this.ammoCratesUsed = 0;\r\n }\r\n \r\n public boolean hasWeapon(String name) { return this.weaponsMap.containsKey(name); }\r\n public Weapon getWeapon() { return this.weaponsMap.get(this.currentWeaponName); }\r\n public Weapon getWeapon(String name) { return this.weaponsMap.get(name); }\r\n public String getCurrentWeaponName() { return this.currentWeaponName; }\r\n public HashMap<String, Weapon> getWeaponsMap() { return this.weaponsMap; }\r\n public int setWeapon(String name) {\r\n if(this.weaponsMap.containsKey(name)) {\r\n this.currentWeaponName = name;\r\n Sounds.FLAMETHROWER.getAudio().stop();\r\n return 1;\r\n } else return 0;\r\n }\r\n public void addWeapon(Weapon w) {\r\n this.weaponsMap.put(w.getName(), w);\r\n }\r\n \r\n public void update() {\r\n // Calculate the player's angle based on the mouse position.\r\n double cX = this.getCenterX();\r\n double cY = this.getCenterY();\r\n this.theta = Math.atan2((cY - Globals.mousePos.y), (cX - Globals.mousePos.x)) - Math.PI / 2;\r\n this.rotate(this.theta);\r\n \r\n // Move the player according to which keys are being held down.\r\n for(int i = 0; i < Globals.keys.length; i++) {\r\n if(Globals.keys[i]) this.move(i);\r\n }\r\n \r\n // If the left mouse button is held down, create a new projectile.\r\n if(Globals.buttons[0]) {\r\n Point target = new Point(Globals.mousePos);\r\n Point2D.Double pos = new Point2D.Double((this.x + 28), (this.y + 2));\r\n AffineTransform.getRotateInstance(this.theta, this.getCenterX(), this.getCenterY()).transform(pos, pos);\r\n double theta = Math.atan2((target.x - pos.x), (target.y - pos.y));\r\n this.getWeapon().fire(theta, pos, this);\r\n }\r\n \r\n { // Resolve status effects.\r\n // Power-Up Effects\r\n if(this.hasEffect(SpeedUp.EFFECT_NAME)) {\r\n StatusEffect status = this.statusEffects.get(SpeedUp.EFFECT_NAME);\r\n if(status.isActive()) {\r\n // Change the player's move speed.\r\n this.speed = Player.MOVE_SPEED * status.getValue();\r\n } else {\r\n // Reset the player's movement speed and remove the status.\r\n this.speed = Player.MOVE_SPEED;\r\n this.removeEffect(SpeedUp.EFFECT_NAME);\r\n }\r\n }\r\n if(this.hasEffect(UnlimitedAmmo.EFFECT_NAME)) {\r\n // If the player has the unlimited ammo effect, but it is no longer active, remove it.\r\n StatusEffect status = this.statusEffects.get(UnlimitedAmmo.EFFECT_NAME);\r\n if(!status.isActive()) this.removeEffect(UnlimitedAmmo.EFFECT_NAME);\r\n }\r\n if(this.hasEffect(ExpMultiplier.EFFECT_NAME)) {\r\n // If the player no longer has the experience multiplier effect, remove it and reset the multiplier.\r\n StatusEffect status = this.statusEffects.get(ExpMultiplier.EFFECT_NAME);\r\n if(status.isActive()) {\r\n // Change the player's experience multiplier.\r\n this.experienceMultiplier = 2;\r\n } else {\r\n this.experienceMultiplier = 1;\r\n this.removeEffect(ExpMultiplier.EFFECT_NAME);\r\n }\r\n }\r\n if(this.hasEffect(NightVision.EFFECT_NAME)) {\r\n // If the player no longer has the effect, remove it.\r\n StatusEffect status = this.statusEffects.get(NightVision.EFFECT_NAME);\r\n if(!status.isActive()) this.removeEffect(NightVision.EFFECT_NAME);\r\n }\r\n \r\n // Negative Effects\r\n if(this.hasEffect(\"Poison\")) {\r\n StatusEffect status = this.statusEffects.get(\"Poison\");\r\n if(status.isActive()) {\r\n if(!this.hasEffect(Invulnerability.EFFECT_NAME)) {\r\n // If the player is poisoned, take damage.\r\n if(Globals.gameTime.getElapsedMillis() >= (this.lastPoisoned + 1000)) {\r\n this.lastPoisoned = Globals.gameTime.getElapsedMillis();\r\n this.takeDamage((int)status.getValue());\r\n }\r\n }\r\n } else this.removeEffect(\"Poison\");\r\n }\r\n \r\n // Other Effects\r\n if(this.hasEffect(Invulnerability.EFFECT_NAME)) {\r\n StatusEffect status = this.statusEffects.get(Invulnerability.EFFECT_NAME);\r\n if(status.isActive()) {\r\n if(Globals.gameTime.getElapsedMillis() >= this.nextBlinkChange) {\r\n this.blink = ((this.blink)?false:true);\r\n this.nextBlinkChange = Globals.gameTime.getElapsedMillis() + 300;\r\n }\r\n } else {\r\n this.removeEffect(Invulnerability.EFFECT_NAME);\r\n this.blink = false;\r\n }\r\n }\r\n \r\n // Check player to see if he has leveled up.\r\n this.checkLevel();\r\n } // End resolving status effects.\r\n }\r\n \r\n public void draw(Graphics2D g2d) {\r\n if(!this.blink) {\r\n g2d.setTransform(this.af);\r\n { // Draw player shadow.\r\n int w = this.img.getWidth();\r\n int h = this.img.getHeight();\r\n int xPos = (int)(this.getCenterX() - (w / 2));\r\n int yPos = (int)(this.getCenterY() - (h / 2) + 5);\r\n g2d.setColor(new Color(0, 0, 0, 100));\r\n g2d.fillOval((xPos + 5), (yPos + 6), (w - 10), (h - 12));\r\n } // End drawing player shadow.\r\n g2d.drawImage(this.img, (int) this.x, (int) this.y, null);\r\n }\r\n }\r\n\r\n // Shape manipulation.\r\n public void rotate(double theta_) { this.af.setToRotation(theta_, getCenterX(), getCenterY()); }\r\n\r\n // Player manipulation.\r\n public void checkLevel() {\r\n while(this.experience >= this.getNextLevelExp()) {\r\n this.experience -= this.getNextLevelExp();\r\n this.level++;\r\n this.skillPoints++;\r\n synchronized(Globals.GAME_MESSAGES) { \r\n Globals.GAME_MESSAGES.add(new Message((\"Played reached level \" + this.level + \"!\"), 5000)); \r\n }\r\n }\r\n }\r\n \r\n public void move(int direction) {\r\n if(direction == 0) y -= (this.speed + this.speedBonus);\r\n else if(direction == 1) x -= (this.speed + this.speedBonus);\r\n else if(direction == 2) y += (this.speed + this.speedBonus);\r\n else if(direction == 3) x += (this.speed + this.speedBonus);\r\n this.light.move(new Point2D.Double((int)this.getCenterX(), (int)this.getCenterY()));\r\n }\r\n \r\n public void move(Point2D.Double p) {\r\n this.x = p.x;\r\n this.y = p.y;\r\n this.light.move(p);\r\n }\r\n \r\n public HashMap<String, StatusEffect> getStatusEffects() { return this.statusEffects; }\r\n \r\n public void addStatusEffect(int id, String name, BufferedImage img, long duration, int value) {\r\n if(!this.statusEffects.containsKey(name)) this.statusEffects.put(name, new StatusEffect(img, duration, value));\r\n else this.statusEffects.get(name).refresh(duration);\r\n }\r\n \r\n public void removeEffect(String name) {\r\n if(this.hasEffect(name)) this.statusEffects.remove(name);\r\n }\r\n \r\n public boolean hasEffect(String name) {\r\n return this.statusEffects.containsKey(name);\r\n }\r\n}\r", "public class Zombie extends Point2D.Double {\r\n // Member variables.\r\n private AffineTransform af;\r\n private Animation img;\r\n \r\n private int type;\r\n protected double health; // How much health the zombie has.\r\n private int damage; // How much damage the zombie does per tick to the player.\r\n private double speed; // How fast the zombie moves.\r\n private int cashValue; // How many points the zombie is worth.\r\n private int experience; // How many experience points the zombie is worth.\r\n \r\n protected long nextMoan;\r\n protected boolean moaned;\r\n \r\n public Zombie(Point2D.Double p_, int type_, int health_, int damage_, double speed_, int cash_, int exp_, Animation animation_) {\r\n super(p_.x, p_.y);\r\n this.af = new AffineTransform();\r\n this.img = animation_;\r\n \r\n this.type = type_;\r\n this.health = health_;\r\n this.damage = damage_;\r\n this.speed = speed_;\r\n this.cashValue = cash_;\r\n this.experience = exp_;\r\n \r\n this.nextMoan = Globals.gameTime.getElapsedMillis() + ((Globals.r.nextInt(7) + 6) * 1000);\r\n this.moaned = false;\r\n }\r\n \r\n // Getter/Setter methods.\r\n public void set(int id, long value) {\r\n // To be overridden.\r\n }\r\n public int getType() { return this.type; }\r\n public double getHealth() { return this.health; }\r\n public void takeDamage(int damage_) { this.health -= damage_; }\r\n public int getDamage() { return this.damage; }\r\n public int getCashValue() { return this.cashValue; }\r\n public int getExpValue() { return this.experience; }\r\n public AffineTransform getTransform() { return this.af; }\r\n public Animation getImage() { return this.img; }\r\n public Rectangle2D.Double getRect() {\r\n double width = this.getImage().getWidth();\r\n double height = this.getImage().getHeight();\r\n return new Rectangle2D.Double((this.x - (width / 2)), (this.y - (height / 2)), width, height); \r\n }\r\n \r\n public boolean isDead() { return this.health <= 0; }\r\n \r\n // Shape manipulation.\r\n public void rotate(double theta_) { this.af.setToRotation(theta_, this.x, this.y); }\r\n \r\n public void move(double theta_) {\r\n this.x += this.speed * Math.cos(theta_ - (Math.PI / 2));\r\n this.y += this.speed * Math.sin(theta_ - (Math.PI / 2));\r\n this.img.move((int)this.x, (int)this.y);\r\n }\r\n \r\n public void update(Player player, List<Zombie> zombies) {\r\n // To be overridden.\r\n }\r\n \r\n public void draw(Graphics2D g2d) {\r\n // Can be overridden.\r\n g2d.setTransform(this.af);\r\n { // Draw zombie's shadow.\r\n int width = this.img.getWidth();\r\n int height = this.img.getHeight();\r\n if(this.type == Globals.ZOMBIE_REGULAR_TYPE) height /= 2;\r\n else if(this.type == Globals.ZOMBIE_DOG_TYPE) width /= 2;\r\n else {\r\n width /= 2;\r\n height /= 2;\r\n }\r\n int xPos = (int)(this.x - (width / 2));\r\n int yPos = (int)(this.y - (height / 2));\r\n g2d.setColor(new Color(0, 0, 0, 100));\r\n g2d.fillOval(xPos, yPos, width, height);\r\n } // End drawing zombie's shadow.\r\n this.img.draw((Graphics2D)g2d);\r\n }\r\n \r\n public void moan(Player player) {\r\n // To be overridden.\r\n if(!this.moaned) {\r\n boolean regular = this.type == Globals.ZOMBIE_REGULAR_TYPE;\r\n boolean dog = this.type == Globals.ZOMBIE_DOG_TYPE;\r\n boolean tiny = this.type == Globals.ZOMBIE_TINY_TYPE;\r\n if(regular || dog || tiny) {\r\n if(Globals.gameTime.getElapsedMillis() >= this.nextMoan) {\r\n double xD = player.getCenterX() - this.x;\r\n double yD = player.getCenterY() - this.y;\r\n double dist = Math.sqrt((xD * xD) + (yD * yD));\r\n double gain = 1.0 - (dist / Player.AUDIO_RANGE);\r\n if(regular || tiny) Sounds.MOAN1.play(gain);\r\n else if(dog) Sounds.MOAN2.play(gain);\r\n this.moaned = true;\r\n }\r\n }\r\n }\r\n }\r\n \r\n public List<Particle> getParticles() {\r\n // To be overridden.\r\n return null;\r\n }\r\n \r\n public int getParticleDamage() { \r\n // To be overridden.\r\n return 0;\r\n }\r\n}\r", "public class Globals {\n // Game Information\n public static final String VERSION = \"1.0\";\n public static final int W_WIDTH = 800; // The width of the game window.\n public static final int W_HEIGHT = 640; // The height of the game window.\n public static final long SLEEP_TIME = 20; // The sleep time of the animation thread.\n public static final long WAVE_BREAK_TIME = 30 * 1000;\n public static final Random r = new Random();\n public static List<Message> GAME_MESSAGES = new ArrayList<Message>();\n \n // Zombie Information\n public static final int ZOMBIE_REGULAR_TYPE = 1;\n public static final long ZOMBIE_REGULAR_SPAWN = 1000;\n public static final int ZOMBIE_DOG_TYPE = 2;\n public static final long ZOMBIE_DOG_SPAWN = 10000;\n public static final int ZOMBIE_ACID_TYPE = 3;\n public static final long ZOMBIE_ACID_SPAWN = 30000;\n public static final int ZOMBIE_POISONFOG_TYPE = 4;\n public static final long ZOMBIE_POISONFOG_SPAWN = 20000;\n public static final int ZOMBIE_MATRON_TYPE = 5;\n public static final long ZOMBIE_MATRON_SPAWN = 50000;\n public static final int ZOMBIE_TINY_TYPE = 6;\n \n // Boss Information\n public static final int ZOMBIE_BOSS_ABERRATION_TYPE = 7;\n public static final int ZOMBIE_BOSS_ZOMBAT_TYPE = 8;\n public static final int ZOMBIE_BOSS_STITCHES_TYPE = 9;\n \n // Game-State Related\n public static Runnable animation; // The primary animation thread.\n public static GameTime gameTime; // Used to keep track of the time.\n \n public static boolean running; // Whether or not the game is currently running.\n public static boolean started;\n public static boolean crashed; // Tells the game whether or not there was a crash.\n public static boolean paused;\n public static boolean storeOpen;\n public static boolean levelScreenOpen;\n public static boolean deathScreen;\n public static boolean waveInProgress; // Whether the player is fighting or waiting for another wave.\n public static long nextWave;\n \n // Input Related\n public static boolean [] keys; // The state of the game key controls.\n public static boolean [] buttons; // The state of the game mouse button controls.\n public static Point mousePos; // The current position of the mouse on the screen.\n \n // Static Weapons\n public static Handgun HANDGUN = new Handgun();\n public static AssaultRifle ASSAULT_RIFLE = new AssaultRifle();\n public static Shotgun SHOTGUN = new Shotgun();\n public static Flamethrower FLAMETHROWER = new Flamethrower();\n public static Grenade GRENADE = new Grenade();\n public static Landmine LANDMINE = new Landmine();\n public static Flare FLARE = new Flare();\n public static LaserWire LASERWIRE = new LaserWire();\n public static TurretWeapon TURRETWEAPON = new TurretWeapon();\n public static Teleporter TELEPORTER = new Teleporter();\n \n public static Weapon getWeaponByName(String name) {\n if(name.equals(Globals.HANDGUN.getName())) return Globals.HANDGUN;\n else if(name.equals(Globals.ASSAULT_RIFLE.getName())) return Globals.ASSAULT_RIFLE;\n else if(name.equals(Globals.SHOTGUN.getName())) return Globals.SHOTGUN;\n else if(name.equals(Globals.FLAMETHROWER.getName())) return Globals.FLAMETHROWER;\n else if(name.equals(Globals.GRENADE.getName())) return Globals.GRENADE;\n else if(name.equals(Globals.LANDMINE.getName())) return Globals.LANDMINE;\n else if(name.equals(Globals.FLARE.getName())) return Globals.FLARE;\n else if(name.equals(Globals.LASERWIRE.getName())) return Globals.LASERWIRE;\n else if(name.equals(Globals.TURRETWEAPON.getName())) return Globals.TURRETWEAPON;\n else if(name.equals(Globals.TELEPORTER.getName())) return Globals.TELEPORTER;\n else return null;\n }\n \n public static void resetWeapons() {\n Globals.HANDGUN.resetAmmo();\n Globals.ASSAULT_RIFLE.resetAmmo();\n Globals.SHOTGUN.resetAmmo();\n Globals.FLAMETHROWER.resetAmmo();\n Globals.GRENADE.resetAmmo();\n Globals.LANDMINE.resetAmmo();\n Globals.FLARE.resetAmmo();\n Globals.LASERWIRE.resetAmmo();\n Globals.TURRETWEAPON.resetAmmo();\n Globals.TELEPORTER.resetAmmo();\n }\n}", "public class Images {\r\n // Background Images\r\n public static final BufferedImage START_SCREEN = GZSFramework.loadImage(\"/resources/images/GZS_Splash.png\");\r\n public static final BufferedImage BACKGROUND = GZSFramework.loadImage(\"/resources/images/GZS_Background6.png\");\r\n public static final BufferedImage DEATH_SCREEN = GZSFramework.loadImage(\"/resources/images/GZS_DeathScreen.png\");\r\n \r\n // Player-Related\r\n public static final BufferedImage PLAYER = GZSFramework.loadImage(\"/resources/images/GZS_Player.png\");\r\n public static final BufferedImage CROSSHAIR = GZSFramework.loadImage(\"/resources/images/GZS_Crosshair.png\");\r\n \r\n // Zombie-Related\r\n public static final BufferedImage ZOMBIE_REGULAR = GZSFramework.loadImage(\"/resources/images/GZS_Zumby2.png\");\r\n public static final BufferedImage ZOMBIE_DOG = GZSFramework.loadImage(\"/resources/images/GZS_Rotdog2.png\");\r\n public static final BufferedImage ZOMBIE_ACID = GZSFramework.loadImage(\"/resources/images/GZS_Upchuck2.png\");\r\n public static final BufferedImage ZOMBIE_POISONFOG = GZSFramework.loadImage(\"/resources/images/GZS_Gasbag2.png\");\r\n public static final BufferedImage ZOMBIE_MATRON = GZSFramework.loadImage(\"/resources/images/GZS_BigMama2.png\");\r\n public static final BufferedImage ZOMBIE_TINY = GZSFramework.loadImage(\"/resources/images/GZS_TinyZumby.png\");\r\n public static final BufferedImage BOSS_ABERRATION = GZSFramework.loadImage(\"/resources/images/GZS_Aberration2.png\");\r\n public static final BufferedImage BOSS_ZOMBAT = GZSFramework.loadImage(\"/resources/images/GZS_Zombat.png\");\r\n public static final BufferedImage BOSS_STITCHES = GZSFramework.loadImage(\"/resources/images/GZS_Stitches.png\");\r\n \r\n public static final BufferedImage ACID_PARTICLE = GZSFramework.loadImage(\"/resources/images/GZS_AcidParticle.png\");\r\n public static final BufferedImage STITCHES_HOOK = GZSFramework.loadImage(\"/resources/images/GZS_Hook.png\");\r\n public static final BufferedImage POISON_GAS_SHEET = GZSFramework.loadImage(\"/resources/images/GZS_PoisonExplosion.png\");\r\n public static final BufferedImage POISON_STATUS_ICON = GZSFramework.loadImage(\"/resources/images/GZS_PoisonIcon.png\");\r\n public static final BufferedImage BLOOD_SHEET = GZSFramework.loadImage(\"/resources/images/GZS_BloodExplosion.png\");\r\n \r\n // Power-Up Related\r\n public static final BufferedImage HEALTH_PACK = GZSFramework.loadImage(\"/resources/images/GZS_Health.png\");\r\n public static final BufferedImage AMMO_PACK = GZSFramework.loadImage(\"/resources/images/GZS_Ammo.png\");\r\n public static final BufferedImage SPEED_UP = GZSFramework.loadImage(\"/resources/images/GZS_SpeedUp.png\");\r\n public static final BufferedImage UNLIMITED_AMMO = GZSFramework.loadImage(\"/resources/images/GZS_UnlimitedAmmo.png\");\r\n public static final BufferedImage EXTRA_LIFE = GZSFramework.loadImage(\"/resources/images/GZS_ExtraLife.png\");\r\n public static final BufferedImage EXP_MULTIPLIER = GZSFramework.loadImage(\"/resources/images/GZS_ExpMultiplier.png\");\r\n public static final BufferedImage INVULNERABILITY = GZSFramework.loadImage(\"/resources/images/GZS_Invulnerability.png\");\r\n public static final BufferedImage NIGHT_VISION = GZSFramework.loadImage(\"/resources/images/GZS_NightVision.png\");\r\n \r\n // Ammo-Related\r\n public static final BufferedImage POPGUN_BULLET = GZSFramework.loadImage(\"/resources/images/GZS_Bullet.png\");\r\n public static final BufferedImage RTPS_BULLET = GZSFramework.loadImage(\"/resources/images/GZS_Bullet2.png\");\r\n public static final BufferedImage FIRE_PARTICLE = GZSFramework.loadImage(\"/resources/images/GZS_FireParticle2.png\");\r\n public static final BufferedImage GRENADE_PARTICLE = GZSFramework.loadImage(\"/resources/images/GZS_HandEggParticle.png\");\r\n public static final BufferedImage LANDMINE_PARTICLE = GZSFramework.loadImage(\"/resources/images/GZS_FlipFlopParticle.png\");\r\n public static final BufferedImage FLARE_PARTICLE = GZSFramework.loadImage(\"/resources/images/GZS_FlareParticle.png\");\r\n public static final BufferedImage LASER_TERMINAL = GZSFramework.loadImage(\"/resources/images/GZS_LaserTerminal.png\");\r\n public static final BufferedImage EXPLOSION_SHEET = GZSFramework.loadImage(\"/resources/images/GZS_Explosion.png\");\r\n}\r", "public enum Sounds {\n // Weapon-Related\n POPGUN(\"shoot4.wav\", false, true),\n RTPS(\"shoot3.wav\", false, false),\n BOOMSTICK(\"shotgun2.wav\", false, false),\n FLAMETHROWER(\"flamethrower2.wav\", true, false),\n THROW(\"throw2.wav\", false, false),\n EXPLOSION(\"explosion2.wav\", false, false),\n LANDMINE_ARMED(\"landmine_armed.wav\", false, false),\n TELEPORT(\"teleport2.wav\", false, false),\n \n // Zombie-Related\n MOAN1(\"zombie_moan_01.wav\", false, true),\n MOAN2(\"zombie_moan_02.wav\", false, true),\n MOAN3(\"zombie_moan_03.wav\", false, true),\n MOAN4(\"zombie_moan_04.wav\", false, true),\n MOAN5(\"zombie_moan_05.wav\", false, true),\n MOAN6(\"zombie_moan_06.wav\", false, true),\n MOAN7(\"zombie_moan_07.wav\", false, true),\n MOAN8(\"zombie_moan_08.wav\", false, true),\n POISONCLOUD(\"poison_cloud.wav\", false, false),\n \n // Game Sounds\n POWERUP(\"powerup2.wav\", false, false),\n PURCHASEWEAPON(\"purchase_weapon2.wav\", false, true),\n BUYAMMO(\"buy_ammo2.wav\", false, true),\n POINTBUY(\"point_buy.wav\", false, true),\n PAUSE(\"pause.wav\", false, false),\n UNPAUSE(\"unpause.wav\", false, false);\n \n private String file;\n private Music audio;\n public Music getAudio() { return this.audio; }\n private boolean looped; \n private boolean overlap;\n\n Sounds(String filename, boolean loop, boolean over) {\n openClip(filename, loop, over);\n }\n\n private synchronized void openClip(String filename, boolean loop, boolean over) {\n file = filename;\n audio = TinySound.loadMusic(\"/resources/sounds/\" + filename);\n looped = loop;\n overlap = over;\n }\n \n public synchronized void play() {\n play(1.0);\n }\n \n public synchronized void play(final double gain) {\n // If the clip supports overlapping, create a new Music object to use.\n if(overlap) {\n Music m = TinySound.loadMusic(\"/resources/sounds/\" + file);\n m.rewind();\n m.play(looped, gain);\n } else {\n audio.rewind();\n audio.play(looped, gain);\n }\n }\n\n public static void init() {\n values();\n }\n}", "public class Explosion extends Point2D.Double {\r\n private Animation img;\r\n public Animation getImage() { return this.img; }\r\n private Dimension size;\r\n public Dimension getSize() { return this.size; }\r\n \r\n public Explosion(BufferedImage bi, Point2D.Double p) {\r\n super(p.x, p.y);\r\n this.size = new Dimension(128, 128);\r\n this.img = new Animation(bi, this.size.width, this.size.height, 8, (int)p.x, (int)p.y, 50, 0, false) {\r\n @Override\r\n public void draw(Graphics2D g2d) {\r\n if((this.timeCreated + this.delay) <= System.currentTimeMillis()) {\r\n g2d.drawImage(this.img, (this.x - (this.frameWidth / 2)), (this.y - (this.frameHeight / 2)),\r\n (this.x + this.frameWidth), (this.y + this.frameHeight),\r\n this.startX, 0, this.endX, this.frameHeight, null);\r\n }\r\n }\r\n };\r\n }\r\n \r\n public void draw(Graphics2D g2d) {\r\n this.img.draw(g2d);\r\n }\r\n}\r", "public class Particle {\r\n protected double theta;\r\n public void setTheta(double theta) { this.theta = theta; }\r\n protected double speed;\r\n protected int life;\r\n public boolean isAlive() { return this.life > 0; }\r\n public void setLife(int newLife) { this.life = newLife; }\r\n protected Point2D.Double pos;\r\n public Point2D.Double getPos() { return this.pos; }\r\n public void setPos(Point2D.Double p) { this.pos = p; }\r\n protected Dimension size;\r\n public Dimension getSize() { return this.size; }\r\n \r\n protected BufferedImage image;\r\n \r\n public Particle(double _theta, double _spread, double _speed, int _life, Point2D.Double _pos, Dimension _size) {\r\n this(_theta, _spread, _speed, _life, _pos, _size, null);\r\n }\r\n \r\n /**\r\n * Constructs a new Particle object.\r\n * @param _theta The angle between the firing position and the mouse position when fired. Given in radians.\r\n * @param _spread The maximum spread for this particle. Given in degrees.\r\n * @param _speed The multiplier used when updating the particle position.\r\n * @param _life Determines how long before the particle disappears.\r\n * @param _pos The starting position of the particle.\r\n * @param _size The size of the particle.\r\n */\r\n public Particle(double _theta, double _spread, double _speed, int _life, Point2D.Double _pos, Dimension _size, BufferedImage _image) {\r\n this.theta = _theta;\r\n this.speed = _speed;\r\n this.life = _life;\r\n this.pos = _pos;\r\n this.size = _size;\r\n \r\n this.image = _image;\r\n\r\n // Determine if the angle of the particle will deviate from its set value.\r\n if(_spread > 0) {\r\n boolean mod = Globals.r.nextBoolean();\r\n double spreadMod = Math.toRadians(Globals.r.nextDouble() * _spread);\r\n if(mod) spreadMod = -spreadMod;\r\n this.theta += spreadMod;\r\n }\r\n }\r\n \r\n /**\r\n * Draws the particle to the screen.\r\n * @param g2d The graphics object used to draw the particle.\r\n **/\r\n public void draw(Graphics2D g2d) {\r\n try {\r\n AffineTransform saved = g2d.getTransform();\r\n /* Had to create the inverse of this transformation because I noticed that everything was rotating\r\n in the opposite direction of the theta. Then I noticed the image was backwards, so I flipped it 180 degrees. */\r\n AffineTransform at = AffineTransform.getRotateInstance((this.theta - Math.PI), this.pos.x, this.pos.y).createInverse();\r\n double x = this.pos.x - (this.size.width / 2);\r\n double y = this.pos.y - (this.size.height / 2);\r\n g2d.setTransform(at);\r\n if(this.image == null) {\r\n double w = this.size.width;\r\n double h = this.size.height;\r\n Rectangle2D.Double rect = new Rectangle2D.Double(x, y, w, h);\r\n g2d.fill(at.createTransformedShape(rect));\r\n } else {\r\n g2d.drawImage(this.image, (int)x, (int)y, null);\r\n }\r\n g2d.setTransform(saved);\r\n } catch(NoninvertibleTransformException nte) {}\r\n }\r\n \r\n /**\r\n * Updates the state of the particle.\r\n **/\r\n public void update() {\r\n if(this.isAlive()) {\r\n // Age the particle.\r\n this.life--;\r\n // Update the position.\r\n this.pos.x += this.speed * Math.cos(-this.theta + (Math.PI / 2));\r\n this.pos.y += this.speed * Math.sin(-this.theta + (Math.PI / 2));\r\n }\r\n }\r\n \r\n public boolean checkCollision(Rectangle2D.Double rect) {\r\n if(rect.contains(pos)) {\r\n this.life = 0;\r\n return true;\r\n } else return false;\r\n }\r\n \r\n public boolean outOfBounds() {\r\n boolean top = this.pos.y < 0;\r\n boolean right = this.pos.x > Globals.W_WIDTH;\r\n boolean bottom = this.pos.y > Globals.W_HEIGHT;\r\n boolean left = this.pos.x < 0;\r\n return top || right || bottom || left;\r\n }\r\n}" ]
import java.util.Iterator; import java.util.List; import genericzombieshooter.actors.Player; import genericzombieshooter.actors.Zombie; import genericzombieshooter.misc.Globals; import genericzombieshooter.misc.Images; import genericzombieshooter.misc.Sounds; import genericzombieshooter.structures.Explosion; import genericzombieshooter.structures.Particle; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.event.KeyEvent; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.Collections;
/** This file is part of Generic Zombie Shooter. Generic Zombie Shooter 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. Generic Zombie Shooter 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 Generic Zombie Shooter. If not, see <http://www.gnu.org/licenses/>. **/ package genericzombieshooter.structures.weapons; /** * Used to represent a landmine weapon. * @author Darin Beaudreau */ public class Landmine extends Weapon { // Final Variables private static final int WEAPON_PRICE = 750; private static final int AMMO_PRICE = 400; private static final int DEFAULT_AMMO = 1; private static final int MAX_AMMO = 3; private static final int AMMO_PER_USE = 1;
private static final int DAMAGE_PER_EXPLOSION = (500 / (int)Globals.SLEEP_TIME);
2
qqq3/good-weather
app/src/main/java/org/asdtm/goodweather/widget/LessWidgetProvider.java
[ "public class MainActivity extends BaseActivity implements AppBarLayout.OnOffsetChangedListener {\n\n private static final String TAG = \"MainActivity\";\n\n private static final long LOCATION_TIMEOUT_IN_MS = 30000L;\n\n private TextView mIconWeatherView;\n private TextView mTemperatureView;\n private TextView mDescriptionView;\n private TextView mHumidityView;\n private TextView mWindSpeedView;\n private TextView mPressureView;\n private TextView mCloudinessView;\n private TextView mLastUpdateView;\n private TextView mSunriseView;\n private TextView mSunsetView;\n private AppBarLayout mAppBarLayout;\n private TextView mIconWindView;\n private TextView mIconHumidityView;\n private TextView mIconPressureView;\n private TextView mIconCloudinessView;\n private TextView mIconSunriseView;\n private TextView mIconSunsetView;\n\n private ConnectionDetector connectionDetector;\n private Boolean isNetworkAvailable;\n private ProgressDialog mProgressDialog;\n private LocationManager locationManager;\n private SwipeRefreshLayout mSwipeRefresh;\n private Menu mToolbarMenu;\n private BroadcastReceiver mWeatherUpdateReceiver;\n\n private String mSpeedScale;\n private String mIconWind;\n private String mIconHumidity;\n private String mIconPressure;\n private String mIconCloudiness;\n private String mIconSunrise;\n private String mIconSunset;\n private String mPercentSign;\n private String mPressureMeasurement;\n\n private SharedPreferences mPrefWeather;\n private SharedPreferences mSharedPreferences;\n\n public static Weather mWeather;\n public static CitySearch mCitySearch;\n\n private static final int REQUEST_LOCATION = 0;\n private static String[] PERMISSIONS_LOCATION = {Manifest.permission.ACCESS_COARSE_LOCATION,\n Manifest.permission.ACCESS_FINE_LOCATION};\n\n public Context storedContext;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n ((GoodWeatherApp) getApplication()).applyTheme(this);\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n mWeather = new Weather();\n mCitySearch = new CitySearch();\n\n weatherConditionsIcons();\n initializeTextView();\n initializeWeatherReceiver();\n\n connectionDetector = new ConnectionDetector(MainActivity.this);\n locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);\n\n mPrefWeather = getSharedPreferences(Constants.PREF_WEATHER_NAME, Context.MODE_PRIVATE);\n mSharedPreferences = getSharedPreferences(Constants.APP_SETTINGS_NAME,\n Context.MODE_PRIVATE);\n setTitle(Utils.getCityAndCountry(this));\n\n /**\n * Configure SwipeRefreshLayout\n */\n mSwipeRefresh = (SwipeRefreshLayout) findViewById(R.id.main_swipe_refresh);\n int top_to_padding = 150;\n mSwipeRefresh.setProgressViewOffset(false, 0, top_to_padding);\n mSwipeRefresh.setColorSchemeResources(R.color.swipe_red, R.color.swipe_green,\n R.color.swipe_blue);\n mSwipeRefresh.setOnRefreshListener(swipeRefreshListener);\n\n /**\n * Share weather fab\n */\n FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);\n this.storedContext = this;\n fab.setOnClickListener(fabListener);\n }\n\n private void updateCurrentWeather() {\n AppPreference.saveWeather(MainActivity.this, mWeather);\n mSharedPreferences = getSharedPreferences(Constants.APP_SETTINGS_NAME,\n Context.MODE_PRIVATE);\n SharedPreferences.Editor configEditor = mSharedPreferences.edit();\n\n mSpeedScale = Utils.getSpeedScale(MainActivity.this);\n String temperature = String.format(Locale.getDefault(), \"%.0f\",\n mWeather.temperature.getTemp());\n String pressure = String.format(Locale.getDefault(), \"%.1f\",\n mWeather.currentCondition.getPressure());\n String wind = String.format(Locale.getDefault(), \"%.1f\", mWeather.wind.getSpeed());\n\n String lastUpdate = Utils.setLastUpdateTime(MainActivity.this,\n saveLastUpdateTimeMillis(MainActivity.this));\n String sunrise = Utils.unixTimeToFormatTime(MainActivity.this, mWeather.sys.getSunrise());\n String sunset = Utils.unixTimeToFormatTime(MainActivity.this, mWeather.sys.getSunset());\n\n mIconWeatherView.setText(\n Utils.getStrIcon(MainActivity.this, mWeather.currentWeather.getIdIcon()));\n mTemperatureView.setText(getString(R.string.temperature_with_degree, temperature));\n if (!AppPreference.hideDescription(MainActivity.this))\n mDescriptionView.setText(mWeather.currentWeather.getDescription());\n else\n mDescriptionView.setText(\" \");\n mHumidityView.setText(getString(R.string.humidity_label,\n String.valueOf(mWeather.currentCondition.getHumidity()),\n mPercentSign));\n mPressureView.setText(getString(R.string.pressure_label, pressure,\n mPressureMeasurement));\n mWindSpeedView.setText(getString(R.string.wind_label, wind, mSpeedScale));\n mCloudinessView.setText(getString(R.string.cloudiness_label,\n String.valueOf(mWeather.cloud.getClouds()),\n mPercentSign));\n mLastUpdateView.setText(getString(R.string.last_update_label, lastUpdate));\n mSunriseView.setText(getString(R.string.sunrise_label, sunrise));\n mSunsetView.setText(getString(R.string.sunset_label, sunset));\n\n configEditor.putString(Constants.APP_SETTINGS_CITY, mWeather.location.getCityName());\n configEditor.putString(Constants.APP_SETTINGS_COUNTRY_CODE,\n mWeather.location.getCountryCode());\n configEditor.apply();\n }\n\n @Override\n public void onResume() {\n super.onResume();\n preLoadWeather();\n mAppBarLayout.addOnOffsetChangedListener(this);\n LocalBroadcastManager.getInstance(this).registerReceiver(mWeatherUpdateReceiver,\n new IntentFilter(\n CurrentWeatherService.ACTION_WEATHER_UPDATE_RESULT));\n }\n\n @Override\n protected void onPause() {\n super.onPause();\n mAppBarLayout.removeOnOffsetChangedListener(this);\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n LocalBroadcastManager.getInstance(this).unregisterReceiver(mWeatherUpdateReceiver);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n this.mToolbarMenu = menu;\n MenuInflater menuInflater = getMenuInflater();\n menuInflater.inflate(R.menu.activity_main_menu, menu);\n\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case R.id.main_menu_refresh:\n if (connectionDetector.isNetworkAvailableAndConnected()) {\n startService(new Intent(this, CurrentWeatherService.class));\n setUpdateButtonState(true);\n } else {\n Toast.makeText(MainActivity.this,\n R.string.connection_not_found,\n Toast.LENGTH_SHORT).show();\n setUpdateButtonState(false);\n }\n return true;\n case R.id.main_menu_detect_location:\n requestLocation();\n return true;\n case R.id.main_menu_search_city:\n Intent intent = new Intent(MainActivity.this, SearchActivity.class);\n startActivityForResult(intent, PICK_CITY);\n return true;\n }\n\n return super.onOptionsItemSelected(item);\n }\n\n private LocationListener mLocationListener = new LocationListener() {\n @Override\n public void onLocationChanged(Location location) {\n mProgressDialog.cancel();\n String latitude = String.format(\"%1$.2f\", location.getLatitude());\n String longitude = String.format(\"%1$.2f\", location.getLongitude());\n\n if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {\n locationManager.removeUpdates(mLocationListener);\n }\n\n connectionDetector = new ConnectionDetector(MainActivity.this);\n isNetworkAvailable = connectionDetector.isNetworkAvailableAndConnected();\n\n mSharedPreferences = getSharedPreferences(Constants.APP_SETTINGS_NAME,\n Context.MODE_PRIVATE);\n SharedPreferences.Editor editor = mSharedPreferences.edit();\n editor.putString(Constants.APP_SETTINGS_LATITUDE, latitude);\n editor.putString(Constants.APP_SETTINGS_LONGITUDE, longitude);\n getAndWriteAddressFromGeocoder(latitude, longitude, editor);\n editor.apply();\n\n if (isNetworkAvailable) {\n startService(new Intent(MainActivity.this, CurrentWeatherService.class));\n sendBroadcast(new Intent(Constants.ACTION_FORCED_APPWIDGET_UPDATE));\n } else {\n Toast.makeText(MainActivity.this, R.string.connection_not_found, Toast.LENGTH_SHORT)\n .show();\n }\n }\n\n @Override\n public void onStatusChanged(String provider, int status, Bundle extras) {\n\n }\n\n @Override\n public void onProviderEnabled(String provider) {\n\n }\n\n @Override\n public void onProviderDisabled(String provider) {\n\n }\n };\n\n private void getAndWriteAddressFromGeocoder(String latitude, String longitude, SharedPreferences.Editor editor) {\n Geocoder geocoder = new Geocoder(this, Locale.getDefault());\n try {\n String latitudeEn = latitude.replace(\",\", \".\");\n String longitudeEn = longitude.replace(\",\", \".\");\n List<Address> addresses = geocoder.getFromLocation(Double.parseDouble(latitudeEn), Double.parseDouble(longitudeEn), 1);\n if ((addresses != null) && (addresses.size() > 0)) {\n editor.putString(Constants.APP_SETTINGS_GEO_CITY, addresses.get(0).getLocality());\n editor.putString(Constants.APP_SETTINGS_GEO_COUNTRY_NAME, addresses.get(0).getCountryName());\n }\n } catch (IOException | NumberFormatException ex) {\n Log.e(TAG, \"Unable to get address from latitude and longitude\", ex);\n }\n }\n\n private SwipeRefreshLayout.OnRefreshListener swipeRefreshListener =\n new SwipeRefreshLayout.OnRefreshListener() {\n @Override\n public void onRefresh() {\n isNetworkAvailable = connectionDetector.isNetworkAvailableAndConnected();\n if (isNetworkAvailable) {\n startService(new Intent(MainActivity.this, CurrentWeatherService.class));\n } else {\n Toast.makeText(MainActivity.this,\n R.string.connection_not_found,\n Toast.LENGTH_SHORT).show();\n mSwipeRefresh.setRefreshing(false);\n }\n }\n };\n\n private void preLoadWeather() {\n mSpeedScale = Utils.getSpeedScale(this);\n String lastUpdate = Utils.setLastUpdateTime(this,\n AppPreference.getLastUpdateTimeMillis(this));\n\n String iconId = mPrefWeather.getString(Constants.WEATHER_DATA_ICON, \"01d\");\n float temperaturePref = mPrefWeather.getFloat(Constants.WEATHER_DATA_TEMPERATURE, 0);\n String description = mPrefWeather.getString(Constants.WEATHER_DATA_DESCRIPTION,\n \"clear sky\");\n int humidity = mPrefWeather.getInt(Constants.WEATHER_DATA_HUMIDITY, 0);\n float pressurePref = mPrefWeather.getFloat(Constants.WEATHER_DATA_PRESSURE, 0);\n float windPref = mPrefWeather.getFloat(Constants.WEATHER_DATA_WIND_SPEED, 0);\n int clouds = mPrefWeather.getInt(Constants.WEATHER_DATA_CLOUDS, 0);\n long sunrisePref = mPrefWeather.getLong(Constants.WEATHER_DATA_SUNRISE, -1);\n long sunsetPref = mPrefWeather.getLong(Constants.WEATHER_DATA_SUNSET, -1);\n\n String temperature = String.format(Locale.getDefault(), \"%.0f\", temperaturePref);\n String pressure = String.format(Locale.getDefault(), \"%.1f\", pressurePref);\n String wind = String.format(Locale.getDefault(), \"%.1f\", windPref);\n String sunrise = Utils.unixTimeToFormatTime(this, sunrisePref);\n String sunset = Utils.unixTimeToFormatTime(this, sunsetPref);\n\n mIconWeatherView.setText(Utils.getStrIcon(this, iconId));\n mTemperatureView.setText(getString(R.string.temperature_with_degree, temperature));\n mDescriptionView.setText(description);\n mLastUpdateView.setText(getString(R.string.last_update_label, lastUpdate));\n mHumidityView.setText(getString(R.string.humidity_label,\n String.valueOf(humidity),\n mPercentSign));\n mPressureView.setText(getString(R.string.pressure_label,\n pressure,\n mPressureMeasurement));\n mWindSpeedView.setText(getString(R.string.wind_label, wind, mSpeedScale));\n mCloudinessView.setText(getString(R.string.cloudiness_label,\n String.valueOf(clouds),\n mPercentSign));\n mSunriseView.setText(getString(R.string.sunrise_label, sunrise));\n mSunsetView.setText(getString(R.string.sunset_label, sunset));\n setTitle(Utils.getCityAndCountry(this));\n }\n\n private void initializeTextView() {\n /**\n * Create typefaces from Asset\n */\n Typeface weatherFontIcon = Typeface.createFromAsset(this.getAssets(),\n \"fonts/weathericons-regular-webfont.ttf\");\n Typeface robotoThin = Typeface.createFromAsset(this.getAssets(),\n \"fonts/Roboto-Thin.ttf\");\n Typeface robotoLight = Typeface.createFromAsset(this.getAssets(),\n \"fonts/Roboto-Light.ttf\");\n\n mIconWeatherView = (TextView) findViewById(R.id.main_weather_icon);\n mTemperatureView = (TextView) findViewById(R.id.main_temperature);\n mDescriptionView = (TextView) findViewById(R.id.main_description);\n mPressureView = (TextView) findViewById(R.id.main_pressure);\n mHumidityView = (TextView) findViewById(R.id.main_humidity);\n mWindSpeedView = (TextView) findViewById(R.id.main_wind_speed);\n mCloudinessView = (TextView) findViewById(R.id.main_cloudiness);\n mLastUpdateView = (TextView) findViewById(R.id.main_last_update);\n mSunriseView = (TextView) findViewById(R.id.main_sunrise);\n mSunsetView = (TextView) findViewById(R.id.main_sunset);\n mAppBarLayout = (AppBarLayout) findViewById(R.id.main_app_bar);\n\n mIconWeatherView.setTypeface(weatherFontIcon);\n mTemperatureView.setTypeface(robotoThin);\n mWindSpeedView.setTypeface(robotoLight);\n mHumidityView.setTypeface(robotoLight);\n mPressureView.setTypeface(robotoLight);\n mCloudinessView.setTypeface(robotoLight);\n mSunriseView.setTypeface(robotoLight);\n mSunsetView.setTypeface(robotoLight);\n\n /**\n * Initialize and configure weather icons\n */\n mIconWindView = (TextView) findViewById(R.id.main_wind_icon);\n mIconWindView.setTypeface(weatherFontIcon);\n mIconWindView.setText(mIconWind);\n mIconHumidityView = (TextView) findViewById(R.id.main_humidity_icon);\n mIconHumidityView.setTypeface(weatherFontIcon);\n mIconHumidityView.setText(mIconHumidity);\n mIconPressureView = (TextView) findViewById(R.id.main_pressure_icon);\n mIconPressureView.setTypeface(weatherFontIcon);\n mIconPressureView.setText(mIconPressure);\n mIconCloudinessView = (TextView) findViewById(R.id.main_cloudiness_icon);\n mIconCloudinessView.setTypeface(weatherFontIcon);\n mIconCloudinessView.setText(mIconCloudiness);\n mIconSunriseView = (TextView) findViewById(R.id.main_sunrise_icon);\n mIconSunriseView.setTypeface(weatherFontIcon);\n mIconSunriseView.setText(mIconSunrise);\n mIconSunsetView = (TextView) findViewById(R.id.main_sunset_icon);\n mIconSunsetView.setTypeface(weatherFontIcon);\n mIconSunsetView.setText(mIconSunset);\n }\n\n private void weatherConditionsIcons() {\n mIconWind = getString(R.string.icon_wind);\n mIconHumidity = getString(R.string.icon_humidity);\n mIconPressure = getString(R.string.icon_barometer);\n mIconCloudiness = getString(R.string.icon_cloudiness);\n mPercentSign = getString(R.string.percent_sign);\n mPressureMeasurement = getString(R.string.pressure_measurement);\n mIconSunrise = getString(R.string.icon_sunrise);\n mIconSunset = getString(R.string.icon_sunset);\n }\n\n private void setUpdateButtonState(boolean isUpdate) {\n if (mToolbarMenu != null) {\n MenuItem updateItem = mToolbarMenu.findItem(R.id.main_menu_refresh);\n ProgressBar progressUpdate = (ProgressBar) findViewById(R.id.toolbar_progress_bar);\n if (isUpdate) {\n updateItem.setVisible(false);\n progressUpdate.setVisibility(View.VISIBLE);\n } else {\n progressUpdate.setVisibility(View.GONE);\n updateItem.setVisible(true);\n }\n }\n }\n\n private void initializeWeatherReceiver() {\n mWeatherUpdateReceiver = new BroadcastReceiver() {\n @Override\n public void onReceive(Context context, Intent intent) {\n switch (intent.getStringExtra(CurrentWeatherService.ACTION_WEATHER_UPDATE_RESULT)) {\n case CurrentWeatherService.ACTION_WEATHER_UPDATE_OK:\n mSwipeRefresh.setRefreshing(false);\n setUpdateButtonState(false);\n updateCurrentWeather();\n break;\n case CurrentWeatherService.ACTION_WEATHER_UPDATE_FAIL:\n mSwipeRefresh.setRefreshing(false);\n setUpdateButtonState(false);\n Toast.makeText(MainActivity.this,\n getString(R.string.toast_parse_error),\n Toast.LENGTH_SHORT).show();\n }\n }\n };\n }\n\n @Override\n public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {\n mSwipeRefresh.setEnabled(verticalOffset == 0);\n }\n\n FloatingActionButton.OnClickListener fabListener = new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n String temperatureScale = Utils.getTemperatureScale(MainActivity.this);\n mSpeedScale = Utils.getSpeedScale(MainActivity.this);\n String weather;\n String temperature;\n String description;\n String wind;\n String sunrise;\n String sunset;\n temperature = String.format(Locale.getDefault(), \"%.0f\", mPrefWeather.getFloat(Constants.WEATHER_DATA_TEMPERATURE, 0));\n description = mPrefWeather.getString(Constants.WEATHER_DATA_DESCRIPTION,\n \"clear sky\");\n wind = String.format(Locale.getDefault(), \"%.1f\",\n mPrefWeather.getFloat(Constants.WEATHER_DATA_WIND_SPEED, 0));\n sunrise = Utils.unixTimeToFormatTime(MainActivity.this, mPrefWeather\n .getLong(Constants.WEATHER_DATA_SUNRISE, -1));\n sunset = Utils.unixTimeToFormatTime(MainActivity.this, mPrefWeather\n .getLong(Constants.WEATHER_DATA_SUNSET, -1));\n weather = \"City: \" + Utils.getCityAndCountry(storedContext) +\n \"\\nTemperature: \" + temperature + temperatureScale +\n \"\\nDescription: \" + description +\n \"\\nWind: \" + wind + \" \" + mSpeedScale +\n \"\\nSunrise: \" + sunrise +\n \"\\nSunset: \" + sunset;\n Intent shareIntent = new Intent(Intent.ACTION_SEND);\n shareIntent.setType(\"text/plain\");\n shareIntent.putExtra(Intent.EXTRA_TEXT, weather);\n shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n try {\n startActivity(Intent.createChooser(shareIntent, \"Share Weather\"));\n } catch (ActivityNotFoundException e) {\n Toast.makeText(MainActivity.this,\n \"Communication app not found\",\n Toast.LENGTH_LONG).show();\n }\n }\n };\n\n private void detectLocation() {\n boolean isGPSEnabled = locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER)\n && locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);\n boolean isNetworkEnabled = locationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER)\n && locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);\n\n mProgressDialog = new ProgressDialog(MainActivity.this);\n mProgressDialog.setMessage(getString(R.string.progressDialog_gps_locate));\n mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);\n mProgressDialog.setIndeterminate(true);\n mProgressDialog.setCancelable(false);\n mProgressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n try {\n locationManager.removeUpdates(mLocationListener);\n } catch (SecurityException e) {\n Log.e(TAG, \"Cancellation error\", e);\n }\n }\n });\n\n if (isNetworkEnabled) {\n networkRequestLocation();\n mProgressDialog.show();\n } else {\n if (isGPSEnabled) {\n gpsRequestLocation();\n mProgressDialog.show();\n } else {\n showSettingsAlert();\n }\n }\n }\n\n public void showSettingsAlert() {\n AlertDialog.Builder settingsAlert = new AlertDialog.Builder(MainActivity.this);\n settingsAlert.setTitle(R.string.alertDialog_gps_title);\n settingsAlert.setMessage(R.string.alertDialog_gps_message);\n\n settingsAlert.setPositiveButton(R.string.alertDialog_gps_positiveButton,\n new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n Intent goToSettings = new Intent(\n Settings.ACTION_LOCATION_SOURCE_SETTINGS);\n startActivity(goToSettings);\n }\n });\n\n settingsAlert.setNegativeButton(R.string.alertDialog_gps_negativeButton,\n new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n dialog.cancel();\n }\n });\n\n settingsAlert.show();\n }\n\n public void gpsRequestLocation() {\n if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {\n Looper locationLooper = Looper.myLooper();\n locationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, mLocationListener, locationLooper);\n final Handler locationHandler = new Handler(locationLooper);\n locationHandler.postDelayed(new Runnable() {\n @Override\n public void run() {\n locationManager.removeUpdates(mLocationListener);\n if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {\n Location lastLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);\n if (lastLocation != null) {\n mLocationListener.onLocationChanged(lastLocation);\n } else {\n locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);\n }\n }\n }\n }, LOCATION_TIMEOUT_IN_MS);\n }\n }\n\n public void networkRequestLocation() {\n if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {\n Looper locationLooper = Looper.myLooper();\n locationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, mLocationListener, locationLooper);\n final Handler locationHandler = new Handler(locationLooper);\n locationHandler.postDelayed(new Runnable() {\n @Override\n public void run() {\n locationManager.removeUpdates(mLocationListener);\n if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {\n Location lastNetworkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);\n Location lastGpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);\n\n if ((lastGpsLocation == null) && (lastNetworkLocation != null)) {\n mLocationListener.onLocationChanged(lastNetworkLocation);\n } else if ((lastGpsLocation != null) && (lastNetworkLocation == null)) {\n mLocationListener.onLocationChanged(lastGpsLocation);\n } else {\n locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocationListener);\n }\n }\n }\n }, LOCATION_TIMEOUT_IN_MS);\n }\n }\n\n private void requestLocation() {\n int fineLocationPermission = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION);\n if (fineLocationPermission != PackageManager.PERMISSION_GRANTED) {\n requestLocationPermission();\n } else {\n detectLocation();\n }\n }\n\n private void requestLocationPermission() {\n if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {\n Snackbar.make(findViewById(android.R.id.content), R.string.permission_location_rationale, Snackbar.LENGTH_LONG)\n .setAction(android.R.string.ok, new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS_LOCATION, REQUEST_LOCATION);\n }\n }).show();\n } else {\n ActivityCompat.requestPermissions(this, PERMISSIONS_LOCATION, REQUEST_LOCATION);\n }\n }\n\n @Override\n public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {\n switch (requestCode) {\n case REQUEST_LOCATION:\n if (PermissionUtil.verifyPermissions(grantResults)) {\n Snackbar.make(findViewById(android.R.id.content), R.string.permission_available_location, Snackbar.LENGTH_SHORT).show();\n } else {\n Snackbar.make(findViewById(android.R.id.content), R.string.permission_not_granted, Snackbar.LENGTH_SHORT).show();\n }\n break;\n default:\n super.onRequestPermissionsResult(requestCode, permissions, grantResults);\n break;\n }\n }\n}", "public class LocationUpdateService extends Service implements LocationListener {\n\n private static final String TAG = \"LocationUpdateService\";\n\n private static final long LOCATION_TIMEOUT_IN_MS = 30000L;\n\n private LocationManager locationManager;\n\n private long lastLocationUpdateTime;\n\n @Override\n public IBinder onBind(Intent intent) {\n return null;\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);\n }\n\n @Override\n public int onStartCommand(Intent intent, int flags, final int startId) {\n int ret = super.onStartCommand(intent, flags, startId);\n requestLocation();\n return ret;\n }\n\n @Override\n public void onLocationChanged(Location location) {\n\n lastLocationUpdateTime = System.currentTimeMillis();\n String latitude = String.format(\"%1$.2f\", location.getLatitude());\n String longitude = String.format(\"%1$.2f\", location.getLongitude());\n Log.d(TAG, \"Lat: \" + latitude + \"; Long: \" + longitude);\n locationManager.removeUpdates(this);\n SharedPreferences mSharedPreferences = getSharedPreferences(Constants.APP_SETTINGS_NAME,\n Context.MODE_PRIVATE);\n SharedPreferences.Editor editor = mSharedPreferences.edit();\n editor.putString(Constants.APP_SETTINGS_LATITUDE, latitude);\n editor.putString(Constants.APP_SETTINGS_LONGITUDE, longitude);\n getAndWriteAddressFromGeocoder(latitude, longitude, editor);\n editor.apply();\n }\n\n @Override\n public void onStatusChanged(String provider, int status, Bundle extras) {\n }\n\n @Override\n public void onProviderEnabled(String provider) {\n }\n\n @Override\n public void onProviderDisabled(String provider) {\n locationManager.removeUpdates(this);\n }\n\n private void getAndWriteAddressFromGeocoder(String latitude, String longitude, SharedPreferences.Editor editor) {\n Geocoder geocoder = new Geocoder(this, Locale.getDefault());\n try {\n String latitudeEn = latitude.replace(\",\", \".\");\n String longitudeEn = longitude.replace(\",\", \".\");\n List<Address> addresses = geocoder.getFromLocation(Double.parseDouble(latitudeEn), Double.parseDouble(longitudeEn), 1);\n if ((addresses != null) && (addresses.size() > 0)) {\n editor.putString(Constants.APP_SETTINGS_GEO_CITY, addresses.get(0).getLocality());\n editor.putString(Constants.APP_SETTINGS_GEO_DISTRICT_OF_CITY, addresses.get(0).getSubLocality());\n editor.putString(Constants.APP_SETTINGS_GEO_COUNTRY_NAME, addresses.get(0).getCountryName());\n }\n } catch (IOException | NumberFormatException ex) {\n Log.e(TAG, \"Unable to get address from latitude and longitude\", ex);\n }\n }\n\n private void requestLocation() {\n int fineLocationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);\n if (fineLocationPermission != PackageManager.PERMISSION_GRANTED) {\n stopSelf();\n } else {\n detectLocation();\n }\n }\n\n private void detectLocation() {\n if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {\n final Looper locationLooper = Looper.myLooper();\n locationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, this, locationLooper);\n final LocationListener locationListener = this;\n final Handler locationHandler = new Handler(locationLooper);\n locationHandler.postDelayed(new Runnable() {\n @Override\n public void run() {\n locationManager.removeUpdates(locationListener);\n if ((System.currentTimeMillis() - (2 * LOCATION_TIMEOUT_IN_MS)) < lastLocationUpdateTime) {\n return;\n }\n if (ContextCompat.checkSelfPermission(LocationUpdateService.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {\n Location lastNetworkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);\n Location lastGpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);\n if ((lastGpsLocation == null) && (lastNetworkLocation != null)) {\n locationListener.onLocationChanged(lastNetworkLocation);\n } else if ((lastGpsLocation != null) && (lastNetworkLocation == null)) {\n locationListener.onLocationChanged(lastGpsLocation);\n } else {\n locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);\n new CountDownTimer(30000, 10000) {\n @Override\n public void onTick(long millisUntilFinished) {\n }\n\n @Override\n public void onFinish() {\n locationManager.removeUpdates(LocationUpdateService.this);\n stopSelf();\n }\n }.start();\n }\n }\n startService(new Intent(getBaseContext(), LessWidgetService.class));\n startService(new Intent(getBaseContext(), MoreWidgetService.class));\n }\n }, LOCATION_TIMEOUT_IN_MS);\n }\n }\n}", "public class AppPreference {\n\n public static String getTemperatureUnit(Context context) {\n return PreferenceManager.getDefaultSharedPreferences(context).getString(\n Constants.KEY_PREF_TEMPERATURE, \"metric\");\n }\n\n public static boolean hideDescription(Context context) {\n return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(\n Constants.KEY_PREF_HIDE_DESCRIPTION, false);\n }\n\n public static String getInterval(Context context) {\n return PreferenceManager.getDefaultSharedPreferences(context)\n .getString(Constants.KEY_PREF_INTERVAL_NOTIFICATION, \"60\");\n }\n\n public static boolean isVibrateEnabled(Context context) {\n return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(\n Constants.KEY_PREF_VIBRATE,\n false);\n }\n\n public static boolean isNotificationEnabled(Context context) {\n return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(\n Constants.KEY_PREF_IS_NOTIFICATION_ENABLED, false);\n }\n\n public static void saveWeather(Context context, Weather weather) {\n SharedPreferences preferences = context.getSharedPreferences(Constants.PREF_WEATHER_NAME,\n Context.MODE_PRIVATE);\n SharedPreferences.Editor editor = preferences.edit();\n editor.putFloat(Constants.WEATHER_DATA_TEMPERATURE, weather.temperature.getTemp());\n if(!hideDescription(context))\n {\n editor.putString(Constants.WEATHER_DATA_DESCRIPTION,\n weather.currentWeather.getDescription());\n }\n else {\n editor.putString(Constants.WEATHER_DATA_DESCRIPTION, \" \");\n }\n editor.putFloat(Constants.WEATHER_DATA_PRESSURE, weather.currentCondition.getPressure());\n editor.putInt(Constants.WEATHER_DATA_HUMIDITY, weather.currentCondition.getHumidity());\n editor.putFloat(Constants.WEATHER_DATA_WIND_SPEED, weather.wind.getSpeed());\n editor.putInt(Constants.WEATHER_DATA_CLOUDS, weather.cloud.getClouds());\n editor.putString(Constants.WEATHER_DATA_ICON, weather.currentWeather.getIdIcon());\n editor.putLong(Constants.WEATHER_DATA_SUNRISE, weather.sys.getSunrise());\n editor.putLong(Constants.WEATHER_DATA_SUNSET, weather.sys.getSunset());\n editor.apply();\n }\n\n public static String[] getCityAndCode(Context context) {\n SharedPreferences preferences = context.getSharedPreferences(Constants.APP_SETTINGS_NAME,\n Context.MODE_PRIVATE);\n String[] result = new String[2];\n result[0] = preferences.getString(Constants.APP_SETTINGS_CITY, \"London\");\n result[1] = preferences.getString(Constants.APP_SETTINGS_COUNTRY_CODE, \"UK\");\n return result;\n }\n\n public static boolean isGeocoderEnabled(Context context) {\n return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(\n Constants.KEY_PREF_WIDGET_USE_GEOCODER, false);\n }\n public static boolean isUpdateLocationEnabled(Context context) {\n return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(\n Constants.KEY_PREF_WIDGET_UPDATE_LOCATION, false);\n }\n \n public static String getTheme(Context context) {\n return PreferenceManager.getDefaultSharedPreferences(context).getString(\n Constants.KEY_PREF_WIDGET_THEME, \"dark\");\n }\n\n public static int getTextColor(Context context) {\n String theme = getTheme(context);\n if (null == theme) {\n return ContextCompat.getColor(context, R.color.widget_transparentTheme_textColorPrimary);\n } else switch (theme) {\n case \"dark\":\n return ContextCompat.getColor(context, R.color.widget_darkTheme_textColorPrimary);\n case \"light\":\n return ContextCompat.getColor(context, R.color.widget_lightTheme_textColorPrimary);\n default:\n return ContextCompat.getColor(context, R.color.widget_transparentTheme_textColorPrimary);\n }\n }\n \n public static int getBackgroundColor(Context context) {\n String theme = getTheme(context);\n if (null == theme) {\n return ContextCompat.getColor(context,\n R.color.widget_transparentTheme_colorBackground);\n } else switch (theme) {\n case \"dark\":\n return ContextCompat.getColor(context,\n R.color.widget_darkTheme_colorBackground);\n case \"light\":\n return ContextCompat.getColor(context,\n R.color.widget_lightTheme_colorBackground);\n default:\n return ContextCompat.getColor(context,\n R.color.widget_transparentTheme_colorBackground);\n }\n }\n \n public static int getWindowHeaderBackgroundColorId(Context context) {\n String theme = getTheme(context);\n if (null == theme) {\n return ContextCompat.getColor(context,\n R.color.widget_transparentTheme_window_colorBackground);\n } else switch (theme) {\n case \"dark\":\n return ContextCompat.getColor(context,\n R.color.widget_darkTheme_window_colorBackground);\n case \"light\":\n return ContextCompat.getColor(context,\n R.color.widget_lightTheme_window_colorBackground);\n default:\n return ContextCompat.getColor(context,\n R.color.widget_transparentTheme_window_colorBackground);\n }\n }\n \n public static long saveLastUpdateTimeMillis(Context context) {\n SharedPreferences sp = context.getSharedPreferences(Constants.APP_SETTINGS_NAME,\n Context.MODE_PRIVATE);\n long now = System.currentTimeMillis();\n sp.edit().putLong(Constants.LAST_UPDATE_TIME_IN_MS, now).apply();\n return now;\n }\n\n public static long getLastUpdateTimeMillis(Context context) {\n SharedPreferences sp = context.getSharedPreferences(Constants.APP_SETTINGS_NAME,\n Context.MODE_PRIVATE);\n return sp.getLong(Constants.LAST_UPDATE_TIME_IN_MS, 0);\n }\n\n public static String getWidgetUpdatePeriod(Context context) {\n return PreferenceManager.getDefaultSharedPreferences(context).getString(\n Constants.KEY_PREF_WIDGET_UPDATE_PERIOD, \"60\");\n }\n\n public static void saveWeatherForecast(Context context, List<WeatherForecast> forecastList) {\n SharedPreferences preferences = context.getSharedPreferences(Constants.PREF_FORECAST_NAME,\n Context.MODE_PRIVATE);\n SharedPreferences.Editor editor = preferences.edit();\n String weatherJson = new Gson().toJson(forecastList);\n editor.putString(\"daily_forecast\", weatherJson);\n editor.apply();\n }\n\n public static List<WeatherForecast> loadWeatherForecast(Context context) {\n SharedPreferences preferences = context.getSharedPreferences(Constants.PREF_FORECAST_NAME,\n Context.MODE_PRIVATE);\n String weather = preferences.getString(\"daily_forecast\",\n context.getString(R.string.default_daily_forecast));\n return new Gson().fromJson(weather,\n new TypeToken<List<WeatherForecast>>() {\n }.getType());\n }\n}", "public class AppWidgetProviderAlarm {\n\n private static final String TAG = \"AppWidgetProviderAlarm\";\n\n private Context mContext;\n private Class<?> mCls;\n\n public AppWidgetProviderAlarm(Context context, Class<?> cls) {\n this.mContext = context;\n this.mCls = cls;\n }\n\n public void setAlarm() {\n String updatePeriodStr = AppPreference.getWidgetUpdatePeriod(mContext);\n long updatePeriodMills = Utils.intervalMillisForAlarm(updatePeriodStr);\n AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);\n alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,\n SystemClock.elapsedRealtime() + updatePeriodMills,\n updatePeriodMills,\n getPendingIntent(mCls));\n }\n\n public void cancelAlarm() {\n AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);\n alarmManager.cancel(getPendingIntent(mCls));\n getPendingIntent(mCls).cancel();\n }\n\n private PendingIntent getPendingIntent(Class<?> cls) {\n Intent intent = new Intent(mContext, cls);\n intent.setAction(Constants.ACTION_FORCED_APPWIDGET_UPDATE);\n return PendingIntent.getBroadcast(mContext,\n 0,\n intent,\n PendingIntent.FLAG_CANCEL_CURRENT);\n }\n\n public boolean isAlarmOff() {\n Intent intent = new Intent(mContext, mCls);\n intent.setAction(Constants.ACTION_FORCED_APPWIDGET_UPDATE);\n PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext,\n 0,\n intent,\n PendingIntent.FLAG_NO_CREATE);\n return pendingIntent == null;\n }\n}", "public class Constants {\n\n /**\n * SharedPreference names\n */\n public static final String APP_SETTINGS_NAME = \"config\";\n public static final String PREF_WEATHER_NAME = \"weather_pref\";\n public static final String PREF_FORECAST_NAME = \"weather_forecast\";\n\n /**\n * Preferences constants\n */\n public static final String APP_SETTINGS_LATITUDE = \"latitude\";\n public static final String APP_SETTINGS_LONGITUDE = \"longitude\";\n public static final String APP_SETTINGS_CITY = \"city\";\n public static final String APP_SETTINGS_COUNTRY_CODE = \"country_code\";\n public static final String APP_SETTINGS_GEO_COUNTRY_NAME = \"geo_country_name\";\n public static final String APP_SETTINGS_GEO_DISTRICT_OF_CITY = \"geo_district_name\";\n public static final String APP_SETTINGS_GEO_CITY = \"geo_city_name\";\n public static final String LAST_UPDATE_TIME_IN_MS = \"last_update\";\n \n public static final String KEY_PREF_IS_NOTIFICATION_ENABLED = \"notification_pref_key\";\n public static final String KEY_PREF_TEMPERATURE = \"temperature_pref_key\";\n public static final String KEY_PREF_HIDE_DESCRIPTION = \"hide_desc_pref_key\";\n public static final String KEY_PREF_INTERVAL_NOTIFICATION = \"notification_interval_pref_key\";\n public static final String KEY_PREF_VIBRATE = \"notification_vibrate_pref_key\";\n public static final String KEY_PREF_WIDGET_UPDATE_LOCATION = \"widget_update_location_pref_key\";\n public static final String KEY_PREF_WIDGET_USE_GEOCODER = \"widget_use_geocoder_pref_key\";\n public static final String KEY_PREF_WIDGET_THEME = \"widget_theme_pref_key\";\n public static final String KEY_PREF_WIDGET_UPDATE_PERIOD = \"widget_update_period_pref_key\";\n public static final String PREF_LANGUAGE = \"language_pref_key\";\n public static final String PREF_THEME = \"theme_pref_key\";\n\n /**\n * About preference screen constants\n */\n public static final String KEY_PREF_ABOUT_VERSION = \"about_version_pref_key\";\n public static final String KEY_PREF_ABOUT_F_DROID = \"about_f_droid_pref_key\";\n public static final String KEY_PREF_ABOUT_GOOGLE_PLAY = \"about_google_play_pref_key\";\n public static final String KEY_PREF_ABOUT_OPEN_SOURCE_LICENSES =\n \"about_open_source_licenses_pref_key\";\n\n public static final String WEATHER_DATA_TEMPERATURE = \"temperature\";\n public static final String WEATHER_DATA_DESCRIPTION = \"description\";\n public static final String WEATHER_DATA_PRESSURE = \"pressure\";\n public static final String WEATHER_DATA_HUMIDITY = \"humidity\";\n public static final String WEATHER_DATA_WIND_SPEED = \"wind_speed\";\n public static final String WEATHER_DATA_CLOUDS = \"clouds\";\n public static final String WEATHER_DATA_ICON = \"icon\";\n public static final String WEATHER_DATA_SUNRISE = \"sunrise\";\n public static final String WEATHER_DATA_SUNSET = \"sunset\";\n\n /**\n * Widget action constants\n */\n public static final String ACTION_FORCED_APPWIDGET_UPDATE =\n \"org.asdtm.goodweather.action.FORCED_APPWIDGET_UPDATE\";\n public static final String ACTION_APPWIDGET_THEME_CHANGED =\n \"org.asdtm.goodweather.action.APPWIDGET_THEME_CHANGED\";\n public static final String ACTION_APPWIDGET_UPDATE_PERIOD_CHANGED =\n \"org.asdtm.goodweather.action.APPWIDGET_UPDATE_PERIOD_CHANGED\";\n\n /**\n * URIs constants\n */\n public static final String SOURCE_CODE_URI = \"https://github.com/qqq3/good-weather\";\n public static final String GOOGLE_PLAY_APP_URI = \"market://details?id=%s\";\n public static final String GOOGLE_PLAY_WEB_URI =\n \"http://play.google.com/store/apps/details?id=%s\";\n public static final String F_DROID_WEB_URI = \"https://f-droid.org/repository/browse/?fdid=%s\";\n public static final String WEATHER_ENDPOINT = \"http://api.openweathermap.org/data/2.5/weather\";\n public static final String WEATHER_FORECAST_ENDPOINT = \"http://api.openweathermap.org/data/2.5/forecast/daily\";\n\n public static final String BITCOIN_ADDRESS = \"1FV8m1MKqZ9ZKB8YNwpsjsuubHTznJSiT8\";\n\n public static final int PARSE_RESULT_SUCCESS = 0;\n public static final int TASK_RESULT_ERROR = -1;\n public static final int PARSE_RESULT_ERROR = -2;\n}", "public class Utils {\n\n public static Bitmap createWeatherIcon(Context context, String text) {\n Bitmap bitmap = Bitmap.createBitmap(256, 256, Bitmap.Config.ARGB_4444);\n Canvas canvas = new Canvas(bitmap);\n Paint paint = new Paint();\n Typeface weatherFont = Typeface.createFromAsset(context.getAssets(),\n \"fonts/weathericons-regular-webfont.ttf\");\n\n paint.setAntiAlias(true);\n paint.setSubpixelText(true);\n paint.setTypeface(weatherFont);\n paint.setStyle(Paint.Style.FILL);\n paint.setColor(AppPreference.getTextColor(context));\n paint.setTextSize(180);\n paint.setTextAlign(Paint.Align.CENTER);\n canvas.drawText(text, 128, 200, paint);\n return bitmap;\n }\n\n public static String getStrIcon(Context context, String iconId) {\n String icon;\n switch (iconId) {\n case \"01d\":\n icon = context.getString(R.string.icon_clear_sky_day);\n break;\n case \"01n\":\n icon = context.getString(R.string.icon_clear_sky_night);\n break;\n case \"02d\":\n icon = context.getString(R.string.icon_few_clouds_day);\n break;\n case \"02n\":\n icon = context.getString(R.string.icon_few_clouds_night);\n break;\n case \"03d\":\n icon = context.getString(R.string.icon_scattered_clouds);\n break;\n case \"03n\":\n icon = context.getString(R.string.icon_scattered_clouds);\n break;\n case \"04d\":\n icon = context.getString(R.string.icon_broken_clouds);\n break;\n case \"04n\":\n icon = context.getString(R.string.icon_broken_clouds);\n break;\n case \"09d\":\n icon = context.getString(R.string.icon_shower_rain);\n break;\n case \"09n\":\n icon = context.getString(R.string.icon_shower_rain);\n break;\n case \"10d\":\n icon = context.getString(R.string.icon_rain_day);\n break;\n case \"10n\":\n icon = context.getString(R.string.icon_rain_night);\n break;\n case \"11d\":\n icon = context.getString(R.string.icon_thunderstorm);\n break;\n case \"11n\":\n icon = context.getString(R.string.icon_thunderstorm);\n break;\n case \"13d\":\n icon = context.getString(R.string.icon_snow);\n break;\n case \"13n\":\n icon = context.getString(R.string.icon_snow);\n break;\n case \"50d\":\n icon = context.getString(R.string.icon_mist);\n break;\n case \"50n\":\n icon = context.getString(R.string.icon_mist);\n break;\n default:\n icon = context.getString(R.string.icon_weather_default);\n }\n\n return icon;\n }\n\n public static String getTemperatureScale(Context context) {\n String[] temperatureScaleArray = context.getResources().getStringArray(\n R.array.pref_temperature_entries);\n String unitPref = AppPreference.getTemperatureUnit(context);\n return unitPref.equals(\"metric\") ?\n temperatureScaleArray[0] : temperatureScaleArray[1];\n }\n\n public static String getSpeedScale(Context context) {\n String unitPref = AppPreference.getTemperatureUnit(context);\n return unitPref.equals(\"metric\") ?\n context.getString(R.string.wind_speed_meters) :\n context.getString(R.string.wind_speed_miles);\n }\n\n public static String setLastUpdateTime(Context context, long lastUpdate) {\n Date lastUpdateTime = new Date(lastUpdate);\n return DateFormat.getTimeFormat(context).format(lastUpdateTime);\n }\n\n public static long intervalMillisForAlarm(String intervalMinutes) {\n int interval = Integer.parseInt(intervalMinutes);\n switch (interval) {\n case 15:\n return AlarmManager.INTERVAL_FIFTEEN_MINUTES;\n case 30:\n return AlarmManager.INTERVAL_HALF_HOUR;\n case 60:\n return AlarmManager.INTERVAL_HOUR;\n case 720:\n return AlarmManager.INTERVAL_HALF_DAY;\n case 1440:\n return AlarmManager.INTERVAL_DAY;\n default:\n return interval * 60 * 1000;\n }\n }\n\n public static String unixTimeToFormatTime(Context context, long unixTime) {\n long unixTimeToMillis = unixTime * 1000;\n return DateFormat.getTimeFormat(context).format(unixTimeToMillis);\n }\n\n public static void copyToClipboard(Context context, String string) {\n ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(\n Context.CLIPBOARD_SERVICE);\n ClipData clipData = ClipData.newPlainText(string, string);\n clipboardManager.setPrimaryClip(clipData);\n }\n\n public static String windDegreeToDirections(Context context, double windDegree) {\n String[] directions = context.getResources().getStringArray(R.array.wind_directions);\n String[] arrows = context.getResources().getStringArray(R.array.wind_direction_arrows);\n int index = (int) Math.abs(Math.round(windDegree % 360) / 45);\n\n return directions[index] + \" \" + arrows[index];\n }\n\n public static URL getWeatherForecastUrl(String endpoint, String lat, String lon, String units, String lang) throws\n MalformedURLException {\n String url = Uri.parse(endpoint)\n .buildUpon()\n .appendQueryParameter(\"appid\", ApiKeys.OPEN_WEATHER_MAP_API_KEY)\n .appendQueryParameter(\"lat\", lat)\n .appendQueryParameter(\"lon\", lon)\n .appendQueryParameter(\"units\", units)\n .appendQueryParameter(\"lang\", \"cs\".equalsIgnoreCase(lang)?\"cz\":lang)\n .build()\n .toString();\n return new URL(url);\n }\n \n public static String getCityAndCountry(Context context) {\n SharedPreferences preferences = context.getSharedPreferences(Constants.APP_SETTINGS_NAME, 0);\n \n if(AppPreference.isGeocoderEnabled(context)) {\n return getCityAndCountryFromGeolocation(preferences);\n } else {\n return getCityAndCountryFromPreference(context);\n }\n }\n \n private static String getCityAndCountryFromGeolocation(SharedPreferences preferences) {\n String geoCountryName = preferences.getString(Constants.APP_SETTINGS_GEO_COUNTRY_NAME, \"United Kingdom\");\n String geoCity = preferences.getString(Constants.APP_SETTINGS_GEO_CITY, \"London\");\n if(\"\".equals(geoCity)) {\n return geoCountryName;\n }\n String geoDistrictOfCity = preferences.getString(Constants.APP_SETTINGS_GEO_DISTRICT_OF_CITY, \"\");\n if (\"\".equals(geoDistrictOfCity) || geoCity.equalsIgnoreCase(geoDistrictOfCity)) {\n return geoCity + \", \" + geoCountryName;\n }\n return geoCity + \" - \" + geoDistrictOfCity + \", \" + geoCountryName;\n }\n\n private static String getCityAndCountryFromPreference(Context context) {\n String[] cityAndCountryArray = AppPreference.getCityAndCode(context);\n return cityAndCountryArray[0] + \", \" + cityAndCountryArray[1];\n }\n}" ]
import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.widget.RemoteViews; import org.asdtm.goodweather.MainActivity; import org.asdtm.goodweather.R; import org.asdtm.goodweather.service.LocationUpdateService; import org.asdtm.goodweather.utils.AppPreference; import org.asdtm.goodweather.utils.AppWidgetProviderAlarm; import org.asdtm.goodweather.utils.Constants; import org.asdtm.goodweather.utils.Utils; import java.util.Locale;
package org.asdtm.goodweather.widget; public class LessWidgetProvider extends AppWidgetProvider { private static final String TAG = "WidgetLessInfo"; @Override public void onEnabled(Context context) { super.onEnabled(context); AppWidgetProviderAlarm widgetProviderAlarm = new AppWidgetProviderAlarm(context, LessWidgetProvider.class); widgetProviderAlarm.setAlarm(); } @Override public void onReceive(Context context, Intent intent) { switch (intent.getAction()) { case Constants.ACTION_FORCED_APPWIDGET_UPDATE: if(AppPreference.isUpdateLocationEnabled(context)) { context.startService(new Intent(context, LocationUpdateService.class)); } else { context.startService(new Intent(context, LessWidgetService.class)); } break; case Intent.ACTION_LOCALE_CHANGED: context.startService(new Intent(context, LessWidgetService.class)); break; case Constants.ACTION_APPWIDGET_THEME_CHANGED: AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context); ComponentName componentName = new ComponentName(context, LessWidgetProvider.class); int[] appWidgetIds = appWidgetManager.getAppWidgetIds(componentName); onUpdate(context, appWidgetManager, appWidgetIds); break; case Constants.ACTION_APPWIDGET_UPDATE_PERIOD_CHANGED: AppWidgetProviderAlarm widgetProviderAlarm = new AppWidgetProviderAlarm(context, LessWidgetProvider.class); if (widgetProviderAlarm.isAlarmOff()) { break; } else { widgetProviderAlarm.setAlarm(); } break; default: super.onReceive(context, intent); } } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { super.onUpdate(context, appWidgetManager, appWidgetIds); for (int appWidgetId : appWidgetIds) { RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_less_3x1); setWidgetTheme(context, remoteViews); preLoadWeather(context, remoteViews); Intent intent = new Intent(context, LessWidgetProvider.class); intent.setAction(Constants.ACTION_FORCED_APPWIDGET_UPDATE); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0); remoteViews.setOnClickPendingIntent(R.id.widget_button_refresh, pendingIntent); Intent intentStartActivity = new Intent(context, MainActivity.class); PendingIntent pendingIntent2 = PendingIntent.getActivity(context, 0, intentStartActivity, 0); remoteViews.setOnClickPendingIntent(R.id.widget_root, pendingIntent2); appWidgetManager.updateAppWidget(appWidgetId, remoteViews); } context.startService(new Intent(context, LessWidgetService.class)); } @Override public void onDisabled(Context context) { super.onDisabled(context); AppWidgetProviderAlarm appWidgetProviderAlarm = new AppWidgetProviderAlarm(context, LessWidgetProvider.class); appWidgetProviderAlarm.cancelAlarm(); } private void preLoadWeather(Context context, RemoteViews remoteViews) { SharedPreferences weatherPref = context.getSharedPreferences(Constants.PREF_WEATHER_NAME, Context.MODE_PRIVATE);
String temperatureScale = Utils.getTemperatureScale(context);
5
lob/lob-java
src/main/java/com/lob/model/Template.java
[ "public class APIException extends LobException {\n\n private static final long serialVersionUID = 1L;\n\n @JsonCreator\n public APIException(@JsonProperty(\"error\") final Map<String, Object> error) {\n super((String)error.get(\"message\"), (Integer)error.get(\"status_code\"));\n }\n\n}", "public class AuthenticationException extends LobException {\n\n private static final long serialVersionUID = 1L;\n\n public AuthenticationException(String message, Integer statusCode) {\n super(message, statusCode);\n }\n\n}", "public class InvalidRequestException extends LobException {\n \n private static final long serialVersionUID = 1L;\n\n @JsonCreator\n public InvalidRequestException(@JsonProperty(\"error\") final Map<String, Object> error) {\n super((String)error.get(\"message\"), (Integer)error.get(\"status_code\"));\n }\n\n}", "public class ParsingException extends LobException {\n\n private static final long serialVersionUID = 1L;\n\n public ParsingException(Exception e) {\n super(e.getMessage(), 0, e);\n }\n}", "public class RateLimitException extends LobException {\n\n private static final long serialVersionUID = 1L;\n\n @JsonCreator\n public RateLimitException(@JsonProperty(\"error\") final Map<String, Object> error) {\n super((String)error.get(\"message\"), (Integer)error.get(\"status_code\"));\n }\n\n}", "public abstract class APIResource {\n\n private static ResponseGetter responseGetter = new ResponseGetter();\n\n public static final String CHARSET = \"UTF-8\";\n\n public enum RequestMethod {\n GET, POST, DELETE\n }\n\n public enum RequestType {\n NORMAL, MULTIPART, JSON\n }\n\n public static <T> LobResponse<T> request(APIResource.RequestMethod method, APIResource.RequestType type,\n String url, Map<String, Object> params, Class<T> clazz,\n RequestOptions options) throws AuthenticationException, APIException, RateLimitException, InvalidRequestException, IOException {\n return responseGetter.request(method, url, params, clazz, type, options);\n }\n\n public static <T> LobResponse<T> request(APIResource.RequestMethod method, APIResource.RequestType type,\n String url, Map<String, Object> params, Map<String, Object> query, Class<T> clazz,\n RequestOptions options) throws AuthenticationException, APIException, RateLimitException, InvalidRequestException, IOException {\n return responseGetter.request(method, url, params, query, clazz, type, options);\n }\n\n}", "public class LobResponse<T> {\n\n int responseCode;\n T responseBody;\n Map<String, List<String>> responseHeaders;\n\n public LobResponse(int responseCode, T responseBody) {\n this.responseCode = responseCode;\n this.responseBody = responseBody;\n this.responseHeaders = null;\n }\n\n public LobResponse(int responseCode, T responseBody, Map<String, List<String>> responseHeaders) {\n this.responseCode = responseCode;\n this.responseBody = responseBody;\n this.responseHeaders = responseHeaders;\n }\n\n public int getResponseCode() {\n return responseCode;\n }\n\n public T getResponseBody() {\n return responseBody;\n }\n\n public Map<String, List<String>> getResponseHeaders() {\n return responseHeaders;\n }\n}", "public class RequestOptions {\n public static RequestOptions getDefault() {\n return new RequestOptions(Lob.apiKey, Lob.apiVersion, null, null);\n }\n\n private final String apiKey;\n private final String lobVersion;\n private final String idempotencyKey;\n private final Proxy proxy;\n\n private RequestOptions(String apiKey, String lobVersion, String idempotencyKey, Proxy proxy) {\n this.apiKey = apiKey;\n this.lobVersion = lobVersion;\n this.idempotencyKey = idempotencyKey;\n this.proxy = proxy;\n }\n\n public String getApiKey() {\n return apiKey;\n }\n\n public String getLobVersion() {\n return lobVersion;\n }\n\n public String getIdempotencyKey() {\n return idempotencyKey;\n }\n \n public Proxy getProxy() {\n \treturn proxy;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n else if (o instanceof RequestOptions) {\n RequestOptions that = (RequestOptions) o;\n \n if (!Objects.equals(this.apiKey, that.getApiKey())) {\n return false;\n }\n \n if (!Objects.equals(this.lobVersion, that.getLobVersion())) {\n return false;\n }\n \n if (!Objects.equals(this.idempotencyKey, that.getIdempotencyKey())) {\n return false;\n } \n \n return true;\n } else {\n return false;\n }\n }\n \n @Override\n public int hashCode() {\n return Objects.hash(apiKey, lobVersion, idempotencyKey);\n } \n\n public static final class Builder {\n private String apiKey;\n private String lobVersion;\n private String idempotencyKey;\n private Proxy proxy;\n\n public Builder() {\n this.apiKey = Lob.apiKey;\n this.lobVersion = Lob.apiVersion;\n }\n\n public String getApiKey() {\n return this.apiKey;\n }\n\n public Builder setApiKey(String apiKey) {\n this.apiKey = apiKey;\n return this;\n }\n\n public Builder setLobVersion(String lobVersion) {\n this.lobVersion = lobVersion;\n return this;\n }\n\n public String getLobVersion() {\n return this.lobVersion;\n }\n\n public Builder setIdempotencyKey(String idempotencyKey) {\n this.idempotencyKey = idempotencyKey;\n return this;\n }\n\n public String getIdempotencyKey() {\n return this.idempotencyKey;\n }\n \n public Builder setProxy(Proxy proxy) {\n \tthis.proxy = proxy;\n \treturn this;\n }\n \n public Proxy getProxy() {\n \treturn this.proxy;\n }\n\n public RequestOptions build() {\n return new RequestOptions(this.apiKey, this.lobVersion, this.idempotencyKey, this.proxy);\n }\n }\n\n}" ]
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.lob.exception.APIException; import com.lob.exception.AuthenticationException; import com.lob.exception.InvalidRequestException; import com.lob.exception.ParsingException; import com.lob.exception.RateLimitException; import com.lob.net.APIResource; import com.lob.net.LobResponse; import com.lob.net.RequestOptions; import java.io.File; import java.io.IOException; import java.time.LocalDate; import java.time.ZonedDateTime; import java.util.HashMap; import java.util.List; import java.util.Map;
public boolean getSuggestJsonEditor() { return suggestJsonEditor; } public String getDescription() { return description; } public String getEngine() { return engine; } public String getHtml() { return html; } public ZonedDateTime getDateCreated() { return dateCreated; } public ZonedDateTime getDateModified() { return dateModified; } public String getObject() { return object; } } @JsonProperty private final String id; @JsonProperty private final String description; @JsonProperty private final List<TemplateVersion> versions; @JsonProperty private final TemplateVersion publishedVersion; @JsonProperty private final Map<String, String> metadata; @JsonProperty private final ZonedDateTime dateCreated; @JsonProperty private final ZonedDateTime dateModified; @JsonProperty private final String object; @JsonCreator public Template( @JsonProperty("id") final String id, @JsonProperty("description") final String description, @JsonProperty("versions") final List<TemplateVersion> versions, @JsonProperty("published_version") final TemplateVersion publishedVersion, @JsonProperty("metadata") final Map<String, String> metadata, @JsonProperty("date_created") final ZonedDateTime dateCreated, @JsonProperty("date_modified") final ZonedDateTime dateModified, @JsonProperty("object") final String object ) { this.id = id; this.description = description; this.versions = versions; this.publishedVersion = publishedVersion; this.metadata = metadata; this.dateCreated = dateCreated; this.dateModified = dateModified; this.object = object; } public String getId() { return id; } public String getDescription() { return description; } public List<TemplateVersion> getVersions() { return versions; } public TemplateVersion getPublishedVersion() { return publishedVersion; } public Map<String, String> getMetadata() { return metadata; } public ZonedDateTime getDateCreated() { return dateCreated; } public ZonedDateTime getDateModified() { return dateModified; } public String getObject() { return object; } public static final class RequestBuilder { private Map<String, Object> params = new HashMap<String, Object>(); private boolean isMultipart = false; private ObjectMapper objectMapper = new ObjectMapper(); public RequestBuilder() { } public Template.RequestBuilder setDescription(String description) { params.put("description", description); return this; } public Template.RequestBuilder setHtml(String html) { params.put("html", html); return this; } public Template.RequestBuilder setMetadata(Map<String, String> metadata) { params.put("metadata", metadata); return this; } public Template.RequestBuilder setEngine(String engine) { params.put("engine", engine); return this; } public LobResponse<Template> create() throws APIException, IOException, AuthenticationException, InvalidRequestException, RateLimitException { return create(null); }
public LobResponse<Template> create(RequestOptions options) throws APIException, IOException, AuthenticationException, InvalidRequestException, RateLimitException {
7
SkaceKamen/sqflint
src/cz/zipek/sqflint/sqf/operators/ThenOperator.java
[ "public class Linter extends SQFParser {\n\tpublic static final int CODE_OK = 0;\n\tpublic static final int CODE_ERR = 1;\n\t\n\tprivate final List<SQFParseException> errors = new ArrayList<>();\n\tprivate final List<Warning> warnings = new ArrayList<>();\n\t\n\tprivate final List<SQFInclude> includes = new ArrayList<>();\n\tprivate final List<SQFMacro> macros = new ArrayList<>();\n\t\t\n\tprivate SQFPreprocessor preprocessor;\n\tprivate final Options options;\n\t\n\tprivate Date startTime;\n\tprivate String filePath;\n\n\tpublic Linter(\n\t\tOptions options,\n\t\tSQFPreprocessor preprocessor,\n\t\tInputStream stream,\n\t\tString filePath\n\t) {\n\t\tsuper(stream);\n\t\t\n\t\tthis.options = options;\n\t\tthis.preprocessor = preprocessor;\n\t\tthis.filePath = filePath;\n\t}\n\t\n\tpublic int start() throws IOException {\n\t\tsetTabSize(1);\n\t\t\n\t\tSQFBlock block = null;\n\n\t\tstartTime = new Date();\n\t\tLogUtil.benchLog(options, this, filePath, \"Linter (1) \");\n\t\ttry {\n\t\t\tblock = CompilationUnit();\n\t\t} catch (ParseException | TokenMgrError e) {\n\t\t\tif (e instanceof SQFParseException) {\n\t\t\t\tgetErrors().add((SQFParseException)e);\n\t\t\t} else if (e instanceof ParseException) {\n\t\t\t\tgetErrors().add(new SQFParseException((ParseException)e));\n\t\t\t} else if (e instanceof TokenMgrError) {\n\t\t\t\tgetErrors().add(new SQFParseException((TokenMgrError)e));\n\t\t\t}\n\t\t} finally {\n\t\t\tif (block != null) {\n\t\t\t\tLogUtil.benchLog(options, this, filePath, \"Linter (2)\");\n\t\t\t\tblock.analyze(this, null);\n\t\t\t\tLogUtil.benchLog(options, this, filePath, \"Linter (3)\");\n\t\t\t}\n\t\t}\n\t\tLogUtil.benchLog(options, this, filePath, \"Linter (4)\");\n\t\t\n\t\t// Always return OK if exit code is disabled\n\t\tif (!options.isExitCodeEnabled()) {\n\t\t\treturn CODE_OK;\n\t\t}\n\t\t\n\t\t// Return ERR code when any error was encountered\n\t\treturn (getErrors().size() > 0) ? CODE_ERR : CODE_OK;\n\t}\n\n\tpublic Date getStartTime() {\n\t\treturn startTime;\n\t}\n\t\t\n\t/**\n\t * Post parse checks, mainly for warnings.\n\t * Currently checks if every used local variable is actually defined.\n\t */\n\t// protected void postParse() {\n\t// \tif (options.isSkipWarnings()) return;\n\n\t// \tgetWarnings().addAll(preprocessor.getWarnings());\n\t// }\n\t\n\t@Override\n\tprotected void pushContext(boolean newThread) {\n\t\tcontext = new SQFContext(this, context, newThread);\n\t}\n\n\t@Override\n\tprotected Linter getLinter() {\n\t\treturn this;\n\t}\n\t\n\tpublic SQFContext getContext() {\n\t\treturn context;\n\t}\n\t\n\t/**\n\t * Adds undefined message for specified token.\n\t * \n\t * @param token token of undefined variable\n\t * @return \n\t */\n\tpublic SQFParseException addUndefinedMessage(Token token) {\n\t\tSQFParseException ex;\n\t\tif (options.isWarningAsError()) {\n\t\t\tex = new SQFParseException(token, \"Possibly undefined variable \" + token);\n\t\t\tgetErrors().add(ex);\n\t\t} else {\n\t\t\tex = new Warning(token, \"Possibly undefined variable \" + token);\n\t\t\tgetWarnings().add((Warning)ex);\n\t\t}\n\t\treturn ex;\n\t}\n\t\n\t/**\n\t * Tries to recover from error if enabled.\n\t * This allows us to catch more errors per file. Adds error to list of encountered problems.\n\t * \n\t * @param ex\n\t * @param recoveryPoint \n\t * @param skip \n\t * @return recovery point (EOF or recoveryPoint)\n\t * @throws cz.zipek.sqflint.parser.ParseException \n\t */\n\t@Override\n\tprotected int recover(ParseException ex, int recoveryPoint, boolean skip) throws ParseException {\n\t\t// Add to list of encountered errors\n\t\tif (!(ex instanceof SQFParseException)) {\n\t\t\tgetErrors().add(new SQFParseException(ex));\n\t\t} else {\n\t\t\tgetErrors().add((SQFParseException)ex);\n\t\t}\n\t\t\n\t\t// Don't actually recover if needed\n\t\tif (options.isStopOnError()) {\n\t\t\tthrow ex;\n\t\t}\n\t\n\t\t// Skip token with error\n\t\tgetNextToken();\n\t\t\n\t\t// Scan until we reach recovery point or EOF\n\t\t// We need to start AT recovery point, so only peek, don't consume\n\t\t// Only consume when it isn't recovery point\n\t\tToken t;\n\t\twhile(true) {\n\t\t\tt = getToken(1);\n\t\t\tif (t.kind == recoveryPoint || t.kind == EOF) {\n\t\t\t\tif (skip) getNextToken();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tgetNextToken();\n\t\t}\n\t\t\n\t\treturn t.kind;\n\t}\n\n\t/**\n\t * @return the errors\n\t */\n\tpublic List<SQFParseException> getErrors() {\n\t\treturn errors;\n\t}\n\n\t/**\n\t * @return the variables\n\t */\n\tpublic Map<String, SQFVariable> getVariables() {\n\t\tMap<String, SQFVariable> variables = new HashMap<>();\n\t\t\n\t\tif (context != null) {\n\t\t\taddContextVariables(variables, context);\n\t\t} else {\n\t\t\tSystem.err.println(\"NO CONTEXT!\");\n\t\t}\n\t\t\n\t\treturn variables;\n\t}\n\t\n\tprivate void addContextVariables(Map<String, SQFVariable> container, SQFContext context) {\n\t\tmergeVariables(container, context.getVariables());\n\t\tcontext.getChildren().forEach(child -> { addContextVariables(container, child); });\n\t}\n\t\n\tprivate void mergeVariables(Map<String, SQFVariable> container, Map<String, SQFVariable> newVariables) {\n\t\tnewVariables.keySet().forEach(key -> {\n\t\t\tSQFVariable added = newVariables.get(key);\n\t\t\tif (container.containsKey(key)) {\n\t\t\t\tSQFVariable var = container.get(key);\n\t\t\t\tvar.usage.addAll(added.usage);\n\t\t\t\tvar.definitions.addAll(added.definitions);\n\t\t\t\tvar.comments.addAll(added.comments);\n\t\t\t} else {\n\t\t\t\tcontainer.put(key, added.copy());\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * @return the warnings\n\t */\n\tpublic List<Warning> getWarnings() {\n\t\treturn warnings;\n\t}\n\n\t/**\n\t * @return the includes\n\t */\n\tpublic List<SQFInclude> getIncludes() {\n\t\treturn includes;\n\t}\n\n\t/**\n\t * @return the macros\n\t */\n\tpublic List<SQFMacro> getMacros() {\n\t\treturn macros;\n\t}\n\n\t/**\n\t * @return the preprocessor\n\t */\n\tpublic SQFPreprocessor getPreprocessor() {\n\t\treturn preprocessor;\n\t}\n\n\t/**\n\t * @return the options\n\t */\n\tpublic Options getOptions() {\n\t\treturn options;\n\t}\n}", "public class SQFParseException extends ParseException {\n\n\tprotected String jsonMessage;\n\tprivate String originFilename;\n\n\tpublic SQFParseException(Token token, String message) {\n\t\tsuper(message);\n\t\tcurrentToken = token;\n\t\tjsonMessage = message;\n\t\t\n\t\tif (token == null) {\n\t\t\tthrow new IllegalArgumentException(\"Token can't be null.\");\n\t\t}\n\t}\n\t\n\tpublic SQFParseException(String filename, Token token, String message) {\n\t\tsuper(message);\n\t\toriginFilename = filename;\n\t\tcurrentToken = token;\n\t\tjsonMessage = message;\n\t\t\n\t\tif (token == null) {\n\t\t\tthrow new IllegalArgumentException(\"Token can't be null.\");\n\t\t}\n\t}\n\t\n\tpublic SQFParseException(ParseException ex) {\n\t\tsuper(buildMessage(ex, true));\n\t\t\n\t\tcurrentToken = ex.currentToken;\n\t\tjsonMessage = buildMessage(ex, false);\n\t}\n\t\n\tpublic SQFParseException(TokenMgrError ex) {\n\t\tsuper(ex.getMessage());\n\t\t\n\t\tcurrentToken = null;\n\t\tjsonMessage = ex.getMessage();\n\t}\n\t\n\tpublic String getJSONMessage() {\n\t\treturn jsonMessage;\n\t}\n\n\tstatic String buildMessage(ParseException ex, boolean position) {\n\t\tif (ex.expectedTokenSequences == null) {\n\t\t\treturn ex.getMessage();\n\t\t}\n\t\t\t\n\t\tToken currentToken = ex.currentToken;\n\t\tint[][] expectedTokenSequences = ex.expectedTokenSequences;\n\t\tString[] tokenImage = ex.tokenImage;\n\t\t\n\t\tString line = System.getProperty(\"line.separator\", \"\\n\");\n\t\tStringBuilder expected = new StringBuilder();\n\t\tint maxSize = 0;\n\t\tfor (int[] expectedTokenSequence : expectedTokenSequences) {\n\t\t\tif (maxSize < expectedTokenSequence.length) {\n\t\t\t\tmaxSize = expectedTokenSequence.length;\n\t\t\t}\n\t\t\tfor (int j = 0; j < expectedTokenSequence.length; j++) {\n\t\t\t\texpected.append(tokenImage[expectedTokenSequence[j]]).append(' ');\n\t\t\t}\n\t\t\tif (expectedTokenSequence[expectedTokenSequence.length - 1] != 0) {\n\t\t\t\texpected.append(\"...\");\n\t\t\t}\n\t\t\texpected.append(line).append(\" \");\n\t\t}\n\t\tString retval = \"Encountered \\\"\";\n\t\tToken tok = currentToken.next;\n\t\t/*\n\t\tfor (int i = 0; i < maxSize; i++) {\n\t\t\tif (i != 0) {\n\t\t\t\tretval += \" \";\n\t\t\t}\n\t\t\tif (tok.kind == 0) {\n\t\t\t\tretval += tokenImage[0];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tretval += \" \" + tokenImage[tok.kind];\n\t\t\tretval += \" \\\"\";\n\t\t\tretval += add_escapes(tok.image);\n\t\t\tretval += \" \\\"\";\n\t\t\ttok = tok.next;\n\t\t}\n\t\t*/\n\t\tretval += add_escapes(tok.toString());\n\t\tretval += \"\\\"\";\n\t\tif (position) {\n\t\t\tretval += \" at line \" + currentToken.next.beginLine + \", column \" + currentToken.next.beginColumn;\n\t\t}\n\t\tretval += \".\" + line;\n\t\tif (expectedTokenSequences.length == 1) {\n\t\t\tretval += \"Was expecting:\" + line + \" \";\n\t\t} else {\n\t\t\tretval += \"Was expecting one of:\" + line + \" \";\n\t\t}\n\t\tretval += expected.toString();\n\t\treturn retval;\n\t}\n\t\n\tstatic String add_escapes(String str) {\n\t\tStringBuilder retval = new StringBuilder();\n\t\tchar ch;\n\t\tfor (int i = 0; i < str.length(); i++) {\n\t\t\tswitch (str.charAt(i)) {\n\t\t\t\tcase 0:\n\t\t\t\t\tcontinue;\n\t\t\t\tcase '\\b':\n\t\t\t\t\tretval.append(\"\\\\b\");\n\t\t\t\t\tcontinue;\n\t\t\t\tcase '\\t':\n\t\t\t\t\tretval.append(\"\\\\t\");\n\t\t\t\t\tcontinue;\n\t\t\t\tcase '\\n':\n\t\t\t\t\tretval.append(\"\\\\n\");\n\t\t\t\t\tcontinue;\n\t\t\t\tcase '\\f':\n\t\t\t\t\tretval.append(\"\\\\f\");\n\t\t\t\t\tcontinue;\n\t\t\t\tcase '\\r':\n\t\t\t\t\tretval.append(\"\\\\r\");\n\t\t\t\t\tcontinue;\n\t\t\t\tcase '\\\"':\n\t\t\t\t\tretval.append(\"\\\\\\\"\");\n\t\t\t\t\tcontinue;\n\t\t\t\tcase '\\'':\n\t\t\t\t\tretval.append(\"\\\\\\'\");\n\t\t\t\t\tcontinue;\n\t\t\t\tcase '\\\\':\n\t\t\t\t\tretval.append(\"\\\\\\\\\");\n\t\t\t\t\tcontinue;\n\t\t\t\tdefault:\n\t\t\t\t\tif ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {\n\t\t\t\t\t\tString s = \"0000\" + Integer.toString(ch, 16);\n\t\t\t\t\t\tretval.append(\"\\\\u\" + s.substring(s.length() - 4, s.length()));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tretval.append(ch);\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\treturn retval.toString();\n\t}\n\n\t/**\n\t * @return the originFilename\n\t */\n\tpublic String getOriginFilename() {\n\t\treturn originFilename;\n\t}\n}", "public class SQFArray extends SQFUnit {\n\tprivate final List<SQFExpression> units = new ArrayList<>();\n\n\tpublic SQFArray(Linter linter) {\n\t\tsuper(linter);\n\t}\n\t\n\tpublic void add(SQFExpression unit) {\n\t\tunits.add(unit);\n\t}\n\n\t/**\n\t * @return the units\n\t */\n\tpublic List<SQFExpression> getItems() {\n\t\treturn units;\n\t}\n\n\t@Override\n\tpublic void analyze(Linter source, SQFBlock context) {\n\t\tfor (SQFExpression unit : units) {\n\t\t\tif (unit != null) {\n\t\t\t\tunit.analyze(source, context);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void revalidate() {\n\t\tfor (SQFUnit unit : units) {\n\t\t\tif (unit != null && unit instanceof SQFExpression) {\n\t\t\t\tSQFExpression exp = (SQFExpression)unit;\n\t\t\t\texp.finish(true);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Array\";\n\t}\t\t\n}", "public class SQFBlock extends SQFUnit {\n\tprivate final List<SQFUnit> statements = new ArrayList<>();\n\tprivate SQFContext innerContext;\n\t\n\tpublic SQFBlock(Linter linter) {\n\t\tsuper(linter);\n\t}\n\t\n\tpublic void add(SQFUnit statement) {\n\t\tstatements.add(statement);\n\t}\n\t\n\tpublic List<SQFUnit> getStatements() {\n\t\treturn statements;\n\t}\n\n\t@Override\n\tpublic void analyze(Linter source, SQFBlock context) {\n\t\tfor (SQFUnit unit : getStatements()) {\n\t\t\tif (unit != null)\n\t\t\t\tunit.analyze(source, this);\n\t\t}\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Code block\";\n\t}\n\n\t@Override\n\tpublic void revalidate() {\n\t\tfor (SQFUnit unit : getStatements()) {\n\t\t\tunit.revalidate();\n\t\t}\n\t}\n\n\t/**\n\t * @return the innerContext\n\t */\n\tpublic SQFContext getInnerContext() {\n\t\treturn innerContext;\n\t}\n\n\t/**\n\t * @param innerContext the innerContext to set\n\t */\n\tpublic void setInnerContext(SQFContext innerContext) {\n\t\tthis.innerContext = innerContext;\n\t}\n}", "public class SQFContext {\n\tprivate final Linter linter;\n\tprivate final SQFContext previous;\n\tprivate boolean newThread;\n\tprivate final List<SQFContext> children = new ArrayList<>();\n\t\n\tprivate final Map<String, SQFVariable> variables = new HashMap<>();\n\t\n\tpublic SQFContext(Linter linter, SQFContext previous, boolean newThread) {\n\t\tthis.linter = linter;\n\t\tthis.previous = previous;\n\t\tthis.newThread = newThread;\n\t\tif (previous != null) {\n\t\t\tprevious.addChild(this);\n\t\t}\n\t}\n\t\n\tpublic void addChild(SQFContext child) {\n\t\tchildren.add(child);\n\t}\n\t\n\t/**\n\t * Loads variable assigned to specified ident.\n\t * If variable isn't registered yet, it will be.\n\t * \n\t * @param ident\n\t * @param name\n\t * @param privateAssigment\n\t * @return\n\t */\n\tpublic SQFVariable getVariable(String ident, String name, boolean privateAssigment) {\n\t\tSQFVariable var;\n\n\t\tif (!variables.containsKey(ident)) {\n\t\t\tif (!privateAssigment &&\n\t\t\t\t\tprevious != null &&\n\t\t\t\t\t(!newThread || !linter.getOptions().isContextSeparationEnabled())\n\t\t\t) {\n\t\t\t\treturn previous.getVariable(ident, name, false);\n\t\t\t} else {\n\t\t\t\tvar = new SQFVariable(name);\n\t\t\t\tvariables.put(ident, var);\n\t\t\t}\n\t\t} else {\n\t\t\tvar = variables.get(ident);\n\t\t}\n\t\t\n\t\treturn var;\n\t}\n\t\n\tpublic SQFParseException handleName(Token name, boolean isAssigment, boolean isPrivate) {\n\t\tSQFVariable var = getVariable(\n\t\t\tname.toString().toLowerCase(),\n\t\t\tname.toString(),\n\t\t\tisAssigment && isPrivate\n\t\t);\n\t\tSQFParseException ex = null;\n\t\t\n\t\tif (var.isLocal() && !isAssigment && var.definitions.isEmpty()) {\n\t\t\tex = linter.addUndefinedMessage(name);\n\t\t}\n\t\t\n\t\tvar.usage.add(name);\n\t\t\n\t\tif (isAssigment) {\n\t\t\tvar.isPrivate = var.isPrivate || isPrivate;\n\t\t\tvar.definitions.add(name);\n\n\t\t\tif (name.specialToken != null) {\n\t\t\t\tvar.comments.add(name.specialToken);\n\t\t\t} else {\n\t\t\t\tvar.comments.add(null);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn ex;\n\t}\n\n\t/**\n\t * @return the previous\n\t */\n\tpublic SQFContext getPrevious() {\n\t\treturn previous;\n\t}\n\n\tpublic Map<String, SQFVariable> getVariables() {\n\t\treturn variables;\n\t}\n\n\tpublic List<SQFContext> getChildren() {\n\t\treturn children;\n\t}\n\n\t/**\n\t * @return the newThread\n\t */\n\tpublic boolean isNewThread() {\n\t\treturn newThread;\n\t}\n\n\t/**\n\t * @param newThread the newThread to set\n\t */\n\tpublic void setNewThread(boolean newThread) {\n\t\tthis.newThread = newThread;\n\t}\n\t\n\tpublic void clear() {\n\t\tvariables.clear();\n\t\tchildren.forEach(c -> c.clear());\n\t}\n}", "public class SQFExpression extends SQFUnit {\n\tstatic int idCounter = 0;\n\tstatic Map<String, SQFExpression> called = new HashMap<>();\n\t\n\tprivate final Token token;\n\tprivate final int id;\n\t\n\tprivate SQFUnit main;\n\tprivate SQFExpression left;\n\tprivate SQFExpression right;\n\t\n\tprivate final List<String> signOperators = Arrays.asList(\"+\", \"-\", \"!\", \"not \");\n\t\n\tprivate SQFParseException sentError;\n\t\n\tpublic SQFExpression(Linter linter, Token token) {\n\t\tsuper(linter);\n\t\tid = idCounter++;\n\t\tthis.token = token;\n\t}\n\t\n\tpublic SQFExpression setMain(SQFUnit expr) {\n\t\tmain = expr;\n\t\treturn this;\n\t}\n\t\n\tpublic SQFExpression setLeft(SQFExpression expr) {\n\t\tleft = expr;\n\t\treturn this;\n\t}\n\t\n\tpublic SQFExpression setRight(SQFExpression expr) {\n\t\tright = expr;\n\t\treturn this;\n\t}\n\n\tpublic SQFExpression finish() {\n\t\treturn finish(false);\n\t}\n\t\n\tpublic SQFExpression finish(boolean revalidate) {\n\t\tif (revalidate) {\n\t\t\tif (getRight() != null) {\n\t\t\t\tgetRight().revalidate();\n\t\t\t}\n\t\t\t\n\t\t\tmain.revalidate();\n\t\t\t\n\t\t\tif (isBlock()) {\n\t\t\t\tgetBlock().revalidate();\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Remove previous error if there is any\n\t\tif (sentError != null) {\n\t\t\tif (sentError instanceof Warning) {\n\t\t\t\tlinter.getWarnings().remove((Warning)sentError);\n\t\t\t} else {\n\t\t\t\tlinter.getErrors().remove(sentError);\n\t\t\t}\n\t\t}\n\t\t\n\t\t// If main part of expression is identifier, try to run command\n\t\tif (main != null && main instanceof SQFIdentifier) {\n\t\t\t// Load main part of this expression\n\t\t\tSQFIdentifier mainIdent = (SQFIdentifier)main;\n\t\t\tString ident = mainIdent.getToken().image.toLowerCase();\n\t\t\t\n\t\t\tif (linter.getOptions().getOperators().containsKey(ident)) {\n\t\t\t\tlinter.getOptions().getOperators().get(ident).analyze(\n\t\t\t\t\tlinter,\n\t\t\t\t\tcontext,\n\t\t\t\t\tthis\n\t\t\t\t);\n\t\t\t} else if (\n\t\t\t\t!linter.getPreprocessor().getMacros().containsKey(ident)\n\t\t\t\t&& !linter.getOptions().isVariableSkipped(ident)\n\t\t\t) {\n\t\t\t\tboolean isPrivate = left != null && left.isPrivate();\n\t\t\t\tboolean isAssigment = right != null && right.isAssignOperator();\n\t\t\t\t\n\t\t\t\tsentError = context.handleName(\n\t\t\t\t\tmainIdent.getToken(),\n\t\t\t\t\tisAssigment,\n\t\t\t\t\tisPrivate\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (!isCommand() && !isOperator()) {\n\t\t\tif (right != null && !right.isOperator() && !right.isCommand()) {\n\t\t\t\tlinter.getErrors().add(new SQFParseException(\n\t\t\t\t\tright.getToken(),\n\t\t\t\t\tmain + \" and \" + right.main + \" is not a valid combination of expressions. Maybe there's missing semicolon?\"\n\t\t\t\t));\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn this;\n\t}\n\n\t/**\n\t * @return contents of expression\n\t */\n\tpublic SQFUnit getMain() {\n\t\tif (main instanceof SQFExpression &&\n\t\t\t((SQFExpression)main).getLeft() == null &&\n\t\t\t((SQFExpression)main).getRight() == null) {\n\t\t\treturn ((SQFExpression)main).getMain();\n\t\t}\n\t\t\n\t\treturn main;\n\t}\n\n\t/**\n\t * @return the left\n\t */\n\tpublic SQFExpression getLeft() {\n\t\treturn left;\n\t}\n\n\t/**\n\t * @return the right\n\t */\n\tpublic SQFExpression getRight() {\n\t\treturn right;\n\t}\n\n\tpublic Token getToken() {\n\t\treturn token;\n\t\t\n\t\t/*\n\t\tif (main != null && main instanceof SQFIdentifier) {\n\t\t\t// Load main part of this expression\n\t\t\tSQFIdentifier token = (SQFIdentifier)main;\n\t\t\treturn token.getToken();\n\t\t}\n\t\treturn null;\n\t\t*/\n\t}\n\t\n\tpublic String getIdentifier() {\n\t\tif (main != null && main instanceof SQFIdentifier) {\n\t\t\t// Load main part of this expression\n\t\t\tSQFIdentifier mainToken = (SQFIdentifier)main;\n\t\t\treturn mainToken.getToken().image.toLowerCase();\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tpublic boolean isCommand() {\n\t\treturn (getIdentifier() != null && linter.getOptions().getOperators().containsKey(getIdentifier()));\n\t}\n\t\n\tpublic boolean isBlock() {\n\t\treturn main != null && main instanceof SQFBlock;\n\t}\n\t\n\tpublic SQFBlock getBlock() {\n\t\tif (isBlock()) {\n\t\t\treturn (SQFBlock)main;\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tpublic boolean isVariable(Linter source) {\n\t\treturn (getIdentifier() != null && !isCommand());\n\t}\n\t\n\tpublic boolean isOperator() {\n\t\treturn main != null && main instanceof SQFOperator;\n\t}\n\t\n\tpublic boolean isSignOperator() {\n\t\treturn isOperator() && signOperators.contains(main.toString());\n\t}\n\t\n\tpublic boolean isPrivate() {\n\t\treturn getIdentifier() != null && getIdentifier().equals(\"private\");\n\t}\n\t\n\tpublic boolean isAssignOperator() {\n\t\treturn isOperator() && main.toString().equals(\"=\");\n\t}\n\n\t@Override\n\tpublic void analyze(Linter source, SQFBlock context) {\n\t\t// Do some analytics on inside (probably won't do anything)\n\t\tif (main != null) {\n\t\t\tmain.analyze(source, context);\n\t\t}\n\t\t\n\t\t// We're going left to right\n\t\tif (right != null) {\n\t\t\tright.analyze(source, context);\n\t\t}\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Expression(\" + main + \", #\" + id + \")\";\n\t}\n\t\n\t@Override\n\tpublic void revalidate() {\n\t\tthis.finish(true);\n\t}\n}", "public class SQFUnit {\n\tprotected final Linter linter;\n\tprotected final SQFContext context;\n\t\n\tpublic SQFUnit(Linter linter) {\n\t\tthis.linter = linter;\n\t\tthis.context = linter.getContext();\n\t}\n\t\n\tpublic void analyze(Linter source, SQFBlock context) {\n\t\t\n\t}\n\t\n\t/**\n\t * @return the context\n\t */\n\tpublic SQFContext getContext() {\n\t\treturn context;\n\t}\n\t\n\tpublic void revalidate() {\n\t\t\n\t}\n}" ]
import cz.zipek.sqflint.linter.Linter; import cz.zipek.sqflint.linter.SQFParseException; import cz.zipek.sqflint.sqf.SQFArray; import cz.zipek.sqflint.sqf.SQFBlock; import cz.zipek.sqflint.sqf.SQFContext; import cz.zipek.sqflint.sqf.SQFExpression; import cz.zipek.sqflint.sqf.SQFUnit;
/* * The MIT License * * Copyright 2016 Jan Zípek (jan at zipek.cz). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package cz.zipek.sqflint.sqf.operators; /** * * @author Jan Zípek (jan at zipek.cz) */ public class ThenOperator extends Operator { @Override
public void analyze(Linter source, SQFContext context, SQFExpression expression) {
0
stuart-warren/logit
src/main/java/com/stuartwarren/logit/jul/Layout.java
[ "public final class ExceptionField extends Field {\n \n private static final ExceptionField FIELD = new ExceptionField();\n \n private ExceptionField() {\n this.setSection(ROOT.EXCEPTION);\n Field.register(this);\n }\n \n public final static void put(final IFieldName key, final String s) {\n FIELD.put0(key, s);\n }\n \n public static Object get(final IFieldName key) {\n return FIELD.get0(key);\n }\n \n public static void clear() {\n FIELD.clear0();\n }\n \n public String toString() {\n final StringBuilder strBuf = new StringBuilder();\n strBuf.append(get(EXCEPTION.CLASS));\n strBuf.append(\": \");\n strBuf.append(get(EXCEPTION.MESSAGE));\n strBuf.append(\"/n\");\n strBuf.append(get(EXCEPTION.STACKTRACE));\n strBuf.append(\"/n\");\n return strBuf.toString();\n }\n \n public static enum EXCEPTION implements IFieldName {\n /**\n * CLASS - exeption_class<br/>\n * Class in which exception occured.\n */\n CLASS(\"exception_class\"),\n /**\n * MESSAGE - exception_message<br/>\n * Message passed as part of exception.\n */\n MESSAGE(\"exception_message\"),\n /**\n * STACKTRACE - stacktrace<br/>\n * Full thrown stacktrace\n */\n STACKTRACE(\"stacktrace\");\n \n private String text;\n \n EXCEPTION(final String text) {\n this.text = text;\n }\n \n public String toString() {\n return this.text;\n }\n \n }\n\n}", "public static enum EXCEPTION implements IFieldName {\n /**\n * CLASS - exeption_class<br/>\n * Class in which exception occured.\n */\n CLASS(\"exception_class\"),\n /**\n * MESSAGE - exception_message<br/>\n * Message passed as part of exception.\n */\n MESSAGE(\"exception_message\"),\n /**\n * STACKTRACE - stacktrace<br/>\n * Full thrown stacktrace\n */\n STACKTRACE(\"stacktrace\");\n \n private String text;\n \n EXCEPTION(final String text) {\n this.text = text;\n }\n \n public String toString() {\n return this.text;\n }\n \n}", "public final class LocationField extends Field {\n \n private static final LocationField FIELD = new LocationField();\n \n private LocationField() {\n this.setSection(ROOT.LOCATION);\n Field.register(this);\n }\n \n public final static void put(final IFieldName key, final String s) {\n FIELD.put0(key, s);\n }\n \n public static Object get(final IFieldName key) {\n return FIELD.get0(key);\n }\n \n public static void clear() {\n FIELD.clear0();\n }\n \n public String toString() {\n final StringBuilder strBuf = new StringBuilder();\n strBuf.append(get(LOCATION.CLASS));\n strBuf.append('.');\n strBuf.append(get(LOCATION.METHOD));\n strBuf.append('(');\n strBuf.append(get(LOCATION.FILE));\n strBuf.append(':');\n strBuf.append(get(LOCATION.LINE));\n strBuf.append(')');\n return strBuf.toString();\n }\n \n public static enum LOCATION implements IFieldName {\n /**\n * FILE - file_name<br/>\n * File name log occured in.\n */\n FILE(\"file_name\"),\n /**\n * CLASS - class_name<br/>\n * Class name log occured in.\n */\n CLASS(\"class_name\"),\n /**\n * METHOD - method_name<br/>\n * Method name log occured in.\n */\n METHOD(\"method_name\"),\n /**\n * LINE - line_number<br/>\n * Line number log occured on.\n */\n LINE(\"line_number\");\n \n private String text;\n \n LOCATION(final String text) {\n this.text = text;\n }\n \n public String toString() {\n return this.text;\n }\n \n }\n\n}", "public static enum LOCATION implements IFieldName {\n /**\n * FILE - file_name<br/>\n * File name log occured in.\n */\n FILE(\"file_name\"),\n /**\n * CLASS - class_name<br/>\n * Class name log occured in.\n */\n CLASS(\"class_name\"),\n /**\n * METHOD - method_name<br/>\n * Method name log occured in.\n */\n METHOD(\"method_name\"),\n /**\n * LINE - line_number<br/>\n * Line number log occured on.\n */\n LINE(\"line_number\");\n \n private String text;\n \n LOCATION(final String text) {\n this.text = text;\n }\n \n public String toString() {\n return this.text;\n }\n \n}", "public interface IFrameworkLayout {\n \n /**\n * @return the layoutType\n */\n public String getLayoutType();\n\n /**\n * @param layoutType the layoutType to set\n */\n public void setLayoutType(String layoutType);\n\n /**\n * @return the detailThreshold\n */\n public String getDetailThreshold();\n\n /**\n * @param detailThreshold the detailThreshold to set\n */\n public void setDetailThreshold(String detailThreshold);\n \n /**\n * @return the fields\n */\n public String getFields();\n\n /**\n * @param fields the fields to set\n */\n public void setFields(String fields);\n\n /**\n * @return the tags\n */\n public String getTags();\n\n /**\n * @param tags the tags to set\n */\n public void setTags(String tags);\n\n\n}", "public class LayoutFactory implements ILayout {\n \n LayoutFactory layout;\n \n public LayoutFactory() {\n }\n \n public LayoutFactory createLayout(String layoutType) {\n this.layout = null;\n if (layoutType.equalsIgnoreCase(\"logstashv1\")) {\n LogitLog.debug(\"Logstashv1 layout in use.\");\n this.layout = new LogstashV1Layout();\n } else if (layoutType.equalsIgnoreCase(\"logstashv0\")) {\n LogitLog.debug(\"Logstashv0 layout in use.\");\n this.layout = new LogstashV0Layout();\n } else {\n LogitLog.debug(\"Default Layout [Logstashv1] in use.\");\n this.layout = new LogstashV1Layout();\n }\n return this.layout;\n }\n\n /* (non-Javadoc)\n * @see com.stuartwarren.logit.layout.ILayout#getLog()\n */\n public Log getLog() {\n return this.layout.getLog();\n }\n\n /* (non-Javadoc)\n * @see com.stuartwarren.logit.layout.ILayout#configure()\n */\n public void configure() {\n this.layout.configure();\n }\n\n /* (non-Javadoc)\n * @see com.stuartwarren.logit.layout.ILayout#format(com.stuartwarren.logit.layout.Log)\n */\n public String format(Log log) {\n String stringLog = this.layout.format(log);\n return stringLog;\n }\n\n}", "public class Log {\n \n private long timestamp;\n private String strTimestamp;\n private String ndc;\n private Map<String, Object> mdc;\n private String level;\n private int levelInt;\n private String loggerName;\n private String threadName;\n private String message;\n private List<String> tags;\n private Map<IFieldName,Object> fields;\n private transient final String user = CachedDetails.INSTANCE.getUsername();\n private transient final String hostname = CachedDetails.INSTANCE.getHostname();\n private transient final String logitVersion = CachedDetails.INSTANCE.getVersion();\n\n /**\n * @return the timestamp\n */\n public long getTimestamp() {\n return timestamp;\n }\n\n /**\n * @param timestamp\n * the timestamp to set\n */\n public Log setTimestamp(long timestamp) {\n this.timestamp = timestamp;\n setStrTimestamp(timestamp);\n return this;\n }\n \n /**\n * @return the strTimestamp\n */\n public String getStrTimestamp() {\n return strTimestamp;\n }\n\n /**\n * Set to ISO8601 format timestamp.\n * Generating timestamp now due to use of {@link System.nanoTime} \n * @param strTimestamp the strTimestamp to set\n */\n private Log setStrTimestamp(long timestamp) {\n Timestamp ts = new Timestamp(timestamp);\n this.strTimestamp = ts.toString();\n return this;\n }\n\n /**\n * @return the ndc\n */\n public String getNdc() {\n return ndc;\n }\n\n /**\n * @param ndc\n * the ndc to set\n */\n public Log setNdc(final String ndc) {\n if (null != ndc) {\n this.ndc = ndc;\n }\n return this;\n }\n\n /**\n * @return the mdc\n */\n public Map<String, Object> getMdc() {\n return mdc;\n }\n\n /**\n * @param properties\n * the mdc to set\n */\n public Log setMdc(final Map<String, Object> properties) {\n this.mdc = properties;\n return this;\n }\n\n /**\n * @return the message\n */\n public String getMessage() {\n return message;\n }\n\n /**\n * @param message\n * the message to set\n */\n public Log setMessage(final String message) {\n if (null != message) {\n this.message = message;\n }\n return this;\n }\n\n /**\n * @return the level\n */\n public String getLevel() {\n return level;\n }\n\n /**\n * @param level\n * the level to set\n */\n public Log setLevel(final String level) {\n if (null != level) {\n this.level = level;\n }\n return this;\n }\n\n /**\n * @return the level_int\n */\n public int getLevelInt() {\n return levelInt;\n }\n\n /**\n * @param levelInt the level_int to set\n */\n public Log setLevelInt(final int levelInt) {\n this.levelInt = levelInt;\n return this;\n }\n\n /**\n * @return the loggerName\n */\n public String getLoggerName() {\n return loggerName;\n }\n\n /**\n * @param loggerName\n * the loggerName to set\n */\n public Log setLoggerName(final String loggerName) {\n if (null != loggerName) {\n this.loggerName = loggerName;\n }\n return this;\n }\n\n /**\n * @return the threadName\n */\n public String getThreadName() {\n return threadName;\n }\n\n /**\n * @param threadName\n * the threadName to set\n */\n public Log setThreadName(final String threadName) {\n if (null != threadName) {\n this.threadName = threadName;\n }\n return this;\n }\n \n /**\n * \n * @return the username\n */\n public String getUsername() {\n return user;\n }\n \n /**\n * \n * @return the hostname\n */\n public String getHostname() {\n return hostname;\n }\n \n /**\n * @return the logitVersion\n */\n public String getLogitVersion() {\n return logitVersion;\n }\n \n /**\n * @return the tags\n */\n public List<String> getTags() {\n return tags;\n }\n \n /**\n * @param tags \n * the tags to set<br/>\n * String split on ,<br/>\n * eg <pre>'tag1,tag2,tag3'</pre><br/>\n */\n public Log setTags(final String tags) {\n // Split string on commas. Ignore whitespace.\n if (null != tags) {\n String[] splitTags = StringUtils.split(tags, \",\");\n for (String tag : splitTags) {\n this.appendTag(tag.trim());\n }\n }\n return this;\n }\n \n /**\n * Append a single tag to the log\n * @param tag \n * the tag to add to the list\n */\n public Log appendTag(final String tag) {\n if (null != tag) {\n if (null == this.tags) {\n this.tags = new ArrayList<String>();\n }\n this.tags.add(tag);\n }\n return this;\n }\n\n /**\n * @return the fields\n */\n public Map<IFieldName,Object> getFields() {\n return fields;\n }\n\n public Log setFields(Map<String, String> fields) {\n if (fields != null) {\n addField(ROOT.CONFIG, fields);\n }\n return this;\n }\n\n /**\n * @param fields the fields to set<br/>\n * List of key:value pairs<br/>\n * String split on : and ,<br/>\n * eg <pre>'field1:value,field2:value'</pre><br/>\n * Added into a config object.<br/>\n * eg <pre>\"config\":{\"field1\":\"value1\"}</pre>\n */\n public static Map<String, String> parseFields(final String fields) {\n final Map<String,String> configFields = new LinkedHashMap<String,String>();\n if (null != fields) {\n for (final String keyValue : StringUtils.split(fields, \",\")) {\n final String[] pairs = StringUtils.split(keyValue.trim(), \":\", 2);\n configFields.put(pairs[0].trim(), pairs.length == 1 ? \"\" : pairs[1].trim());\n }\n\n }\n return configFields;\n }\n \n /**\n * Add all registered fields and their values into the current log<br/>\n * Classes implementing IField should register themselves in their constructor\n */\n public Log addRegisteredFields() {\n \n // add all registered fields to log\n Map<IFieldName,Object> l = Field.list();\n Iterator<Entry<IFieldName, Object>> it = l.entrySet().iterator();\n while (it.hasNext()) {\n Map.Entry<IFieldName,Object> pairs = (Map.Entry<IFieldName,Object>)it.next();\n IFieldName key = (IFieldName) pairs.getKey();\n @SuppressWarnings(\"unchecked\")\n Map<IFieldName,Object> value = (Map<IFieldName,Object>) pairs.getValue();\n this.addField(key, value);\n it.remove(); // avoids a ConcurrentModificationException\n }\n return this;\n }\n\n /**\n * @return a string representation of the current log.\n */\n public String toString() {\n final StringBuffer strBuf = new StringBuffer();\n strBuf.append(getTimestamp());\n strBuf.append(' ');\n strBuf.append(getNdc());\n strBuf.append(' ');\n strBuf.append(getMdc());\n strBuf.append(' ');\n strBuf.append(getMessage());\n strBuf.append(' ');\n strBuf.append(getLevel());\n strBuf.append(' ');\n strBuf.append(getLoggerName());\n strBuf.append(' ');\n strBuf.append(getThreadName());\n strBuf.append(' ');\n strBuf.append(getTags());\n strBuf.append(' ');\n strBuf.append(getFields());\n strBuf.append(' ');\n strBuf.append(getUsername());\n strBuf.append(' ');\n strBuf.append(getHostname());\n return strBuf.toString();\n }\n \n @SuppressWarnings(\"unchecked\")\n private Log addField(final IFieldName key, final Object val) {\n if (null == fields) {\n this.fields = new LinkedHashMap<IFieldName, Object>();\n }\n if (val instanceof HashMap) {\n if (!((LinkedHashMap<String, Object>) val).isEmpty()) {\n if (null != val) {\n fields.put(key,(LinkedHashMap<String, Object>) val);\n }\n }\n } else if (null != val) {\n fields.put(key, val);\n }\n return this;\n }\n\n}", "public final class LogitLog {\n\n /**\n Defining this value makes logit print logit-internal debug\n statements to <code>System.out</code>.\n \n <p> The value of this string is <b>logit.debug</b>.\n \n <p>Note that the search for all option names is case sensitive. \n */\n public static final String DEBUG_KEY=\"logit.debug\";\n public static final String TRACE_KEY=\"logit.trace\";\n private static boolean debugEnabled;\n private static boolean traceEnabled;\n\n /**\n In quietMode not even errors generate any output.\n */\n private static boolean quietMode;\n\n private static final String PREFIX = \"logit: \";\n private static final String TRACE_PREFIX = \"logit:TRACE \";\n private static final String ERR_PREFIX = \"logit:ERROR \";\n private static final String WARN_PREFIX = \"logit:WARN \";\n\n static {\n final String key = OptionConverter.getSystemProperty(DEBUG_KEY, null);\n final String tkey = OptionConverter.getSystemProperty(TRACE_KEY, null);\n if(key != null || tkey != null) { \n debugEnabled = OptionConverter.toBoolean(key, true);\n }\n if(tkey != null) {\n traceEnabled = OptionConverter.toBoolean(tkey, true);\n }\n }\n \n private LogitLog() {\n \n }\n\n /**\n Allows to enable/disable logit internal logging.\n */\n static\n public\n void setInternalDebugging(final boolean enabled) {\n debugEnabled = enabled;\n }\n \n static\n public\n boolean isDebugEnabled() {\n return debugEnabled;\n }\n \n static\n public\n boolean isTraceEnabled() {\n return traceEnabled;\n }\n\n \n /**\n This method is used to output logit internal debug\n statements. Output goes to <code>System.out</code>.\n */\n public\n static\n void trace(final String msg) {\n if(traceEnabled && !quietMode) {\n System.out.println(TRACE_PREFIX+msg);\n }\n }\n \n /**\n This method is used to output logit internal debug\n statements. Output goes to <code>System.out</code>.\n */\n public\n static\n void trace(final String msg, final Throwable t) {\n if(traceEnabled && !quietMode) {\n System.out.println(TRACE_PREFIX+msg);\n if(t != null) {\n t.printStackTrace(System.out);\n }\n }\n }\n /**\n This method is used to output logit internal debug\n statements. Output goes to <code>System.out</code>.\n */\n public\n static\n void debug(final String msg) {\n if(debugEnabled && !quietMode) {\n System.out.println(PREFIX+msg);\n }\n }\n\n /**\n This method is used to output logit internal debug\n statements. Output goes to <code>System.out</code>.\n */\n public\n static\n void debug(final String msg, final Throwable t) {\n if(debugEnabled && !quietMode) {\n System.out.println(PREFIX+msg);\n if(t != null) {\n t.printStackTrace(System.out);\n }\n }\n }\n \n\n /**\n This method is used to output logit internal error\n statements. There is no way to disable error statements.\n Output goes to <code>System.err</code>.\n */\n public\n static\n void error(final String msg) {\n if(quietMode){\n return;\n }\n System.err.println(ERR_PREFIX+msg);\n } \n\n /**\n This method is used to output logit internal error\n statements. There is no way to disable error statements.\n Output goes to <code>System.err</code>. \n */\n public\n static\n void error(final String msg, final Throwable t) {\n if(quietMode) {\n return;\n }\n System.err.println(ERR_PREFIX+msg);\n if(t != null) {\n t.printStackTrace();\n }\n } \n\n /**\n In quite mode LogitLog generates strictly no output, not even\n for errors. \n\n @param quietMode A true for not\n */\n public\n static\n void setQuietMode(final boolean quietMode) {\n LogitLog.quietMode = quietMode;\n }\n\n /**\n This method is used to output logit internal warning\n statements. There is no way to disable warning statements.\n Output goes to <code>System.err</code>. */\n public\n static\n void warn(final String msg) {\n if(quietMode) {\n return;\n }\n System.err.println(WARN_PREFIX+msg);\n } \n\n /**\n This method is used to output logit internal warnings. There is\n no way to disable warning statements. Output goes to\n <code>System.err</code>. */\n public\n static\n void warn(final String msg, final Throwable t) {\n if(quietMode) {\n return;\n }\n System.err.println(WARN_PREFIX+msg);\n if(t != null) {\n t.printStackTrace();\n }\n } \n}" ]
import com.stuartwarren.logit.fields.ExceptionField; import com.stuartwarren.logit.fields.ExceptionField.EXCEPTION; import com.stuartwarren.logit.fields.LocationField; import com.stuartwarren.logit.fields.LocationField.LOCATION; import com.stuartwarren.logit.layout.IFrameworkLayout; import com.stuartwarren.logit.layout.LayoutFactory; import com.stuartwarren.logit.layout.Log; import com.stuartwarren.logit.utils.LogitLog; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Formatter; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.LogRecord;
/** * */ package com.stuartwarren.logit.jul; /** * @author Stuart Warren * @date 6 Oct 2013 * */ public class Layout extends Formatter implements IFrameworkLayout { private transient final String prefix = Layout.class.getName(); private transient final LogManager manager = LogManager.getLogManager(); private String layoutType = "log"; private String detailThreshold = Level.WARNING.toString(); private String fields; private Map<String, String> parsedFields; private String tags; private transient final LayoutFactory layoutFactory = new LayoutFactory(); private transient final LayoutFactory layout; private transient boolean getLocationInfo = false; public Layout() { super(); LogitLog.debug("Jul layout in use."); configure(); this.layout = layoutFactory.createLayout(this.layoutType); } /** * */ private void configure() { setLayoutType(manager.getProperty(prefix + ".layoutType")); setDetailThreshold(manager.getProperty(prefix + ".detailThreshold")); setFields(manager.getProperty(prefix + ".fields")); setTags(manager.getProperty(prefix + ".tags")); } /* (non-Javadoc) * @see java.util.logging.Formatter#format(java.util.logging.LogRecord) */ @Override public String format(final LogRecord record) {
final Log log = doFormat(record);
6
EthanCo/Halo-Turbo
sample/src/main/java/com/ethanco/sample/MulticastClientActivity.java
[ "public class Halo extends AbstractHalo {\n private ISocket haloImpl;\n\n public Halo() {\n this(new Builder());\n }\n\n public Halo(Builder builder) {\n this.haloImpl = SocketFactory.create(builder);\n }\n\n @Override\n public boolean start() {\n return this.haloImpl.start();\n }\n\n @Override\n public void stop() {\n if (haloImpl != null) {\n haloImpl.stop();\n }\n }\n\n @Override\n public List<IHandler> getHandlers() {\n return this.haloImpl.getHandlers();\n }\n\n @Override\n public void addHandler(IHandler handler) {\n this.haloImpl.addHandler(handler);\n }\n\n @Override\n public boolean removeHandler(IHandler handler) {\n return this.haloImpl.removeHandler(handler);\n }\n\n @Override\n public boolean isRunning() {\n return haloImpl.isRunning();\n }\n\n public static class Builder extends Config {\n\n public Builder() {\n this.mode = Mode.MINA_NIO_TCP_CLIENT;\n this.targetIP = \"192.168.1.1\";\n this.targetPort = 19600;\n //this.sourceIP = \"192.168.1.1\";\n this.sourcePort = 19700;\n this.bufferSize = 1024;\n this.handlers = new ArrayList<>();\n this.convertors = new ArrayList<>();\n //需要的自行进行初始化\n //this.threadPool = Executors.newCachedThreadPool();\n }\n\n public Builder setMode(Mode mode) {\n this.mode = mode;\n return this;\n }\n\n public Builder setTargetIP(String targetIP) {\n this.targetIP = targetIP;\n return this;\n }\n\n public Builder setTargetPort(int targetPort) {\n this.targetPort = targetPort;\n return this;\n }\n\n /*public Builder setSourceIP(String sourceIP) {\n this.sourceIP = sourceIP;\n return this;\n }*/\n\n public Builder setSourcePort(int sourcePort) {\n this.sourcePort = sourcePort;\n return this;\n }\n\n public Builder setBufferSize(int bufferSize) {\n this.bufferSize = bufferSize;\n return this;\n }\n\n public Builder setThreadPool(ExecutorService threadPool) {\n this.threadPool = threadPool;\n return this;\n }\n\n public Builder addHandler(IHandler handler) {\n if (!this.handlers.contains(handler)) {\n this.handlers.add(handler);\n }\n return this;\n }\n\n //添加转换器\n public Builder addConvert(IConvertor convertor) {\n if (!convertors.contains(convertor)) {\n this.convertors.add(convertor);\n }\n return this;\n }\n\n //这是自定义的转换器列表\n public Builder setConverts(List<IConvertor> convertors) {\n this.convertors = convertors;\n return this;\n }\n\n //设置ProtocolCodecFactory,现仅对Mina有效\n public Builder setCodec(Object codec) {\n this.codec = codec;\n return this;\n }\n\n public Builder setContext(Context context) {\n this.context = context;\n return this;\n }\n\n //设置心跳\n public Builder setKeepAlive(KeepAlive keepAlive) {\n this.keepAlive = keepAlive;\n return this;\n }\n\n public Halo build() {\n return new Halo(this);\n }\n }\n}", "public abstract class IHandlerAdapter implements IHandler {\n\n @Override\n public void sessionCreated(ISession session) {\n\n }\n\n @Override\n public void sessionOpened(ISession session) {\n\n }\n\n @Override\n public void sessionClosed(ISession session) {\n\n }\n\n @Override\n public void messageReceived(ISession session, Object message) {\n\n }\n\n @Override\n public void messageSent(ISession session, Object message) {\n\n }\n}", "public interface ISession {\n void write(Object message);\n\n void close();\n}", "public class HexLogHandler extends BaseLogHandler {\n\n public HexLogHandler() {\n }\n\n public HexLogHandler(String tag) {\n super(tag);\n }\n\n @Override\n protected String convertToString(Object message) {\n if (message == null) {\n return \"message is null\";\n }\n\n String receive;\n if (message instanceof byte[] || message instanceof Byte[]) {\n receive = HexUtil.bytesToHexString((byte[]) message);\n } else if (message instanceof String) {\n receive = (String) message;\n } else {\n receive = message.toString();\n }\n return receive.trim();\n }\n}", "public enum Mode {\n MINA_NIO_TCP_CLIENT,\n MINA_NIO_TCP_SERVER,\n MINA_NIO_UDP_CLIENT,\n MINA_NIO_UDP_SERVER,\n MULTICAST,\n UDP_CLIENT,\n}", "public class ObjectJsonByteConvertor extends ObjectJsonConvertor {\n @Override\n public Object sentConvert(Object message) {\n Object result = super.sentConvert(message);\n if (result instanceof String) {\n return ((String) result).getBytes();\n }\n return result;\n }\n}" ]
import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Toast; import com.ethanco.halo.turbo.Halo; import com.ethanco.halo.turbo.ads.IHandlerAdapter; import com.ethanco.halo.turbo.ads.ISession; import com.ethanco.halo.turbo.impl.handler.HexLogHandler; import com.ethanco.halo.turbo.type.Mode; import com.ethanco.json.convertor.convert.ObjectJsonByteConvertor; import com.ethanco.sample.databinding.ActivityMulticastClientBinding; import java.util.concurrent.Executors;
package com.ethanco.sample; public class MulticastClientActivity extends AppCompatActivity { private static final String TAG = "Z-Client"; private ActivityMulticastClientBinding binding; private ScrollBottomTextWatcher watcher; private Halo halo; private ISession session; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = DataBindingUtil.setContentView(this, R.layout.activity_multicast_client); halo = new Halo.Builder() .setMode(Mode.MULTICAST) .setSourcePort(19601) .setTargetPort(19602) .setTargetIP("224.0.0.1") .setBufferSize(512) .addHandler(new HexLogHandler(TAG)) //.addHandler(new StringLogHandler(TAG)) .addHandler(new DemoHandler())
.addConvert(new ObjectJsonByteConvertor())
5
popo1379/popomusic
app/src/main/java/com/popomusic/presenter/JKPresenter.java
[ "public class MyApplication extends Application {\n public static DaoSession mDaoSession;\n public static DaoSession searchDaoSession;\n public static DaoSession videoDaoSession;\n public static Context mContext;\n\n // private static RefWatcher mRefWatcher;\n @Override\n public void onCreate() {\n super.onCreate();\n this.mContext = this.getApplicationContext();\n initGreenDao();\n initdown();\n }\n //初始化数据库\n private void initGreenDao() {\n DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this,\"music_db\",null);\n Database db = helper.getWritableDb();\n mDaoSession = new DaoMaster(db).newSession();\n\n DaoMaster.DevOpenHelper helper1=new DaoMaster.DevOpenHelper(this,\"search_db\",null);\n Database db1 = helper.getWritableDb();\n searchDaoSession=new DaoMaster(db1).newSession();\n\n DaoMaster.DevOpenHelper Videohelper=new DaoMaster.DevOpenHelper(this,\"video_db\",null);\n Database videodb = helper.getWritableDb();\n videoDaoSession=new DaoMaster(videodb).newSession();\n\n }\n\n public static DaoSession getDaoSession(){\n return mDaoSession;\n }\n\n public static DaoSession getDaoSession1(){\n return searchDaoSession;\n }\n\n public static DaoSession getVideoDaoSession(){return videoDaoSession;}\n\n //初始化FileDownloader\n private void initdown(){FileDownloader.init(mContext);}\n}", "public class JKActivity extends BaseActivity implements JKMusicData.View,SwipeRefreshLayout.OnRefreshListener{\n\n private static final String TAG = JKActivity.class.getName();\n private RecyclerView recyclerView;\n private JKPresenter mPresenter;\n private LocalMusicAdapter mAdapter;\n private Messenger mServiceMessenger;\n Messenger mMessengerClient;\n private MyHandler myHandler;\n private LinearLayoutManager mLayoutManager;\n private SwipeRefreshLayout srfLayout;\n private List<MusicBean> mList;\n public int currentTime;//实时当前进度\n public int duration;//歌曲的总进度\n @BindView(R.id.play_pause)ImageView mBtnPlay;\n @BindView(R.id.title)TextView title;\n @BindView(R.id.artist)TextView artist;\n @BindView(R.id.nowplayingcard)ImageView playcard;\n @BindView(R.id.song_progress_normal)ProgressBar progressBar;\n @BindView(R.id.topContainer)RelativeLayout relativeLayout;\n @BindView(R.id.content)LinearLayout linearLayout;\n\n @Override\n public void init(Bundle savedInstanceState) {\n bindService(new Intent(this, MediaPlayerService.class),mServiceConnection,BIND_AUTO_CREATE);\n myHandler = new MyHandler(this);\n mMessengerClient = new Messenger(myHandler);\n }\n\n @Override\n public int setLayoutResourceID() {\n return R.layout.activity_jk;\n }\n @Override\n public void initView() {\n recyclerView=(RecyclerView)findViewById(R.id.recycler_JK);\n mAdapter=new LocalMusicAdapter(this);\n mLayoutManager = new LinearLayoutManager(this);\n recyclerView.setLayoutManager(mLayoutManager);\n recyclerView.setHasFixedSize(true);\n recyclerView.setAdapter(mAdapter);\n LogUtils.d(\"LocalMusicActivity\",\"initView()\");\n srfLayout=(SwipeRefreshLayout)findViewById(R.id.swipe);\n mPresenter=new JKPresenter((JKMusicData.View)this);\n mBtnPlay.setImageResource(R.mipmap.bar_play);\n }\n @Override\n public void initData() {\n srfLayout.setOnRefreshListener(this);\n mList = MyApplication.getDaoSession().getMusicBeanDao().queryBuilder().where(MusicBeanDao.Properties.Type.eq(Constant.MUSIC_KOREA)).list();\n if (null != mList) {\n mAdapter.setList(mList);\n mAdapter.notifyDataSetChanged();\n LogUtils.d(\"LocalMusicActivity\",\"从数据库提取数据\");\n }else\n srfLayout.post(() -> onRefresh());\n }\n\n @Override\n public void setData(List<MusicBean> list){\n Collections.shuffle(list);\n mAdapter.setList(list);\n mAdapter.notifyDataSetChanged();\n }\n @Override\n public void onRefresh() {\n mAdapter.removeAll();\n mPresenter.requestData();\n }\n //刷新开关:开\n @Override\n public void showProgress() {\n if (!srfLayout.isRefreshing()) {\n srfLayout.setRefreshing(true);\n }\n }\n\n //刷新开关:关\n @Override\n public void hideProgress() {\n if (srfLayout.isRefreshing()) {\n srfLayout.setRefreshing(false);\n }\n }\n\n @Override\n public void initListener() {\n\n mAdapter.setOnItemClickListener((view, position) -> playSong(position));\n\n mBtnPlay.setOnClickListener(view -> {\n if (null != mServiceMessenger) {\n Message msgToServicePlay = Message.obtain();\n msgToServicePlay.arg1 = 0x40001;//表示这个暂停是由点击按钮造成的,\n msgToServicePlay.what = Constant.PLAYING_ACTIVITY_PLAY;\n try {\n mServiceMessenger.send(msgToServicePlay);\n } catch (RemoteException e) {\n e.printStackTrace();\n }\n }\n });\n relativeLayout.setOnClickListener(view -> startActivity(new Intent(JKActivity.this,PlayMusicActivity.class)));\n\n }\n\n\n ServiceConnection mServiceConnection = new ServiceConnection() {\n @Override\n public void onServiceConnected(ComponentName componentName, IBinder iBinder) {\n mServiceMessenger = new Messenger(iBinder);\n //连接到服务\n if (null != mServiceMessenger){\n Message msgToService = Message.obtain();\n msgToService.replyTo = mMessengerClient;\n msgToService.what = Constant.JK_MUSIC_ACTIVITY;\n try {\n mServiceMessenger.send(msgToService);\n } catch (RemoteException e) {\n e.printStackTrace();\n }\n }\n }\n\n @Override\n public void onServiceDisconnected(ComponentName componentName) {\n\n }\n };\n /**\n * 播放被点击的歌曲\n * @param position\n */\n private void playSong(int position){\n Intent intent = new Intent(this, PlayMusicActivity.class);\n intent.putExtra(\"position\",position);\n intent.putExtra(\"flag\",Constant.MUSIC_KOREA);\n// LogUtils.e(\"JKActivity\",\"点击网络音乐:\"+mList.get(position).getSongname());\n startActivity(intent);\n }\n\n static class MyHandler extends Handler {\n private WeakReference<JKActivity> weakActivity;\n public MyHandler(JKActivity activity) {\n weakActivity = new WeakReference<JKActivity>(activity);\n }\n\n @Override\n public void handleMessage(Message msgFromService) {\n JKActivity activity = weakActivity.get();\n if (null == activity) return;\n switch (msgFromService.what) {\n case Constant.MEDIA_PLAYER_SERVICE_SONG_PLAYING://通过Bundle传递对象,显示正在播放的歌曲\n LogUtils.e(TAG, \"收到消息了\");\n Bundle bundle = msgFromService.getData();\n activity.mAdapter.showPlaying((MusicBean) bundle.getSerializable(Constant.MEDIA_PLAYER_SERVICE_MODEL_PLAYING));\n activity.mAdapter.notifyDataSetChanged();\n MusicBean musicBean = (MusicBean) bundle.getSerializable(Constant.MEDIA_PLAYER_SERVICE_MODEL_PLAYING);\n activity.title.setText(musicBean.getSongname());\n activity.artist.setText(musicBean.getSingername());\n Glide.with(activity).load(musicBean.getAlbumpic_big()).into(activity.playcard);\n break;\n case Constant.MEDIA_PLAYER_SERVICE_IS_PLAYING:\n LogUtils.d(TAG, \"收到了来自service的信息:是否更新UI\");\n if (1 == msgFromService.arg1) {//正在播放\n LogUtils.d(TAG, \"play按钮触发\");\n activity.mBtnPlay.setImageResource(R.mipmap.bar_puase);\n\n } else {\n LogUtils.d(TAG, \"pause按钮触发\");\n activity.mBtnPlay.setImageResource(R.mipmap.bar_play);\n }\n\n break;\n case Constant.MEDIA_PLAYER_SERVICE_PROGRESS:\n // LogUtils.d(\"LocalMusicActivity\", \"进度条开始工作\");\n activity.currentTime = msgFromService.arg1;\n activity.duration = msgFromService.arg2;\n if (0 == activity.duration) break;\n activity.progressBar.setProgress(activity.currentTime * 100 / activity.duration);\n break;\n }\n\n super.handleMessage(msgFromService);\n }\n\n }\n @Override\n protected void onDestroy() {\n unbindService(mServiceConnection);\n if (null != myHandler){\n myHandler.removeCallbacksAndMessages(null);\n myHandler = null;\n }\n super.onDestroy();\n// MyApplication.getRefWatcher().watch(this);\n }\n\n\n}", "public class ApiManager {\n private static final int READ_TIME_OUT = 3;\n\n private static final int CONNECT_TIME_OUT = 3;\n\n private QQMusicApi mQQMusicApiService;\n\n //构造函数私有化,只创建一个实例\n private ApiManager(){\n HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(message -> showRetrofitLog(message)).setLevel(HttpLoggingInterceptor.Level.BODY);//打印请求日志\n OkHttpClient okHttpClient = new OkHttpClient.Builder()\n .readTimeout(READ_TIME_OUT, TimeUnit.SECONDS)\n .connectTimeout(CONNECT_TIME_OUT,TimeUnit.SECONDS)\n .addInterceptor(loggingInterceptor)\n .build();\n Retrofit retrofit1 = new Retrofit.Builder()\n\n .client(okHttpClient)\n .addConverterFactory(GsonConverterFactory.create())\n .addCallAdapterFactory(RxJava2CallAdapterFactory.create())\n .baseUrl(Constant.QQ_MUSIC_BASE_URL)\n .build();\n mQQMusicApiService = retrofit1.create(QQMusicApi.class);\n }\n\n\n /**\n * 单例对象持有者\n */\n private static class SingletonHolder{\n private static final ApiManager INSTANCE = new ApiManager();\n }\n\n /**\n * 获取ApiManager单例对象\n */\n public static ApiManager getApiManager(){\n return SingletonHolder.INSTANCE;\n }\n\n /**\n * 打印日志\n * 返回的是json,就打印格式化好了的json,不是json就原样打印\n * @param message\n */\n private void showRetrofitLog(String message){\n if (message.startsWith(\"{\")){\n LogUtils.d(\"Retrofit:\",message);\n }else {\n LogUtils.e(\"Retrofit:\",message);\n }\n }\n\n public QQMusicApi getQQMusicApiService(){\n return mQQMusicApiService;\n }\n}", "public class Constant {\n public static final String NOTIFICATION_INTENT_ACTION = \"notification_intent_action\";\n //PlayingActivity的message.what的属性\n public static final int PLAYING_ACTIVITY_PLAY = 0x10001;\n public static final int PLAYING_ACTIVITY_NEXT = 0x10002;\n public static final int PLAYING_ACTIVITY_SINGLE = 0x10003;\n public static final int PLAYING_ACTIVITY = 0x10004;//初始化PlayingActivity的Messenger对象的标识\n public static final int PLAYING_ACTIVITY_CUSTOM_PROGRESS = 0x10005;//用户拖动进度条时,更新音乐播放器的播放进度\n public static final int PLAYING_ACTIVITY_INIT = 0x10006;//向播放器传递的歌曲集合数据,进行初始化\n public static final int PLAYING_ACTIVITY_PLAYING_POSITION = 0x10007;//播放歌曲的位置\n public static final int PLAYING_ACTIVITY_PLAY_MODE = 0x10008;//播放模式\n public static final String PLAYING_ACTIVITY_DATA_KEY = \"playing_activity_data_key\";//向播放器传递的歌曲集合数据的key\n\n\n\n //下载\n public static final int DOWN_MUSIC=0*10009;\n\n\n //MediaPlayerService的message.what的属性值\n public static final int MEDIA_PLAYER_SERVICE_PROGRESS = 0x20001;\n public static final int MEDIA_PLAYER_SERVICE_SONG_PLAYING = 0x20002;\n public static final int MEDIA_PLAYER_SERVICE_IS_PLAYING = 0x20003;//播放器是否在播放音乐,用于修改PlayingActivity的UI\n public static final int MEDIA_PLAYER_SERVICE_UPDATE_SONG = 0x20004;//通知PalyingActivity跟换专辑图片 歌曲信息等\n public static final String MEDIA_PLAYER_SERVICE_MODEL_PLAYING = \"song_playing\";//服务端正在播放的歌曲\n //LocalMusicActivity\n public static final int LOCAL_MUSIC_ACTIVITY = 0x30001;\n //JKActivity\n public static final int JK_MUSIC_ACTIVITY = 0x50001;\n //RockActivity\n public static final int ROCK_MUSIC_ACTIVITY = 0x60001;\n //VolksliedActivity\n public static final int VOLKSLIED_MUSIC_ACTIVITY = 0x70001;\n //MainActivity\n public static final int MAIN_ACTIVITY = 0x80001;\n //CollectedActivity\n public static final int COLLECTED_ACTIVITY = 0x90001;\n //LockActivity\n public static final int LOCK_ACTIVITY = 0x100001;\n public static final int LOCK_ACTIVITY_PRE = 0x100002;\n public static final int LOCK_ACTIVITY_NEXT = 0x100003;\n public static final int LOCK_ACTIVITY_PLAY = 0x100004;\n //QQMusicApi相关\n public static final String QQ_MUSIC_APP_ID = \"35348\";\n public static final String QQ_MUSIC_SIGN = \"e2849f7d954e42719b8ca65fdc60a883\";\n public static final String QQ_MUSIC_BASE_URL = \"http://route.showapi.com/\";\n //歌曲类型的type\n public static final String MUSIC_WEST = \"3\";//欧美\n public static final String MUSIC_INLAND = \"5\";//内地\n public static final String MUSIC_HONGKANG = \"6\";//港台\n public static final String MUSIC_KOREA = \"5\";//韩国\n public static final String MUSIC_JAPAN = \"17\";//日本\n public static final String MUSIC_VOLKSLIED = \"18\";//民谣\n public static final String MUSIC_ROCK = \"19\";//摇滚\n public static final String MUSIC_SALES = \"23\";//销量\n public static final String MUSIC_HOT = \"26\";//热歌\n public static final String MUSIC_LOCAL = \"27\";//本地音乐\n public static final String MUSIC_SEARCH = \"28\";//搜索到的音乐\n public static final String MUSIC_Like = \"29\";//收藏的音乐\n\n\n //SharedPrefrence键值\n public static final String SP_PLAY_MODE = \"sp_play_mode\";//0表示顺序播放,1表示单曲循环\n\n public static final String MAIN_RANDOM = \"main_random\";\n\n //PlayingActivity左上角显示的类型\n public static final String CATEGOTY = \"categoty\";\n\n //搜索歌曲使用的Bundle的key\n public static final String SEARCH_ACTIVITY_DATA_KEY = \"search_activity_data_key\";\n\n public static final String HEADER_IMG_PATH = \"header_img_path\";\n\n public static final String USER_NAME = \"user_name\";\n\n //锁屏\n public static final String NOTIFY_SCREEN_OFF = \"notify_screen_off\";\n\n public static final String KEY = \"aex02165daudxbmtrsul63c\";\n\n //开眼视频API\n public static final String Video_BASE_URL = \"http://baobab.kaiyanapp.com/api/\";\n\n //易源数据\n\n public static final String Show_BASE_URL = \"http://route.showapi.com/\";\n}", "@Entity\npublic class MusicBean extends BaseBean{\n /**\n * songname : 舍不得 (《漂亮的李慧珍》电视剧插曲)\n * seconds : 148\n * albummid : 001sP1d63Zutvt\n * songid : 200506552\n * singerid : 1099829\n * albumpic_big : http://i.gtimg.cn/music/photo/mid_album_300/v/t/001sP1d63Zutvt.jpg\n * albumpic_small : http://i.gtimg.cn/music/photo/mid_album_90/v/t/001sP1d63Zutvt.jpg\n * downUrl : http://dl.stream.qqmusic.qq.com/200506552.mp3?vkey=B184A6356B726EDAF0F1A645833D6B4FA939EA201C7984D6F00FDD7FF2556C3C703B23688C0E5143E8306E12A6064E612FB4B9DDC36214E5&guid=2718671044\n * url : http://ws.stream.qqmusic.qq.com/200506552.m4a?fromtag=46\n * singername : 迪丽热巴\n * albumid : 1826345\n */\n @Id(autoincrement = true)\n private Long id;\n private String songname;\n private int seconds;\n private String albummid;\n private int songid;\n private int singerid;\n private String albumpic_big;\n private String albumpic_small;\n private String downUrl;\n private String url;\n private String singername;\n private int albumid;\n private int type;//表示歌曲的类型\n private boolean isCollected;\n\n @Generated(hash = 1899243370)\n public MusicBean() {\n }\n\n @Generated(hash = 1740311575)\n public MusicBean(Long id, String songname, int seconds, String albummid, int songid, int singerid, String albumpic_big, String albumpic_small, String downUrl, String url, String singername, int albumid, int type, boolean isCollected) {\n this.id = id;\n this.songname = songname;\n this.seconds = seconds;\n this.albummid = albummid;\n this.songid = songid;\n this.singerid = singerid;\n this.albumpic_big = albumpic_big;\n this.albumpic_small = albumpic_small;\n this.downUrl = downUrl;\n this.url = url;\n this.singername = singername;\n this.albumid = albumid;\n this.type = type;\n this.isCollected = isCollected;\n }\n\n public String getSongname() {\n return songname;\n }\n\n public void setSongname(String songname) {\n this.songname = songname;\n }\n\n public int getSeconds() {\n return seconds;\n }\n\n public void setSeconds(int seconds) {\n this.seconds = seconds;\n }\n\n public String getAlbummid() {\n return albummid;\n }\n\n public void setAlbummid(String albummid) {\n this.albummid = albummid;\n }\n\n public int getSongid() {\n return songid;\n }\n\n public void setSongid(int songid) {\n this.songid = songid;\n }\n\n public int getSingerid() {\n return singerid;\n }\n\n public void setSingerid(int singerid) {\n this.singerid = singerid;\n }\n\n public String getAlbumpic_big() {\n return albumpic_big;\n }\n\n public void setAlbumpic_big(String albumpic_big) {\n this.albumpic_big = albumpic_big;\n }\n\n public String getAlbumpic_small() {\n return albumpic_small;\n }\n\n public void setAlbumpic_small(String albumpic_small) {\n this.albumpic_small = albumpic_small;\n }\n\n public String getDownUrl() {\n return downUrl;\n }\n\n public void setDownUrl(String downUrl) {\n this.downUrl = downUrl;\n }\n\n public String getUrl() {\n return url;\n }\n\n public void setUrl(String url) {\n this.url = url;\n }\n\n public String getSingername() {\n return singername;\n }\n\n public void setSingername(String singername) {\n this.singername = singername;\n }\n\n public int getAlbumid() {\n return albumid;\n }\n\n public void setAlbumid(int albumid) {\n this.albumid = albumid;\n }\n\n public int getType() {\n return type;\n }\n\n public void setType(int type) {\n this.type = type;\n }\n\n public boolean isCollected() {\n return isCollected;\n }\n\n public void setCollected(boolean collected) {\n isCollected = collected;\n }\n\n public boolean getIsCollected() {\n return this.isCollected;\n }\n\n public void setIsCollected(boolean isCollected) {\n this.isCollected = isCollected;\n }\n\n public Long getId() {\n return this.id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n}", "public interface JKMusicData {\n interface View extends BaseView {\n void setData(List<MusicBean> list);\n void hideProgress();\n void showProgress();\n\n }\n\n interface Presenter extends BasePresenter {\n\n }\n}", "@SuppressWarnings(\"ALL\")\npublic class LogUtils {\n\n\n private static final boolean DEBUG = true;\n\n public static void v(String tag, String message) {\n if (DEBUG) {\n Log.v(tag, message);\n }\n }\n\n public static void d(String tag, String message) {\n if (DEBUG) {\n Log.d(tag, message);\n }\n }\n\n public static void i(String tag, String message) {\n if (DEBUG) {\n Log.i(tag, message);\n }\n }\n\n public static void w(String tag, String message) {\n if (DEBUG) {\n Log.w(tag, message);\n }\n }\n\n public static void e(String tag, String message) {\n if (DEBUG) {\n Log.e(tag, message);\n }\n }\n\n}" ]
import android.widget.Toast; import com.popomusic.MyApplication; import com.popomusic.activity.JKActivity; import com.popomusic.api.ApiManager; import com.popomusic.bean.Constant; import com.popomusic.bean.MusicBean; import com.popomusic.data.JKMusicData; import com.popomusic.util.LogUtils; import java.util.List; import io.reactivex.android.schedulers.AndroidSchedulers; import rx.Observable; import rx.schedulers.Schedulers;
package com.popomusic.presenter; /** * Created by dingmouren on 2017/2/7. * 从数据库取数据,就不用这个类了,后期考虑可能分页加载什么的,先不删除了 */ public class JKPresenter implements JKMusicData.Presenter { private static final String TAG = JKPresenter.class.getName(); private JKMusicData.View mView; private JKActivity jkActivity; public JKPresenter(JKMusicData.View view) { this.mView = view; } private List<MusicBean> mList; @Override public void requestData() { ApiManager.getApiManager().getQQMusicApiService() .getQQMusic(Constant.QQ_MUSIC_APP_ID,Constant.QQ_MUSIC_SIGN,Constant.MUSIC_KOREA) .subscribeOn(io.reactivex.schedulers.Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(qqMusicBodyQQMusicResult -> parseData(Constant.MUSIC_KOREA,qqMusicBodyQQMusicResult.getShowapi_res_body().getPagebean().getSonglist()),this:: loadError); } private void loadError(Throwable throwable) { throwable.printStackTrace(); LogUtils.w("JKPresenter","loadError RXjava异常!!"); mView.hideProgress();
Toast.makeText(MyApplication.mContext,"网络异常!",Toast.LENGTH_SHORT).show();
0
DevComPack/setupmaker
src/main/java/com/dcp/sm/gui/pivot/facades/SetFacade.java
[ "public class IOFactory\n{\n //ISO3 language codes\n public static String[] iso3Codes;\n //File type extensions\n public static String[] archiveExt;// = {\"zip\", \"rar\", \"jar\", \"iso\"};\n public static String[] exeExt;// = {\"exe\", \"jar\", \"cmd\", \"sh\", \"bat\"};\n public static String[] setupExt;// = {\"msi\"};\n public static String[] docExt;// = {\"txt\", \"pdf\", \"doc\", \"docx\", \"xml\", \"rtf\", \"odt\", \"xls\", \"xlsx\", \"csv\"};\n public static String[] imgExt;// = {\"bmp\", \"jpg\", \"jpeg\", \"gif\", \"png\", \"ico\"};\n public static String[] webExt;// = {\"html\", \"htm\", \"php\", \"js\", \"asp\", \"aspx\", \"css\"};\n public static String[] soundExt;// = {\"wav\", \"mp3\", \"ogg\", \"wma\"};\n public static String[] vidExt;// = {\"mp4\", \"mpg\", \"mpeg\", \"wmv\", \"avi\", \"mkv\"};\n public static String[] custExt;//User defined custom extensions\n \n /**\n * Returns file type of a file\n * @param f: file\n * @return FILE_TYPE\n */\n public static FILE_TYPE getFileType(File f) {\n if (f.isDirectory()) return FILE_TYPE.Folder;\n \n String NAME = f.getName();\n if (IOFactory.isFileType(NAME, FILE_TYPE.Archive))//Archive\n return FILE_TYPE.Archive;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Executable))//Executable\n return FILE_TYPE.Executable;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Setup))//Setup file\n return FILE_TYPE.Setup;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Document))//Text Document file\n return FILE_TYPE.Document;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Image))//Image file\n return FILE_TYPE.Image;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Web))//Web file\n return FILE_TYPE.Web;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Sound))//Sound file\n return FILE_TYPE.Sound;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Video))//Video file\n return FILE_TYPE.Video;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Custom))//Custom extension\n return FILE_TYPE.Custom;\n else//Simple File\n return FILE_TYPE.File;\n }\n \n /**\n * Tests if a file's extension is of a type\n * (folders and files without extension are automatically valid)\n * @param file_name\n * @param file_type\n * @return boolean: success\n */\n public static boolean isFileType(String file_name, FILE_TYPE file_type) {\n // Accept all (unix) files without extensions\n if (!file_name.contains(\".\"))\n return true;\n \n String[] exts = null;\n switch (file_type) {\n case Archive:\n exts = archiveExt;\n break;\n case Executable:\n exts = exeExt;\n break;\n case Setup:\n exts = setupExt;\n break;\n case Document:\n exts = docExt;\n break;\n case Image:\n exts = imgExt;\n break;\n case Web:\n exts = webExt;\n break;\n case Sound:\n exts = soundExt;\n break;\n case Video:\n exts = vidExt;\n break;\n case Custom:\n exts = custExt;\n break;\n case File:\n return true;\n default:\n break;\n }\n assert exts != null;\n \n for(String S : exts)\n if (file_name.toLowerCase().endsWith(\".\"+S)) {\n return true;\n }\n return false;\n }\n \n \n // Cached icons\n private static final String iconsPath = \"/com/dcp/sm/gui/icons/\";\n public static Image imgFolder;//Folder icon\n public static Image imgFile;//File icon\n public static Image imgZip;//Archive icon\n public static Image imgExe;//Executable icon\n public static Image imgSetup;//Setup icon\n public static Image imgDoc;//Text file icon\n public static Image imgImg;//Image file icon\n public static Image imgWeb;//Web file icon\n public static Image imgSound;//Audio file icon\n public static Image imgVid;//Video file icon\n public static Image imgCust;//Custom filter file icon\n public static Image imgHistory;//History file icon\n public static Image imgClose;//Close file icon\n // Menu icons\n public static Image imgAdd;//Add menu icon\n public static Image imgRight;//Right arrow menu icon\n public static Image imgEdit;//Edit menu icon\n public static Image imgDelete;//Delete menu icon\n public static Image imgImport;//Import menu icon\n public static Image imgCopy;//Copy menu icon\n public static Image imgPaste;//Paste menu icon\n \n //Filters\n public final static Filter<File> imgFilter = new Filter<File>() {\n @Override public boolean include(File file)\n {\n if (file.isDirectory()) return false;\n else if (file.isFile() && IOFactory.isFileType(file.getName(), FILE_TYPE.Image) )\n return false;\n return true;\n }\n };\n public final static Filter<File> docFilter = new Filter<File>() {\n @Override public boolean include(File file)\n {\n if (file.isDirectory()) return false;\n else if (file.isFile() && (IOFactory.isFileType(file.getName(), FILE_TYPE.Document)\n || IOFactory.isFileType(file.getName(), FILE_TYPE.Web)))\n return false;\n return true;\n }\n };\n \n //JSON Files\n public static final String jsonSettings = \"settings.json\";\n //Directories Paths\n public static String resPath;// = \"res\";\n public static String xmlPath;// = resPath+\"/xml\";\n public static String langpackPath;// = resPath+\"/langpacks\";\n public static String batPath;// = resPath+\"/bat\";\n public static String antPath;// = resPath+\"/ant\";\n public static String psPath;// = resPath+\"ps/\";\n public static String libPath;// = \"lib/dcp\";\n public static String targetPath;// = \"target\";\n public static String savePath;// = \"saves\";\n public static String exeTargetDir;// = \"~tmp/\";\n //File Paths\n public static String confFile;// = \"conf.dcp\";\n public static String defDirFile;// = resPath+\"/default-dir.txt\";\n public static String xmlIzpackInstall;// = \"install.xml\";\n public final static String dcpFileExt = \"dcp\";\n //Options\n public static boolean izpackWrite;// = true; \n public static boolean izpackCompile;// = true;\n public static String apikey;// = Admin:Admin\n \n //Jar libraries\n //public static String jarExecutable;// = libPath+\"/dcp-executable.jar\";\n //public static String jarListeners;// = libPath+\"/dcp-listeners.jar\";\n public static String jarResources;// = libPath+\"/dcp-resources.jar\";\n //Ant build files\n public static String xmlIzpackAntBuild;// = antPath+\"/izpack-target.xml\";\n public static String xmlRunAntBuild;// = antPath+\"/run-target.xml\";\n public static String xmlDebugAntBuild;// = antPath+\"/debug-target.xml\";\n //Bat files\n public static String batClean;// = batPath+\"/clean.bat\";\n //izpack spec files\n public static String xmlProcessPanelSpec;// = xmlPath+\"/ProcessPanelSpec.xml\";\n public static String xmlShortcutPanelSpec;// = xmlPath+\"/ShortcutPanelSpec.xml\";\n public static String xmlRegistrySpec;// = xmlPath+\"/RegistrySpec.xml\";\n // chocolatey files\n public static String psChocolateyInstall;// = psPath+\"/ChocolateyInstall.ps1\"\n public static String psChocolateyUninstall;// = psPath+\"/ChocolateyUninstall.ps1\"\n \n public static String saveFile = \"\";//\"save.dcp\";\n public static void setSaveFile(String canonicalPath) {\n if (canonicalPath.length() > 0 && !canonicalPath.endsWith(\".\"+IOFactory.dcpFileExt)) {//add file extension if not given\n canonicalPath = canonicalPath.concat(\".\"+IOFactory.dcpFileExt);\n }\n saveFile = canonicalPath;\n }\n \n /**\n * Load settings from JSON file: settings.json\n * @throws ParseException \n * @throws IOException \n */\n private static boolean loadSettings(String json_file) throws IOException, ParseException {\n JsonSimpleReader json_ext = new JsonSimpleReader(json_file, \"extensions\");\n archiveExt = json_ext.readStringArray(\"archiveExt\");\n exeExt = json_ext.readStringArray(\"exeExt\");\n setupExt = json_ext.readStringArray(\"setupExt\");\n docExt = json_ext.readStringArray(\"docExt\");\n imgExt = json_ext.readStringArray(\"imgExt\");\n webExt = json_ext.readStringArray(\"webExt\");\n soundExt = json_ext.readStringArray(\"soundExt\");\n vidExt = json_ext.readStringArray(\"vidExt\");\n custExt = json_ext.readStringArray(\"custExt\");\n json_ext.close();\n\n JsonSimpleReader json_paths = new JsonSimpleReader(json_file, \"paths\");\n savePath = json_paths.readString(\"savePath\");\n resPath = json_paths.readString(\"resPath\");\n xmlPath = json_paths.readString(\"xmlPath\");\n langpackPath = json_paths.readString(\"langpackPath\");\n batPath = json_paths.readString(\"batPath\");\n antPath = json_paths.readString(\"antPath\");\n psPath = json_paths.readString(\"psPath\");\n libPath = json_paths.readString(\"libPath\");\n targetPath = json_paths.readString(\"targetPath\");\n exeTargetDir = json_paths.readString(\"exeTargetDir\");\n json_paths.close();\n\n JsonSimpleReader json_files = new JsonSimpleReader(json_file, \"files\");\n confFile = json_files.readString(\"confFile\");\n defDirFile = json_files.readString(\"defDirFile\");\n xmlIzpackInstall = json_files.readString(\"xmlIzpackInstall\");\n json_files.close();\n\n JsonSimpleReader json_options = new JsonSimpleReader(json_file, \"options\");\n izpackWrite = (json_options.readString(\"izpackWrite\").equalsIgnoreCase(\"yes\") ||\n json_options.readString(\"izpackWrite\").equalsIgnoreCase(\"true\"));\n izpackCompile = (json_options.readString(\"izpackCompile\").equalsIgnoreCase(\"yes\") ||\n json_options.readString(\"izpackCompile\").equalsIgnoreCase(\"true\"));\n apikey = json_options.readString(\"apikey\");\n json_options.close();\n \n JsonSimpleReader json_codes = new JsonSimpleReader(json_file, \"codes\");\n iso3Codes = json_codes.readStringArray(\"iso3\");\n json_codes.close();\n \n return true;\n }\n \n /**\n * Data load\n */\n public static void init() {\n try {\n \n //Import file extensions from settings.json\n loadSettings(IOFactory.jsonSettings);\n //jarExecutable = libPath+\"/dcp-executable.jar\";\n //jarListeners = libPath+\"/dcp-listeners.jar\";\n jarResources = libPath+\"/dcp-resources.jar\";\n xmlIzpackAntBuild = antPath+\"/izpack-target.xml\";\n xmlRunAntBuild = antPath+\"/run-target.xml\";\n xmlDebugAntBuild = antPath+\"/debug-target.xml\";\n batClean = batPath+\"/clean.bat\";\n xmlProcessPanelSpec = xmlPath+\"/ProcessPanelSpec.xml\";\n xmlShortcutPanelSpec = xmlPath+\"/ShortcutPanelSpec.xml\";\n xmlRegistrySpec = xmlPath+\"/RegistrySpec.xml\";\n psChocolateyInstall = psPath+\"/ChocolateyInstall.ps1\";\n psChocolateyUninstall = psPath+\"/ChocolateyUninstall.ps1\";\n \n //Images Resources\n imgFolder = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"folder.png\"));\n imgFile = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"file.png\"));\n imgZip = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"archive.png\"));\n imgExe = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"executable.png\"));\n imgSetup = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"setup.png\"));\n imgDoc = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"document.png\"));\n imgImg = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"image.png\"));\n imgWeb = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"webfile.png\"));\n imgSound = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"sound.png\"));\n imgVid = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"video.png\"));\n imgCust = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"filter.png\"));\n imgHistory = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"history.png\"));\n imgClose = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"close.png\"));\n imgAdd = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"add.png\"));\n \n imgRight = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"right.png\"));\n imgEdit = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"edit.png\"));\n imgDelete = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"delete.png\"));\n imgImport = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"import.png\"));\n imgCopy = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"copy.png\"));\n imgPaste = Image.load(IOFactory.class.getClass().getResource(iconsPath + \"paste.png\"));\n \n //Make needed directories\n String[] dirs = new String[] {resPath, antPath, batPath, xmlPath, targetPath, savePath};\n for(String dir:dirs) {\n File f = new File(dir);\n if (!f.exists())\n f.mkdir();\n }\n \n } catch (TaskExecutionException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n } catch (ParseException e) {\n e.printStackTrace();\n }\n }\n \n}", "public static enum FILE_TYPE {\n File,\n Folder,\n Archive,\n Executable,\n Setup,\n Document,\n Image,\n Web,\n Sound,\n Video,\n Custom\n}", "public class CastFactory\n{\n //Constants\n private final static String PATH_DELIMITER = \"/\";\n \n \n /**\n * File to Pack cast\n * @param FILE\n * @return Pack\n */\n public static Pack fileToPack(File FILE) {\n String NAME = FILE.getName();//File name\n Image IMG = null;//Icon\n IMG = nameToImage(NAME, FILE.isDirectory());\n Pack P = new Pack(NAME, IMG);//Pack (NAME + IMG)\n P.setFileType(IOFactory.getFileType(FILE));\n P.setSize(FILE.length());//Size\n \n try {//File Path\n P.setPath(FILE.getCanonicalPath());//PATH\n \n } catch (IOException e) {\n e.printStackTrace();\n }\n \n return P;\n }\n \n /**\n * Pivot Image from Pack name\n * @param NAME\n * @param folder\n * @return Image\n */\n public static Image nameToImage(String NAME, boolean folder)\n {\n Image IMG = null;//Icon\n if (folder) {//Folder\n IMG = IOFactory.imgFolder;\n }\n else {//File icon\n if (IOFactory.isFileType(NAME, FILE_TYPE.Archive))\n IMG = IOFactory.imgZip;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Executable))\n IMG = IOFactory.imgExe;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Setup))\n IMG = IOFactory.imgSetup;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Document))\n IMG = IOFactory.imgDoc;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Image))\n IMG = IOFactory.imgImg;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Web))\n IMG = IOFactory.imgWeb;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Sound))\n IMG = IOFactory.imgSound;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Video))\n IMG = IOFactory.imgVid;\n else if (IOFactory.isFileType(NAME, FILE_TYPE.Custom))\n IMG = IOFactory.imgCust;\n else\n IMG = IOFactory.imgFile;//Simple File\n }\n return IMG;\n }\n\n /**\n * String array path to single string delimited by '/'\n * @param PATH\n * @return String Path\n */\n public static String pathToString(String[] PATH) {\n String tmpPath = \"\";\n for(String s:PATH)//Strings concat\n tmpPath = tmpPath + s + PATH_DELIMITER;\n return tmpPath;\n }\n \n /**\n * Tree view Node to String array path from Tree view root\n * @param NODE\n * @return path array of parent groups\n */\n public static String[] nodeToPath(TreeNode NODE) {\n java.util.List<String> backList = new java.util.ArrayList<String>();\n //Return back in hierarchy\n TreeNode Ntmp = NODE;\n do {\n backList.add(Ntmp.getText());\n Ntmp = Ntmp.getParent();\n } while(Ntmp != null);\n //Copy the hierarchy from top to bottom\n String[] PATH = new String[backList.size()];\n int i = 0;\n ListIterator<String> it = backList.listIterator(backList.size());\n while(it.hasPrevious()) {\n PATH[i++] = it.previous();\n }\n \n return PATH;\n }\n \n /**\n * Add Group's children to tree branch recursively\n * @param group\n * @return group's new branch instance\n */\n public static TreeBranch groupToSingleBranch(Group group) {\n TreeBranch TB = new TreeBranch(IOFactory.imgFolder, group.getName());\n TB.setUserData(group);//Save model data\n return TB;\n }\n private static void recursivAdd(Group group, TreeBranch TARGET_TB) {\n for(Group G:group.getChildren()) {\n TreeBranch TB = groupToSingleBranch(G);\n TARGET_TB.add(TB);\n recursivAdd(G, TB);//-@\n }\n }\n /**\n * Group model to new TreeBranch tree view component\n * @param group\n * @return group's new branch instance with childs\n */\n public static TreeBranch groupToBranch(Group group) {\n TreeBranch TB = groupToSingleBranch(group);\n recursivAdd(group, TB);//Add its childs\n return TB;\n }\n \n /**\n * Pack model to Tree view node\n * @param P\n * @return pack's new node instance\n */\n public static TreeNode packToNode(Pack P) {\n //TreeNode node = new TreeNode(P.getIcon(), P.getInstallName());\n TreeNode node = new TreeNode(P.getIcon(), P.getName());\n node.setUserData(P);//Save model data\n return node;\n }\n \n \n /**\n * Validate path\n * @param target_file\n * @param default_name\n * @param extension\n * @return validated path\n */\n public static String pathValidate(String target_file, String default_name, String extension) {\n //Target file output validating\n if (target_file.equals(\"\"))//If no path entered\n target_file = new File(\"\").getAbsolutePath() + \"/\"+default_name + \".\"+extension;//in working directory\n \n else {//Path entered\n \n //if relative path entered\n if ( (OSValidator.isWindows() && !target_file.substring(1).startsWith(\":\")) ||//Windows starts with '?:'\n (OSValidator.isUnix() && !target_file.startsWith(\"/\")) )//Unix starts with '/'\n target_file = new File(\"\").getAbsolutePath() + \"/\" + target_file;\n //if no extension .jar given in path, add it to last name\n if (!(target_file.endsWith(\".\"+extension.toLowerCase()) ||\n target_file.endsWith(\".\"+extension.toUpperCase()))) {\n \n if (target_file.endsWith(\"/\") || target_file.endsWith(\"\\\\\"))//if ends with directory\n target_file = target_file + default_name + \".\"+extension;\n else//If ends with file name\n target_file = target_file + \".\"+extension;\n \n }\n //If parent path doesn't exist\n if (!new File(new File(target_file).getParent()).exists()) {\n new File(new File(target_file).getParent()).mkdir();//Making the directory\n if (!new File(new File(target_file).getParent()).exists())//If error in creating dir\n target_file = new File(\"\").getAbsolutePath() + \"/\" + default_name;//Working dir\n }\n }\n \n return target_file;\n }\n \n /**\n * Update model data of old Pack\n * @param P: Pack to update\n * @param DCP_VERSION: old DCP version of pack\n */\n public static void packModelUpdate(Pack P, String DCP_VERSION) {\n switch (DCP_VERSION) {// no break for first cases to update properties on cascade\n case \"1.0\":\n P.setInstallVersion(Pack.getVersionFromName(P.getName()));\n case \"1.1\":\n P.setArch(0);\n \n Out.print(LOG_LEVEL.DEBUG, \"Pack data model updated from \"+ DCP_VERSION +\".x to current DCP version\");\n break;\n }\n }\n \n /**\n * Update setup data of old SetupConfigs\n * @param setupConfig: SetupConfig to update\n * @param DCP_VERSION: old DCP version of pack\n */\n public static void setupModelUpdate(SetupConfig setupConfig, String DCP_VERSION) {\n switch (DCP_VERSION) {// no break for first cases to update properties on cascade\n case \"1.0\":\n case \"1.1\":\n setupConfig.setScanMode(SCAN_MODE.SIMPLE_SCAN);\n setupConfig.setScanFolder(SCAN_FOLDER.PACK_FOLDER);\n \n Out.print(LOG_LEVEL.DEBUG, \"Setup data model updated from \"+ DCP_VERSION +\".x to current DCP version\");\n break;\n }\n }\n \n}", "public class GroupFactory\n{\n private static List<Group> groups = new ArrayList<Group>();\n public static List<Group> getGroups() { return groups; }\n \n //Returns Group of PATH\n public static Group get(String[] path) {\n return get(CastFactory.pathToString(path));\n }\n public static Group get(String path) {\n if (path == null) return null;\n for(Group G:groups)\n if (G.getPath().equalsIgnoreCase(path))\n return G;\n return null;\n }\n public static List<Group> getByName(String name) {\n if (name==null) return null;\n List<Group> list = new ArrayList<Group>();\n for(Group G:groups)\n if (G.getName().equalsIgnoreCase(name))\n list.add(G);\n return list;\n }\n \n //Returns index of Group or -1 if not found\n public static int indexOf(Group G) {\n return groups.indexOf(G);\n }\n \n //Add a new group\n public static boolean addGroup(Group group) {\n if (indexOf(group) == -1) {//Group not already created\n groups.add(group);\n if (group.getParent() != null) {//Has parent group\n group.getParent().addChild(group);//Set the parent's child\n }\n Out.print(LOG_LEVEL.DEBUG, \"Group added: \" + group.getName());\n return true;\n }\n else {//Group already present\n return false;\n }\n }\n \n //Remove a group (+sub groups)\n public static void removeGroup(Group group) {\n if (group.getParent() != null) {//If has parent\n Group PARENT = group.getParent();\n PARENT.removeChild(group);//Cascade delete\n }\n for (Group G:group.getChildren())//Childs delete\n groups.remove(G);\n \n String name = group.getName();\n groups.remove(group);\n Out.print(LOG_LEVEL.DEBUG, \"Group deleted with cascade: \" + name);\n }\n \n //Clear all groups\n public static void clear() {\n groups.clear();\n Out.print(LOG_LEVEL.DEBUG, \"All Groups erased.\");\n }\n \n //Returns Group root of G\n public static Group getRoot(Group group) {\n if (group.getParent() != null) {\n Group ROOT = group.getParent();\n while(ROOT.getParent() != null)\n ROOT = ROOT.getParent();\n return ROOT;\n }\n else return group;//Is a root\n }\n \n //Returns the roots\n public static List<Group> getRoots() {\n List<Group> ROOTS = new ArrayList<Group>();\n for(Group G:groups)\n if (G.getParent() == null)\n ROOTS.add(G);\n return ROOTS;\n }\n \n public static boolean hasParent(Group src, Group trgt) {\n assert trgt != null;\n if (src.equals(trgt))\n return true;\n if (src.getParent() != null)\n return hasParent(src.getParent(), trgt);\n return false;\n }\n \n //Returns path from root to Group\n public static String[] getPath(Group group) {\n java.util.List<String> backList = new java.util.ArrayList<String>();\n //Return back in hierarchy\n Group Gtmp = group;\n do {\n backList.add(Gtmp.getName());\n Gtmp = Gtmp.getParent();\n } while(Gtmp != null);\n //Copy the hierarchy from top to bottom\n String[] PATH = new String[backList.size()];\n int i = 0;\n for(ListIterator<String> it = backList.listIterator(backList.size());\n it.hasPrevious();) {\n PATH[i++] = it.previous();\n }\n return PATH;\n }\n\n /**\n * @return groups length\n */\n public static int getCount()\n {\n return groups.getLength();\n }\n \n}", "public class PackFactory\n{\n //Data\n private static List<Pack> packs = new ArrayList<Pack>();//List of packs\n \n //Get all Packs data\n public static List<Pack> getPacks() { return packs; }//Get packs\n \n //Returns the pack of index\n public static Pack get(int index) {\n if (index >= 0 && index < packs.getLength())\n return packs.get(index);\n return null;\n }\n \n /**\n * @param name: filename\n * @return List of Packs of same name (length=0 if none)\n */\n public static List<Pack> getByName(String name) {\n assert name != null;\n if (name==null) return null;\n List<Pack> list = new ArrayList<Pack>();\n for(Pack P:packs)\n if (P.getName().equalsIgnoreCase(name))\n list.add(P);\n return list;\n }\n public static List<Pack> getByGroup(Group group) {\n assert group != null;\n if (group==null) return null;\n List<Pack> list = new ArrayList<Pack>();\n for(Pack P:packs)\n if (P.getGroup() != null && P.getGroup().equals(group))\n list.add(P);\n return list;\n }\n \n //Returns the index of a given Pack, or -1\n public static int indexOf(Pack pack) {\n for(int i = 0; i<packs.getLength(); i++)\n if (packs.get(i).equals(pack))\n return i;\n return -1;\n }\n \n //Add a pack\n public static boolean addPack(Pack pack) {\n packs.add(pack);\n Out.print(LOG_LEVEL.DEBUG, \"Pack added: \" + pack.getName());\n return true;\n }\n \n //Removes a pack\n public static boolean removePack(Pack pack) {\n packs.remove(pack);\n Out.print(LOG_LEVEL.DEBUG, \"Pack deleted: \" + pack.getName());\n return true;\n }\n \n //Clear all packs\n public static boolean clear() {\n packs.clear();\n Out.print(LOG_LEVEL.DEBUG, \"All Packs erased.\");\n return true;\n }\n\n /**\n * @return packs length\n */\n public static int getCount()\n {\n return packs.getLength();\n }\n \n}", "public enum LOG_LEVEL {\n DEBUG(0, \"DEBUG\"),\n INFO(1, \"INFO\"),\n WARN(2, \"WARNING\"),\n ERR(3, \"ERROR\");\n \n private int _level;\n private String _tag;\n private LOG_LEVEL(int level, String tag)\n {\n _level = level;\n _tag = tag;\n }\n @Override\n public String toString()\n {\n return this._tag;\n }\n \n public int value()\n {\n return this._level;\n }\n}", "public class Group implements Comparable<Group>, Serializable\n{\n /**\n * Class written into save file\n */\n private static final long serialVersionUID = 7019635543387148548L;\n \n //Groups\n private String installGroups = \"\";//Install Groups *\n //Attributes\n private String name;//Group name\n private Group parent = null;//Parent group, if any\n private String description = \"\";//Group's description\n //Childs\n private List<Group> children = new ArrayList<Group>();//Childs, if is parent\n public void addChild(Group G) { children.add(G); }//Add child to Group\n public void removeChild(Group G) { children.remove(G); }//Delete Child Cascade\n public List<Group> getChildren() { return children; }//Returns the childs\n \n //Constructors\n public Group() {\n }\n public Group(String name) {\n this.name = name;\n }\n public Group(String name, Group parent) {\n this.name = name;\n setParent(parent);\n }\n public Group(Group group) {\n this.name = group.getName();\n if (group.getParent() != null)\n \tsetParent(group.getParent());\n setDescription(group.getDescription());\n setInstallGroups(group.getInstallGroups());\n }\n \n /**\n * Cast group model from Non-Maven data (<v1.2.1)\n * @param group\n */\n public Group(dcp.logic.model.Group group) {\n assert group != null;\n this.name = group.name;\n if (group.parent != null)\n \tsetParent(new Group(group.parent));\n setDescription(group.description);\n setInstallGroups(group.installGroups);\n\t}\n\t//Getters & Setters\n public String getInstallGroups() { return installGroups; }\n public void setInstallGroups(String installGroups) { this.installGroups = installGroups; }\n \n public String getName() { return name; }\n public void setName(String name) { this.name = name; }\n \n public Group getParent() { return parent; }\n public void setParent(Group PARENT) { this.parent = PARENT; }\n public boolean hasParent(Group PARENT) {\n return GroupFactory.hasParent(this, PARENT);\n }\n \n public String getDescription() { return description; }\n public void setDescription(String description) { this.description = description; }\n \n public String getPath() {\n return CastFactory.pathToString(GroupFactory.getPath(this));\n }\n \n //Comparison function\n @Override\n public boolean equals(Object obj)//Groups compare\n {\n if (obj==null) return false;\n if (obj instanceof Group) {\n Group G = (Group) obj;\n if (G.getParent() != null)\n return this.name.equalsIgnoreCase(G.getName()) && this.getPath().equalsIgnoreCase(G.getPath());\n else//Group has no parent\n return this.name.equalsIgnoreCase(G.getName()) && this.parent == null;\n }\n else if (obj instanceof TreeBranch) {\n TreeBranch branch = (TreeBranch) obj;\n return this.name.equalsIgnoreCase(branch.getText()) &&\n ( (this.getParent() != null && branch.getParent() != null && this.getParent().equals(branch.getParent())) ||\n (this.getParent() == null && branch.getParent() == null) );\n }\n else return false;\n }\n \n @Override\n public String toString()\n {\n return this.getPath();\n }\n @Override\n public int compareTo(Group o)\n {\n if (this.equals(o))\n return 0;//Equal\n else {\n int string_compare = (this.getName().compareTo(o.getName()));//Name comparison\n if (string_compare != 0)\n return string_compare;\n else\n return -1;\n }\n }\n \n}", "public class Pack implements Serializable\n{\n /**\n * Write Pack data to save file\n */\n private static final long serialVersionUID = -8775694196832301518L;\n \n //Relations\n private Group group = null;//Pack member of this group\n private String installGroups = \"\";//Install Groups *\n private Group dependsOnGroup = null;//Group dependency\n private Pack dependsOnPack = null;//Pack dependency\n //Attributes\n private String name = \"\";//File Name\n private FILE_TYPE fileType = FILE_TYPE.File;//File type\n private double size = 0;//File Size in bytes\n private String path = \"\";//File Absolute Path\n private INSTALL_TYPE installType = INSTALL_TYPE.COPY;//Install Type\n private PLATFORM installOs = PLATFORM.ALL;//Install OS\n private int arch = 0;// Platform Architecture (32/64 bits|0 = all)\n private String installPath = \"\";//Install Path, after the $INSTALL_PATH defined\n private String shortcutPath = \"\";//Relative path for shortcut\n //Info\n private int priority = 0;//Pack install priority\n private String installName = \"\";//Pack Install Name\n private String installVersion = \"1.0.0\";//Pack Install Version\n private String description = \"\";//Pack description\n //Booleans\n private boolean silent_install = false;//If Setup install is passive\n private boolean required = false;//Is required\n private boolean selected = true;//Is selected\n private boolean hidden = false;//Is hidden\n private boolean override = true;//If pack will override existing pack\n private boolean shortcut = false;//If pack will have a shortcut created for it\n //Icon\n private String icon = \"\";//Icon file path\n private transient Image imgIcon = null;//Icon Image\n \n //Functions\n public String getBaseName() {//Name without extension\n if (name.contains(\".\"))\n return name.substring(0,name.lastIndexOf(\".\"));\n return name;\n }\n // extract version number from file name<\n public static String getVersionFromName(String name) {\n try {\n if (Pattern.compile(\".*[0-9]+([._\\\\-a-zA-Z][0-9]+)+.*\").matcher(name).find()) {\n String[] borders = name.split(\"[0-9]+([._\\\\-a-zA-Z][0-9]+)+[a-zA-Z]?\");\n if (borders.length > 0)\n return name.substring(borders[0].length(), name.length() - (borders.length > 1?borders[1].length():0));\n else\n return name;\n }\n return \"1.0.0\";\n }\n catch(IllegalStateException e) {\n System.out.println(e);\n return \"1.0.0\";\n }\n }\n \n //Constructors\n public Pack(String NAME, Image ICON) {\n this.name = NAME;\n this.description = name;\n this.installName = name;\n this.installVersion = getVersionFromName(name);\n setIcon(ICON);\n }\n public Pack(Pack pack) {//Copy another Pack data\n name = pack.name;\n priority = pack.priority;\n fileType = pack.fileType;\n installName = pack.installName;\n installVersion = pack.installVersion; // 1.1\n size = pack.size;\n path = pack.path;\n group = pack.group;\n installType = pack.installType;\n if (pack.installOs != null) installOs = pack.installOs;\n arch = pack.arch; // 1.2\n installPath = pack.installPath;\n shortcutPath = pack.shortcutPath;\n installGroups = pack.installGroups;\n description = pack.description;\n if (pack.dependsOnGroup!=null) dependsOnGroup = pack.dependsOnGroup;\n if (pack.dependsOnPack!=null) dependsOnPack = pack.dependsOnPack;\n required = pack.required;\n selected = pack.selected;\n hidden = pack.hidden;\n override = pack.override;\n shortcut = pack.shortcut;\n silent_install = pack.silent_install;\n icon = pack.icon;\n imgIcon = pack.imgIcon;\n }\n \n /**\n * Cast pack model from Non-Maven data (<v1.2.1)\n * @param obj\n */\n public Pack(dcp.logic.model.Pack pack) {\n name = pack.name;\n priority = pack.priority;\n fileType = pack.fileType.cast();\n installName = pack.installName;\n installVersion = pack.installVersion; // 1.1\n size = pack.size;\n path = pack.path;\n if (pack.group != null) group = new Group(pack.group);\n installType = pack.installType.cast();\n if (pack.installOs != null) installOs = pack.installOs.cast();\n arch = pack.arch; // 1.2\n installPath = pack.installPath;\n shortcutPath = pack.shortcutPath;\n installGroups = pack.installGroups;\n description = pack.description;\n if (pack.dependsOnGroup != null) dependsOnGroup = GroupFactory.get(new Group(pack.dependsOnGroup).getPath());\n if (pack.dependsOnPack != null) dependsOnPack = new Pack(pack.dependsOnPack);\n required = pack.required;\n selected = pack.selected;\n hidden = pack.hidden;\n override = pack.override;\n shortcut = pack.shortcut;\n silent_install = pack.silent_install;\n icon = pack.icon;\n setIcon(imgIcon);\n\t}\n \n \n\t//Overrides\n @Override public boolean equals(Object obj)//Packs compare\n {\n if (obj==null) return false;\n if (obj instanceof Pack) {//With a Pack model\n Pack P = (Pack) obj;\n return this.name.toLowerCase().equals(P.getName().toLowerCase())//Name\n && this.path.toLowerCase().equals(P.getPath().toLowerCase());//Path\n }\n else if (obj instanceof TreeNode) {//With a TreeView Node\n TreeNode node = (TreeNode) obj;\n return this.name.toLowerCase().equals(node.getText().toLowerCase())//Name\n && this.group.equals(node.getParent());//Group\n }\n else return super.equals(obj);\n }\n @Override\n public String toString()\n {\n return this.name;\n }\n \n /**\n * Update pack name and path from new file\n * @param new_file\n */\n public void updatePack(File new_file) {\n name = new_file.getName();\n path = new_file.getAbsolutePath();\n }\n \n //Relation functions\n public Group getGroup() { return group; }\n public String getGroupName() {\n if (group != null)\n return group.getName();\n return \"\";\n }\n public String getGroupPath() {\n if (group != null)\n return group.getPath();\n return \"\";\n }\n public void setGroup(Group group) { this.group = group; }\n \n public String getInstallGroups() { return installGroups; }\n public void setInstallGroups(String installGroups) { this.installGroups = installGroups; }\n \n public Group getGroupDependency() { return dependsOnGroup; }\n public void setGroupDependency(Group group) { this.dependsOnGroup = group; this.dependsOnPack = null; }\n public Pack getPackDependency() { return dependsOnPack; }\n public void setPackDependency(Pack pack) { this.dependsOnPack = pack; this.dependsOnGroup = null; }\n \n \n //Getters & Setters\n public String getName() { return name; }\n \n public double getSize() { return size; }\n public void setSize(double size) { this.size = size; }\n\n public String getIconPath() { return icon; }\n public Image getIcon() { return imgIcon; }\n public void setIcon(String ICON)\n {\n this.icon = ICON;\n try {\n setIcon( Image.load(getClass().getResource(icon)) );\n } catch (TaskExecutionException e) {\n e.printStackTrace();\n }\n }\n public void setIcon(Image ICON) { imgIcon = ICON; }\n \n public String getPath() { return path; }\n public void setPath(String path) { this.path = path; }\n \n public String getInstallPath() { return installPath; }\n public void setInstallPath(String installPath) { this.installPath = installPath; }\n \n public String getShortcutPath() { return shortcutPath; }\n public void setShortcutPath(String shortcutPath) {\n if (shortcutPath.length() > 0 && !(shortcutPath.substring(0, 1).equals(\"/\") || shortcutPath.substring(0, 1).equals(\"\\\\\")))\n shortcutPath = \"/\" + shortcutPath;\n this.shortcutPath = shortcutPath;\n }\n \n \n //Info functions\n public String getInstallName() { return installName; }\n public void setInstallName(String installName) { this.installName = installName; }\n\n public String getInstallVersion() { return installVersion; }\n public void setInstallVersion(String installVersion) { this.installVersion = installVersion; }\n \n public String getDescription() { return description; }\n public void setDescription(String description) { this.description = description; }\n \n public INSTALL_TYPE getInstallType() { return installType; }\n public void setInstallType(INSTALL_TYPE IT) { installType = IT; }\n\n public PLATFORM getInstallOs() { return installOs; }\n public void setInstallOs(PLATFORM OS) { installOs = OS; }\n \n public int getArch() { return arch; }\n public void setArch(int arch) {\n assert arch == 0 || arch == 32 || arch == 64;\n this.arch = arch;\n }\n \n public int getPriority() { return priority+1; }\n public void setPriority(int priority) { this.priority = priority; }\n \n \n //Boolean functions\n public FILE_TYPE getFileType() { return fileType; }\n public void setFileType(FILE_TYPE fileType) { this.fileType = fileType; }\n public boolean isSilentInstall() { return this.silent_install; }\n public void setSilentInstall(boolean silent_install) { this.silent_install = silent_install; }\n \n public boolean isRequired() { return required; }\n public void setRequired(boolean required) {\n this.required = required;\n if (required == true && this.getPackDependency() != null) {\n this.getPackDependency().setRequired(true);\n }\n }\n public boolean isSelected() { return selected; }\n public void setSelected(boolean selected) {\n this.selected = selected;\n if (selected == true && this.getPackDependency() != null) {\n this.getPackDependency().setSelected(true);\n }\n }\n public boolean isHidden() { return hidden; }\n public void setHidden(boolean hidden) { this.hidden = hidden; }\n public boolean isOverride() { return override; }\n public void setOverride(boolean override) { this.override = override; }\n public boolean isShortcut() { return shortcut; }\n public void setShortcut(boolean shortcut) { this.shortcut = shortcut; }\n \n}", "public class Out\n{\n //Log\n private static List<String> log = new ArrayList<String>();//Global Log\n public static List<String> getLog() { return log; }\n private static int displayLevel = 1;//logs to display must be >= than this\n \n private static List<String> compileLog = new ArrayList<String>();//Izpack compile Log\n public static List<String> getCompileLog() { return compileLog; }\n \n //Pivot GUI Component Repaint for log update\n private static Component logger = null;\n public static Component getLogger() { return logger; }\n public static void setLogger(Component logger) { Out.logger = logger; }\n \n //Clear the stream cache\n public static void clearCompileLog() {\n compileLog.clear();\n }\n \n //Add a new empty line\n public static void newLine() {\n print(LOG_LEVEL.INFO, \"\");\n }\n \n /**\n * Prints a string to the output stream\n * @param text: log text\n * @param outStream: output stream\n */\n public static void print(String text, PrintStream outStream) {\n outStream.println(text);\n }\n \n /**\n * print text with a tag\n * format: [TAG] TXT\n * @param TAG: tag name\n * @param TXT: text to log\n */\n public static void print(LOG_LEVEL level, String msg) {\n print(\"[\"+level.toString()+\"] \"+msg, System.out);\n log.add(msg);\n final String log_TXT = msg;\n \n if (level.value() >= displayLevel)// display if >= than threshold\n log(log_TXT);\n }\n \n public static void log(final String msg) {\n ApplicationContext.queueCallback(new Runnable() {//Enqueue GUI display repaint\n @Override public void run()\n {\n compileLog.add(msg);\n if (getLogger() != null) getLogger().repaint();//Component update\n }\n });\n }\n \n}" ]
import java.util.TreeMap; import org.apache.pivot.collections.ArrayList; import org.apache.pivot.collections.List; import org.apache.pivot.collections.Sequence; import org.apache.pivot.wtk.content.TreeBranch; import org.apache.pivot.wtk.content.TreeNode; import com.dcp.sm.config.io.IOFactory; import com.dcp.sm.logic.factory.TypeFactory.FILE_TYPE; import com.dcp.sm.logic.factory.CastFactory; import com.dcp.sm.logic.factory.GroupFactory; import com.dcp.sm.logic.factory.PackFactory; import com.dcp.sm.logic.factory.TypeFactory.LOG_LEVEL; import com.dcp.sm.logic.model.Group; import com.dcp.sm.logic.model.Pack; import com.dcp.sm.main.log.Out;
package com.dcp.sm.gui.pivot.facades; public class SetFacade { // DATA private List<TreeBranch> treeData; // Groups UI collection private java.util.Map<Group, TreeBranch> branches; // Treeview Branch mapped to Group private Pack packData;// Pack data copied for pasting to other packs /** * Set Tab Facade Constructor * @param treeData: TreeView data */ public SetFacade(List<TreeBranch> treeData) { this.treeData = treeData; branches = new TreeMap<Group, TreeBranch>(); } /** * Import/Create data from given lists of data (Scan) * @param groups: list of scanned folders/groups (null if import packs only) * @param packs: list of scanned packs * @param groupTarget: if folder target is enabled, set pack install path to groups */ public boolean importDataFrom(List<Group> groups, List<Pack> packs, boolean folderGroup, boolean groupTarget) { //if (packs == null && groups == null) return false; // Groups Import GroupFactory.clear(); treeData.clear(); if (groups != null && folderGroup == true) for(Group G:groups)// Fill Data from Scan folders newGroup(G); // Packs data save for same packs if (packs != null) { List<Pack> newPacks = new ArrayList<Pack>(); Pack pack;// pack data to restore for(Pack p:packs) { List<Pack> oldPacks = PackFactory.getByName(p.getName()); if (oldPacks.getLength() == 1) {// if only one pack with same filename Out.print(LOG_LEVEL.DEBUG, "Pack " + p.getName() + " data restored."); pack = new Pack(oldPacks.get(0)); pack.setGroup(p.getGroup()); } else {// otherwise reset packs pack = new Pack(p); } // remove install path if option disabled from scan if (pack.getInstallPath().length() > 0 && groupTarget == false && pack.getInstallPath().equals(p.getGroupPath())) pack.setInstallPath(""); // set group folder path if enabled from scan else if (groupTarget == true) pack.setInstallPath(p.getGroupPath()); // Group correct if (folderGroup == true) { boolean found = false; for(Group g:GroupFactory.getGroups()) if (g.equals(pack.getGroup())) { found = true; pack.setGroup(g);// group rename bugfix: point to the new created group break; } if (found == false)// bugfix: pack data restore groups no more available pack.setGroup(null); } else pack.setGroup(null); newPacks.add(pack); } // Packs Import PackFactory.clear(); for(Pack p : newPacks) {// Fill Data from Scan files newPack(p); } } else PackFactory.clear(); return true; } ////==================================================================================== /** * Get Pack of a node * @param node to cast * @return Pack */ public Pack getPack(TreeNode node) { for(Pack P : PackFactory.getPacks()) { if (P.getGroup() != null && P.equals(node)) return P; } return null; } /** * Create a new Pack model * @return pack created */ public boolean newPack(Pack pack) { // Data update if (!PackFactory.addPack(pack)) return false; // TreeView update if (pack.getGroup() != null) addNodeToBranch(pack); return true; } /** * Check if name is unique or already given to another pack * @param pack name * @return pack name is unique */ public boolean validatePack(String name) { int i = 0; for(Pack p : PackFactory.getPacks()) { if (p.getInstallName().equals(name)) i++; } if (i > 1) return false; return true; } /** * Delete a pack from memory * @param pack to delete */ public boolean deletePack(Pack pack) { if (pack.getGroup() != null) return false; return PackFactory.removePack(pack); } ////===================================================================================== /** * Get Group of a branch * @param branch to cast * @return Group */ public Group getGroup(TreeBranch branch) { return GroupFactory.get(CastFactory.nodeToPath(branch)); } /** * Add a new group under an existing group or at TreeView root * @param name of new group * @param parent of new group */ public boolean newGroup(String name, String path) { Group parent = GroupFactory.get(path); if (parent != null) { Group group = new Group(name, parent); if (GroupFactory.addGroup(group)) { TreeBranch branch = CastFactory.groupToSingleBranch(group); branches.get(parent).add(branch); branches.put(group, branch); Out.print(LOG_LEVEL.DEBUG, "Group added: " + group.getPath()); return true; } else return false; } else { Group group = new Group(name); if (GroupFactory.addGroup(group)) {
TreeBranch branch = new TreeBranch(IOFactory.imgFolder, name);
0
t28hub/json2java4idea
core/src/test/java/io/t28/json2java/core/JavaConverterTest.java
[ "public class GeneratedAnnotationPolicy implements AnnotationPolicy {\n private final Class<?> klass;\n\n public GeneratedAnnotationPolicy(@Nonnull Class<?> klass) {\n this.klass = klass;\n }\n\n @Override\n public void apply(@Nonnull TypeSpec.Builder builder) {\n builder.addAnnotation(AnnotationSpec.builder(Generated.class)\n .addMember(\"value\", \"$S\", klass.getCanonicalName())\n .build());\n }\n}", "public class SuppressWarningsAnnotationPolicy implements AnnotationPolicy {\n private final String value;\n\n public SuppressWarningsAnnotationPolicy(@Nonnull String value) {\n this.value = value;\n }\n\n @Override\n public void apply(@Nonnull TypeSpec.Builder builder) {\n builder.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class)\n .addMember(\"value\", \"$S\", value)\n .build());\n }\n}", "public class JsonParserImpl implements JsonParser {\n private final ObjectMapper mapper;\n\n public JsonParserImpl() {\n this(new ObjectMapper());\n }\n\n @VisibleForTesting\n JsonParserImpl(@Nonnull ObjectMapper mapper) {\n this.mapper = mapper;\n }\n\n @Nonnull\n @Override\n public JsonValue parse(@Nonnull String json) throws JsonParseException {\n try {\n final Object parsed = mapper.readValue(json, Object.class);\n return JsonValue.wrap(parsed);\n } catch (IOException e) {\n throw new JsonParseException(\"Unable to parse a JSON string(\" + json + \")\", e);\n }\n }\n}", "public enum DefaultNamePolicy implements NamePolicy {\n CLASS {\n @Nonnull\n @Override\n public String convert(@Nonnull String name, @Nonnull TypeName type) {\n return format(name, CaseFormat.UPPER_CAMEL);\n }\n },\n METHOD {\n private static final String BOOLEAN_PREFIX = \"is\";\n private static final String GENERAL_PREFIX = \"get\";\n\n @Nonnull\n @Override\n public String convert(@Nonnull String name, @Nonnull TypeName type) {\n final StringBuilder builder = new StringBuilder();\n if (type.equals(TypeName.BOOLEAN) || type.equals(ClassName.get(Boolean.class))) {\n builder.append(BOOLEAN_PREFIX);\n } else {\n builder.append(GENERAL_PREFIX);\n }\n return builder.append(format(name, CaseFormat.UPPER_CAMEL))\n .toString();\n }\n },\n FIELD {\n @Nonnull\n @Override\n public String convert(@Nonnull String name, @Nonnull TypeName type) {\n return format(name, CaseFormat.LOWER_CAMEL);\n }\n },\n PARAMETER {\n @Nonnull\n @Override\n public String convert(@Nonnull String name, @Nonnull TypeName type) {\n return format(name, CaseFormat.LOWER_CAMEL);\n }\n };\n\n private static final String NO_TEXT = \"\";\n private static final String DELIMITER = \"_\";\n private static final String DELIMITER_REGEX = \"(_|-|\\\\s|\\\\.|:)\";\n private static final String CAMEL_CASE_REGEX = \"(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])\";\n private static final String INVALID_IDENTIFIER_REGEX = \"[^A-Za-z0-9_$]\";\n\n @Nonnull\n @CheckReturnValue\n public static String format(@Nonnull String name, @Nonnull CaseFormat format) {\n final Matcher matcher = Pattern.compile(DELIMITER_REGEX).matcher(name);\n final String pattern;\n if (matcher.find()) {\n pattern = DELIMITER_REGEX;\n } else {\n pattern = CAMEL_CASE_REGEX;\n }\n final String snakeCase = Stream.of(name.split(pattern))\n .map(Ascii::toLowerCase)\n .map(part -> part.replaceAll(INVALID_IDENTIFIER_REGEX, NO_TEXT))\n .filter(part -> !Strings.isNullOrEmpty(part))\n .collect(Collectors.joining(DELIMITER));\n return CaseFormat.LOWER_UNDERSCORE.to(format, snakeCase);\n }\n}", "public class JavaBuilderImpl implements JavaBuilder {\n private static final String INDENT = \" \";\n\n @Nonnull\n @Override\n public String build(@Nonnull String packageName, @Nonnull TypeSpec typeSpec) throws JavaBuildException {\n return JavaFile.builder(packageName, typeSpec)\n .indent(INDENT)\n .skipJavaLangImports(true)\n .build()\n .toString();\n }\n}" ]
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; import com.google.common.io.Files; import io.t28.json2java.core.annotation.GeneratedAnnotationPolicy; import io.t28.json2java.core.annotation.SuppressWarningsAnnotationPolicy; import io.t28.json2java.core.io.JsonParserImpl; import io.t28.json2java.core.naming.DefaultNamePolicy; import io.t28.json2java.core.io.JavaBuilderImpl; import org.junit.Before; import org.junit.Test; import javax.annotation.Nonnull; import java.io.File; import java.nio.charset.StandardCharsets; import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
/* * Copyright (c) 2017 Tatsuya Maki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.t28.json2java.core; public class JavaConverterTest { private static final String JSON_RESOURCE_DIR = "src/test/resources/json"; private static final String JAVA_RESOURCE_DIR = "src/test/resources/java"; private static final String PACKAGE_NAME = "io.t28.test"; private JavaConverter underTest; @Before public void setUp() throws Exception { final Configuration configuration = Configuration.builder() .style(Style.NONE) .classNamePolicy(DefaultNamePolicy.CLASS) .methodNamePolicy(DefaultNamePolicy.METHOD) .fieldNamePolicy(DefaultNamePolicy.FIELD) .parameterNamePolicy(DefaultNamePolicy.PARAMETER) .annotationPolicy(new SuppressWarningsAnnotationPolicy("all"))
.annotationPolicy(new GeneratedAnnotationPolicy(JavaConverter.class))
0
tarzasai/Flucso
src/net/ggelardi/flucso/FeedFragment.java
[ "public class FeedAdapter extends BaseAdapter {\n\n\tprivate Context context;\n\tprivate FFSession session;\n\tprivate OnClickListener listener;\n\tprivate LayoutInflater inflater;\n\t\n\tpublic Feed feed;\n\t\n\tpublic FeedAdapter(Context context, OnClickListener clickListener) {\n\t\tsuper();\n\t\t\n\t\tthis.context = context;\n\t\tsession = FFSession.getInstance(context);\n\t\tlistener = clickListener;\n\t\tinflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n\t}\n\t\n\t@Override\n\tpublic int getCount() {\n\t\treturn feed == null ? 0 : feed.entries.size();\n\t}\n\t\n\t@Override\n\tpublic Entry getItem(int position) {\n\t\treturn feed.entries.get(position);\n\t}\n\t\n\t@Override\n\tpublic long getItemId(int position) {\n\t\treturn position;\n\t}\n\t\n\t@Override\n\tpublic View getView(int position, View convertView, ViewGroup parent) {\n\t\tViewHolder vh;\n\t\tView view = convertView;\n\t\tif (view == null) {\n\t\t\tview = inflater.inflate(R.layout.item_feed_entry, parent, false);\n\t\t\tvh = new ViewHolder();\n\t\t\tvh.lNormal = (LinearLayout) view.findViewById(R.id.l_feed_entry_visible);\n\t\t\tvh.lHidden = (LinearLayout) view.findViewById(R.id.l_feed_entry_hidden);\n\t\t\tvh.txtFromH = (TextView) view.findViewById(R.id.txt_feed_hidden_from);\n\t\t\tvh.txtTimeH = (TextView) view.findViewById(R.id.txt_feed_hidden_time);\n\t\t\tvh.imgFrom = (ImageView) view.findViewById(R.id.img_entry_from);\n\t\t\tvh.imgFrom.setOnClickListener(listener);\n\t\t\tvh.txtFrom = (TextView) view.findViewById(R.id.txt_entry_from);\n\t\t\tvh.txtTo = (TextView) view.findViewById(R.id.txt_entry_to);\n\t\t\tvh.txtTime = (TextView) view.findViewById(R.id.txt_entry_time);\n\t\t\tvh.txtBody = (TextView) view.findViewById(R.id.txt_feed_body);\n\t\t\tvh.imgThumb = (ImageView) view.findViewById(R.id.img_feed_thumb);\n\t\t\tvh.imgThumb.setOnClickListener(listener);\n\t\t\tvh.imgTNext = (ImageView) view.findViewById(R.id.img_feed_tnext);\n\t\t\tvh.imgTNext.setOnClickListener(listener);\n\t\t\tvh.imgTPrev = (ImageView) view.findViewById(R.id.img_feed_tprev);\n\t\t\tvh.imgTPrev.setOnClickListener(listener);\n\t\t\tvh.lComm = (LinearLayout) view.findViewById(R.id.l_feed_lc);\n\t\t\tvh.imgLC = (ImageView) view.findViewById(R.id.img_feed_lc);\n\t\t\tvh.txtLC = (TextView) view.findViewById(R.id.txt_feed_lc);\n\t\t\tvh.txtLikes = (TextView) view.findViewById(R.id.txt_feed_likes);\n\t\t\tvh.txtLikes.setOnClickListener(listener);\n\t\t\tvh.txtFiles = (TextView) view.findViewById(R.id.txt_feed_files);\n\t\t\tvh.txtFiles.setOnClickListener(listener);\n\t\t\tvh.txtFrwd = (TextView) view.findViewById(R.id.txt_feed_fwd);\n\t\t\tvh.txtFrwd.setOnClickListener(listener);\n\t\t\tvh.txtHide = (TextView) view.findViewById(R.id.txt_feed_hide);\n\t\t\tvh.txtHide.setOnClickListener(listener);\n\t\t\tvh.lFoF = (LinearLayout) view.findViewById(R.id.l_feed_fof);\n\t\t\tvh.imgFoF1 = (ImageView) view.findViewById(R.id.img_feed_fof1);\n\t\t\tvh.imgFoF2 = (ImageView) view.findViewById(R.id.img_feed_fof2);\n\t\t\tvh.imgIsDM = (ImageView) view.findViewById(R.id.img_entry_dm);\n\t\t\tvh.imgSpAl = (ImageView) view.findViewById(R.id.img_entry_sa);\n\t\t\tvh.txtComms = (TextView) view.findViewById(R.id.txt_feed_comms);\n\t\t\tview.setTag(vh);\n\t\t} else {\n\t\t\tvh = (ViewHolder) view.getTag();\n\t\t}\n\t\t\n\t\tvh.imgFrom.setTag(Integer.valueOf(position));\n\t\tvh.imgThumb.setTag(Integer.valueOf(position));\n\t\tvh.imgTNext.setTag(Integer.valueOf(position));\n\t\tvh.imgTPrev.setTag(Integer.valueOf(position));\n\t\tvh.txtLikes.setTag(Integer.valueOf(position));\n\t\tvh.txtFiles.setTag(Integer.valueOf(position));\n\t\tvh.txtFrwd.setTag(Integer.valueOf(position));\n\t\tvh.txtHide.setTag(Integer.valueOf(position));\n\t\t\n\t\tString tmp;\n\t\tfinal Entry entry = getItem(position);\n\t\t\n\t\tif (entry.hidden || entry.banned || entry.spoiler) {\n\t\t\tvh.lNormal.setVisibility(View.GONE);\n\t\t\tvh.lHidden.setVisibility(View.VISIBLE);\n\t\t\tvh.txtFromH.setCompoundDrawablesRelativeWithIntrinsicBounds(entry.hidden ? R.drawable.ic_action_desktop :\n\t\t\t\t(entry.spoiler ? R.drawable.ic_action_spoiler_alert : R.drawable.ic_action_phone), 0, 0, 0);\n\t\t\tvh.txtFromH.setText(entry.from.getName());\n\t\t\tvh.txtTimeH.setText(entry.getFuzzyTime());\n\t\t\treturn view;\n\t\t} else {\n\t\t\tvh.lNormal.setVisibility(View.VISIBLE);\n\t\t\tvh.lHidden.setVisibility(View.GONE);\n\t\t}\n\t\t\n\t\tCommons.picasso(context).load(entry.from.getAvatarUrl()).placeholder(\n\t\t\tR.drawable.nomugshot).into(vh.imgFrom);\n\t\t\n\t\tvh.txtFrom.setText(entry.from.getName());\n\t\tvh.txtFrom.setCompoundDrawablesRelativeWithIntrinsicBounds(entry.from.locked ? R.drawable.entry_private : 0, 0, 0, 0);\n\n\t\tvh.imgIsDM.setVisibility(entry.isDM() ? View.VISIBLE : View.GONE);\n\t\tvh.imgSpAl.setVisibility(entry.hasSpoilers() ? View.VISIBLE : View.GONE);\n\t\t\n\t\ttmp = entry.getToLine();\n\t\tif (tmp == null) {\n\t\t\tvh.txtTo.setVisibility(View.GONE);\n\t\t} else {\n\t\t\tvh.txtTo.setText(tmp);\n\t\t\tvh.txtTo.setVisibility(View.VISIBLE);\n\t\t}\n\t\t\n\t\tString tl = entry.getFuzzyTime();\n\t\tif (entry.via != null && !TextUtils.isEmpty(entry.via.name.trim()))\n\t\t\ttl += new StringBuilder().append(\" \").append(context.getString(R.string.source_prefix)).append(\" \").append(\n\t\t\t\tentry.via.name.trim()).toString();\n\t\tvh.txtTime.setText(tl);\n\t\t\n\t\tvh.txtHide.setVisibility(entry.canHide() ? View.VISIBLE : View.GONE);\n\t\tvh.txtBody.setText(Html.fromHtml(entry.body));\n\t\t\n\t\tString img = entry.thumbnails.length > 0 ? entry.thumbnails[entry.thumbpos].url : entry.getFirstImage();\n\t\tif (TextUtils.isEmpty(img))\n\t\t\tvh.imgThumb.setVisibility(View.GONE);\n\t\telse {\n\t\t\tvh.imgThumb.setVisibility(View.VISIBLE);\n\t\t\tif (Commons.YouTube.isVideoUrl(img))\n\t\t\t\timg = Commons.YouTube.getPreview(img);\n\t\t\tCommons.picasso(context).load(img).placeholder(R.drawable.ic_action_picture).into(vh.imgThumb);\n\t\t}\n\t\tvh.imgTNext.setVisibility(entry.thumbnails.length > 1 ? View.VISIBLE : View.GONE);\n\t\tvh.imgTPrev.setVisibility(entry.thumbnails.length > 1 ? View.VISIBLE : View.GONE);\n\t\t\n\t\tif (entry.files.length > 0 || (entry.thumbnails.length + entry.files.length) > 1) {\n\t\t\tvh.txtFiles.setVisibility(View.VISIBLE);\n\t\t\tvh.txtFiles.setText(Integer.toString(entry.thumbnails.length + entry.files.length));\n\t\t} else\n\t\t\tvh.txtFiles.setVisibility(View.GONE);\n\t\t\n\t\tif (!session.getPrefs().getBoolean(PK.FEED_ELC, true) || entry.comments.size() <= 0) {\n\t\t\tvh.lComm.setVisibility(View.GONE);\n\t\t\tvh.lNormal.setBackground(view.getResources().getDrawable(R.drawable.feed_item_box_nc));\n\t\t} else {\n\t\t\tvh.lComm.setVisibility(View.VISIBLE);\n\t\t\tvh.lNormal.setBackground(view.getResources().getDrawable(R.drawable.feed_item_box_lc));\n\t\t\tComment c = entry.comments.get(entry.comments.size() - 1);\n\t\t\tif (c.placeholder)\n\t\t\t\tc = entry.comments.get(entry.comments.size() - 2);\n\t\t\tCommons.picasso(context).load(c.from.getAvatarUrl()).placeholder(R.drawable.nomugshot).into(vh.imgLC);\n\t\t\tvh.txtLC.setText(Html.fromHtml(c.body));\n\t\t}\n\t\t\n\t\tvh.txtLikes.setCompoundDrawablesRelativeWithIntrinsicBounds(entry.canUnlike() ? R.drawable.entry_liked :\n\t\t\tR.drawable.entry_like, 0, 0, 0);\n\t\t\n\t\tint n = entry.getLikesCount();\n\t\tif (n <= 0) {\n\t\t\tvh.txtLikes.setCompoundDrawablePadding(0);\n\t\t\tvh.txtLikes.setText(\"\");\n\t\t} else {\n\t\t\tvh.txtLikes.setCompoundDrawablePadding(14);\n\t\t\tvh.txtLikes.setText(Integer.toString(n));\n\t\t}\n\t\t\n\t\tn = entry.getCommentsCount();\n\t\tif (n <= 0) {\n\t\t\tvh.txtComms.setCompoundDrawablePadding(0);\n\t\t\tvh.txtComms.setText(\"\");\n\t\t} else {\n\t\t\tvh.txtComms.setCompoundDrawablePadding(14);\n\t\t\tvh.txtComms.setText(Integer.toString(n));\n\t\t}\n\t\t\n\t\tString[] fofs = entry.getFofIDs();\n\t\tif (fofs == null) {\n\t\t\tvh.lFoF.setVisibility(View.GONE);\n\t\t\tvh.imgFoF1.setVisibility(View.GONE);\n\t\t\tvh.imgFoF2.setVisibility(View.GONE);\n\t\t} else {\n\t\t\tvh.lFoF.setVisibility(View.VISIBLE);\n\t\t\tvh.imgFoF1.setVisibility(View.VISIBLE);\n\t\t\tCommons.picasso(context).load(\"http://friendfeed-api.com/v2/picture/\" + fofs[0] + \"?size=large\").placeholder(\n\t\t\t\tR.drawable.nomugshot).into(vh.imgFoF1);\n\t\t\tif (fofs.length == 1)\n\t\t\t\tvh.imgFoF2.setVisibility(View.GONE);\n\t\t\telse {\n\t\t\t\tvh.imgFoF2.setVisibility(View.VISIBLE);\n\t\t\t\tCommons.picasso(context).load(\"http://friendfeed-api.com/v2/picture/\" + fofs[1] + \"?size=large\").placeholder(\n\t\t\t\t\tR.drawable.nomugshot).into(vh.imgFoF2);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn view;\n\t}\n\t\n\tpublic static class ViewHolder {\n\t\tpublic LinearLayout lNormal;\n\t\tpublic LinearLayout lHidden;\n\t\tpublic TextView txtFromH;\n\t\tpublic TextView txtTimeH;\n\t\tpublic ImageView imgFrom;\n\t\tpublic TextView txtFrom;\n\t\tpublic TextView txtTo;\n\t\tpublic TextView txtTime;\n\t\tpublic TextView txtHide;\n\t\tpublic TextView txtBody;\n\t\tpublic ImageView imgThumb;\n\t\tpublic ImageView imgTNext;\n\t\tpublic ImageView imgTPrev;\n\t\tpublic LinearLayout lComm;\n\t\tpublic ImageView imgLC;\n\t\tpublic TextView txtLC;\n\t\tpublic TextView txtLikes;\n\t\tpublic TextView txtFiles;\n\t\tpublic TextView txtFrwd;\n\t\tpublic LinearLayout lFoF;\n\t\tpublic ImageView imgFoF1;\n\t\tpublic ImageView imgFoF2;\n\t\tpublic ImageView imgIsDM;\n\t\tpublic ImageView imgSpAl;\n\t\tpublic TextView txtComms;\n\t}\n}", "public class SubscrListAdapter extends BaseAdapter {\n\n\tprivate final BaseFeed target;\n\tprivate final Context context;\n\tprivate final FFSession session;\n\tprivate final List<ListRef> lstsubs;\n\tprivate final LayoutInflater inflater;\n\t\n\tpublic SubscrListAdapter(Context context, BaseFeed target) {\n\t\tsuper();\n\n\t\tthis.target = target;\n\t\tthis.context = context;\n\t\tsession = FFSession.getInstance(context);\n\t\tlstsubs = new ArrayList<ListRef>();\n\t\tinflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n\t\t\n\t\tloadData();\n\t}\n\t\n\t@Override\n\tpublic int getCount() {\n\t\treturn lstsubs.size();\n\t}\n\t\n\t@Override\n\tpublic ListRef getItem(int position) {\n\t\treturn lstsubs.get(position);\n\t}\n\t\n\t@Override\n\tpublic long getItemId(int position) {\n\t\treturn position;\n\t}\n\t\n\t@Override\n\tpublic View getView(int position, View convertView, ViewGroup parent) {\n\t\tViewHolder vh;\n\t\tView view = convertView;\n\t\tif (view == null) {\n\t\t\tview = inflater.inflate(R.layout.item_subscr, parent, false);\n\t\t\tvh = new ViewHolder();\n\t\t\tvh.img = (ImageView) view.findViewById(R.id.img_subscr);\n\t\t\tvh.sw = (Switch) view.findViewById(R.id.sw_subscr);\n\t\t\tvh.sw.setOnCheckedChangeListener(new OnCheckedChangeListener() {\n\t\t\t\t@Override\n\t\t\t\tpublic void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {\n\t\t\t\t\tint pos;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tpos = (Integer) buttonView.getTag();\n\t\t\t\t\t} catch (Exception err) {\n\t\t\t\t\t\treturn; // wtf?\n\t\t\t\t\t}\n\t\t\t\t\tgetItem(pos).toggle(isChecked);\n\t\t\t\t}});\n\t\t\tview.setTag(vh);\n\t\t} else {\n\t\t\tvh = (ViewHolder) view.getTag();\n\t\t}\n\t\tListRef item = getItem(position);\n\t\tCommons.picasso(context).load(\"http://friendfeed-api.com/v2/picture/\" + item.fid + \"?size=large\").placeholder(\n\t\t\tR.drawable.nomugshot).into(vh.img);\n\t\tvh.sw.setTag(Integer.valueOf(position));\n\t\tvh.sw.setText(item.name);\n\t\tvh.sw.setChecked(item.active);\n\t\tvh.sw.setEnabled(!item.checking);\n\t\tvh.sw.setCompoundDrawablesRelativeWithIntrinsicBounds(item.checking ? R.drawable.ic_action_time : 0, 0, 0, 0);\n\t\treturn view;\n\t}\n\t\n\tprivate void loadData() {\n\t\tif (target.isList()) {\n\t\t\tCallback<FeedInfo> callback = new Callback<FeedInfo>() {\n\t\t\t\t@Override\n\t\t\t\tpublic void success(FeedInfo result, Response response) {\n\t\t\t\t\tList<BaseFeed> lst = Arrays.asList(result.feeds);\n\t\t\t\t\tCollections.sort(lst, new Comparator<BaseFeed>() {\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic int compare(BaseFeed lhs, BaseFeed rhs) {\n\t\t\t\t\t\t\treturn lhs.name.compareToIgnoreCase(rhs.name);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tfor (BaseFeed feed: lst)\n\t\t\t\t\t\tlstsubs.add(new ListRef(feed.id, feed.name, true));\n\t\t\t\t\tnotifyDataSetChanged();\n\t\t\t\t}\n\t\t\t\t@Override\n\t\t\t\tpublic void failure(RetrofitError error) {\n\t\t\t\t\tnotifyDataSetChanged();\n\t\t\t\t\tnew AlertDialog.Builder(context).setTitle(R.string.res_rfcall_failed).setMessage(\n\t\t\t\t\t\tCommons.retrofitErrorText(error)).setIcon(android.R.drawable.ic_dialog_alert).create().show();\n\t\t\t\t}\n\t\t\t};\n\t\t\tFFAPI.client_profile(session).get_profile(target.id, callback);\n\t\t} else {\n\t\t\tlstsubs.add(new ListRef(\"home\", \"Home\", false));\n\t\t\tfor (SectionItem s: session.getNavigation().lists)\n\t\t\t\tlstsubs.add(new ListRef(s.id, s.name, false));\n\t\t\tcheckTargetPresence(0, true);\n\t\t}\n\t}\n\n\tprivate void checkTargetPresence(final int position, final boolean next) {\n\t\tif (position > getCount() - 1)\n\t\t\treturn;\n\t\tfinal ListRef item = getItem(position);\n\t\titem.checking = true;\n\t\tCallback<FeedInfo> callback = new Callback<FeedInfo>() {\n\t\t\t@Override\n\t\t\tpublic void success(FeedInfo result, Response response) {\n\t\t\t\titem.active = false;\n\t\t\t\titem.checking = false;\n\t\t\t\tfor (BaseFeed f: result.feeds)\n\t\t\t\t\tif (f.isIt(target.id)) {\n\t\t\t\t\t\titem.active = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\tif (next)\n\t\t\t\t\tcheckTargetPresence(position+1, next);\n\t\t\t\tnotifyDataSetChanged();\n\t\t\t}\n\t\t\t@Override\n\t\t\tpublic void failure(RetrofitError error) {\n\t\t\t\titem.checking = false;\n\t\t\t\tnotifyDataSetChanged();\n\t\t\t\tnew AlertDialog.Builder(context).setTitle(R.string.res_rfcall_failed).setMessage(\n\t\t\t\t\tCommons.retrofitErrorText(error)).setIcon(android.R.drawable.ic_dialog_alert).create().show();\n\t\t\t}\n\t\t};\n\t\tFFAPI.client_profile(session).get_profile(item.fid, callback);\n\t}\n\t\n\tclass ListRef {\n\t\tString fid;\n\t\tString name;\n\t\tboolean active = false;\n\t\tboolean checking = false;\n\t\t\n\t\tpublic ListRef(String fid, String name, boolean active) {\n\t\t\tthis.fid = fid;\n\t\t\tthis.name = name;\n\t\t\tthis.active = active;\n\t\t}\n\t\t\n\t\tpublic void toggle(boolean value) {\n\t\t\tif (checking)\n\t\t\t\treturn;\n\t\t\tchecking = true;\n\t\t\tCallback<SimpleResponse> callback = new Callback<SimpleResponse>() {\n\t\t\t\t@Override\n\t\t\t\tpublic void success(SimpleResponse result, Response response) {\n\t\t\t\t\tLog.v(\"subscr\", result.status);\n\t\t\t\t\tif (result.status.equals(\"subscribed\"))\n\t\t\t\t\t\tactive = true;\n\t\t\t\t\telse if (result.status.equals(\"unsubscribed\"))\n\t\t\t\t\t\tactive = false;\n\t\t\t\t\telse if (result.status != \"\")\n\t\t\t\t\t\tToast.makeText(context, result.status, Toast.LENGTH_SHORT).show();\n\t\t\t\t\telse\n\t\t\t\t\t\tToast.makeText(context, \"Unknown error\", Toast.LENGTH_LONG).show();\n\t\t\t\t\tchecking = false;\n\t\t\t\t\tnotifyDataSetChanged();\n\t\t\t\t}\n\t\t\t\t@Override\n\t\t\t\tpublic void failure(RetrofitError error) {\n\t\t\t\t\tchecking = false;\n\t\t\t\t\tnotifyDataSetChanged();\n\t\t\t\t\tnew AlertDialog.Builder(context).setTitle(R.string.res_rfcall_failed).setMessage(\n\t\t\t\t\t\tCommons.retrofitErrorText(error)).setIcon(android.R.drawable.ic_dialog_alert).create().show();\n\t\t\t\t}\n\t\t\t};\n\t\t\tfinal String feedId = target.isList() ? fid : target.id;\n\t\t\tfinal String listId = target.isList() ? target.id : fid;\n\t\t\tif (value && !active)\n\t\t\t\tFFAPI.client_write(session).subscribe(feedId, listId, callback);\n\t\t\telse if (!value && active)\n\t\t\t\tFFAPI.client_write(session).unsubscribe(feedId, listId, callback);\n\t\t\telse {\n\t\t\t\tchecking = false;\n\t\t\t\tnotifyDataSetChanged();\n\t\t\t}\n\t\t}\n\t}\n\t\n\tstatic class ViewHolder {\n\t\tSwitch sw;\n\t\tImageView img;\n\t}\n}", "public class Commons {\n\t// we better don't tell FF and other sites we are a phone, if we want to receive all images as supposed:\n\tpublic static final String USER_AGENT = \"Mozilla/5.0 (Windows NT 5.1; rv:16.0) Gecko/20100101 Firefox/16.0\";\n\t\n\tpublic static class PK {\n\t\tpublic static final String USERNAME = \"Username\";\n\t\tpublic static final String REMOTEKEY = \"RemoteKey\";\n\t\tpublic static final String STARTUP = \"pk_startup\";\n\t\tpublic static final String LOCALE = \"pk_locale\";\n\t\tpublic static final String PROXY_USED = \"pk_proxy_active\";\n\t\tpublic static final String PROXY_HOST = \"pk_proxy_host\";\n\t\tpublic static final String PROXY_PORT = \"pk_proxy_port\";\n\t\tpublic static final String PROF_INFO = \"pk_prof_info\";\n\t\tpublic static final String PROF_LIST = \"pk_prof_list\";\n\t\tpublic static final String FEED_UPD = \"pk_feed_upd\";\n\t\tpublic static final String FEED_FOF = \"pk_feed_fof\";\n\t\tpublic static final String FEED_HID = \"pk_feed_hid\";\n\t\tpublic static final String FEED_ELC = \"pk_feed_elc\";\n\t\tpublic static final String FEED_HBK = \"pk_feed_hbk\";\n\t\tpublic static final String FEED_HBF = \"pk_feed_hbf\";\n\t\tpublic static final String FEED_SPO = \"pk_feed_spo\";\n\t\tpublic static final String ENTR_IMCO = \"pk_entry_imco\";\n\t\tpublic static final String SERV_PROF = \"pk_serv_prof\";\n\t\tpublic static final String SERV_NOTF = \"pk_serv_notf\";\n\t\tpublic static final String SERV_MSGS = \"pk_serv_msgs\";\n\t\tpublic static final String SERV_MSGS_TIME = \"pk_serv_msgs_time\";\n\t\tpublic static final String SERV_MSGS_CURS = \"pk_serv_msgs_cursor\";\n\t}\n\t\n\tpublic static ArrayList<String> bFeeds = new ArrayList<String>();\n\tpublic static ArrayList<String> bWords = new ArrayList<String>();\n\tpublic static boolean bSpoilers = false;\n\t\n\tpublic static boolean isConnected(Context context) {\n\t\tConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n\t\tNetworkInfo ni = cm.getActiveNetworkInfo();\n\t\treturn ni != null && ni.isConnectedOrConnecting();\n\t}\n\t\n\tpublic static boolean isOnWIFI(Context context) {\n\t\tConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n\t\tNetworkInfo ni = cm.getActiveNetworkInfo();\n\t\treturn ni != null && ni.isConnectedOrConnecting() && ni.getType() == ConnectivityManager.TYPE_WIFI;\n\t}\n\t\n\tpublic static Picasso picasso(Context ctx) {\n\t\t/*\n\t\t * FOR DEBUG ONLY!\n\t\t * \n\t Picasso.Builder builder = new Picasso.Builder(ctx);\n\t builder.downloader(new UrlConnectionDownloader(ctx) {\n\t @Override\n\t protected HttpURLConnection openConnection(Uri uri) throws IOException {\n\t HttpURLConnection connection = super.openConnection(uri);\n\t connection.setRequestProperty(\"User-Agent\", USER_AGENT);\n\t return connection;\n\t }\n\t });\n\t builder.listener(new Picasso.Listener() {\n\t\t\t@Override\n\t\t\tpublic void onImageLoadFailed(Picasso picasso, Uri uri, Exception error) {\n\t\t\t\tLog.v(\"picasso\", error.getLocalizedMessage() + \" -- \" + uri.toString());\n\t\t\t}});\n\t return builder.build();\n\t */\n\t return Picasso.with(ctx);\n\t}\n\t\n\tpublic static long convertTime(long timestamp, String fromTimeZone, String toTimeZone) {\n\t\tCalendar fromCal = new GregorianCalendar(TimeZone.getTimeZone(fromTimeZone));\n\t\tfromCal.setTimeInMillis(timestamp);\n\t\tCalendar toCal = new GregorianCalendar(TimeZone.getTimeZone(toTimeZone));\n\t\ttoCal.setTimeInMillis(fromCal.getTimeInMillis());\n\t\treturn toCal.getTimeInMillis();\n\t}\n\n\tpublic static int retrofitErrorCode(RetrofitError error) {\n\t\tResponse r = error.getResponse();\n\t\tif (r != null)\n\t\t\treturn r.getStatus();\n\t\treturn -1;\n\t}\n\n\tpublic static String retrofitErrorText(RetrofitError error) {\n\t\tString msg;\n\t\tResponse r = error.getResponse();\n\t\tif (r != null) {\n\t\t\t\n\t\t\tif (r.getBody() instanceof TypedByteArray) {\n\t\t\t\tTypedByteArray b = (TypedByteArray) r.getBody();\n\t\t\t\tmsg = new String(b.getBytes());\n\t\t\t} else\n\t\t\t\tmsg = r.getReason();\n\t\t} else\n\t\t\tmsg = error.getLocalizedMessage();\n\t\tif (msg == null && error.getCause() != null) {\n\t\t\tmsg = error.getCause().getLocalizedMessage();\n\t\t\tif (msg == null)\n\t\t\t\tmsg = error.getCause().getClass().getName();\n\t\t}\n\t\tLog.v(\"RPC\", msg);\n\t\tLog.v(\"RPC\", error.getUrl());\n\t\treturn msg;\n\t}\n\t\n\tpublic static String firstUrl(String text) {\n\t\tif (!TextUtils.isEmpty(text))\n\t\t\tfor (String s : text.split(\"\\\\s+\"))\n\t\t\t\tif (Patterns.WEB_URL.matcher(s).matches())\n\t\t\t\t\treturn s;\n\t\treturn null;\n\t}\n\t\n\tpublic static String firstImage(String text) {\n\t\tif (!TextUtils.isEmpty(text)) {\n\t\t\tString chk;\n\t\t\tString[] words = text.split(\"\\\\s+\");\n\t\t\tfor (String s : words)\n\t\t\t\tif (Patterns.WEB_URL.matcher(s).matches()) {\n\t\t\t\t\tif (YouTube.isVideoUrl(s))\n\t\t\t\t\t\treturn YouTube.getPreview(s);\n\t\t\t\t\tchk = s.toLowerCase(Locale.getDefault());\n\t\t\t\t\tif (chk.indexOf(\"/m.friendfeed-media.com/\") > 0 || (chk.endsWith(\".jpg\") || chk.endsWith(\".jpeg\") ||\n\t\t\t\t\t\tchk.endsWith(\".png\") || chk.endsWith(\".gif\")))\n\t\t\t\t\t\treturn s;\n\t\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tpublic static class YouTube {\n\t\t\n\t\tpublic static boolean isVideoUrl(String url) {\n\t\t\treturn url.contains(\"www.youtube.com\") || url.contains(\"://youtu.be/\");\n\t\t}\n\t\t\n\t\tpublic static String getId(String url) {\n\t\t\tif (url.startsWith(\"http://youtu.be/\"))\n\t\t\t\treturn url.substring(16);\n\t\t\tif (url.startsWith(\"https://youtu.be/\"))\n\t\t\t\treturn url.substring(17);\n\t\t\tif (url.contains(\"www.youtube.com/watch\"))\n\t\t\t\treturn Uri.parse(url).getQueryParameter(\"v\");\n\t\t\tif (url.contains(\"www.youtube.com/v/\")) {\n\t\t\t\tString id = Uri.parse(url).getLastPathSegment();\n\t\t\t\treturn id.contains(\"&\") ? id.substring(0, id.indexOf(\"&\")) : id;\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tpublic static String getPreview(String url) {\n\t\t\tString id = getId(url);\n\t\t\tif (id != null)\n\t\t\t\treturn \"http://img.youtube.com/vi/\" + id + \"/0.jpg\";\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tpublic static String getFriendlyUrl(String url) {\n\t\t\treturn !isVideoUrl(url) ? url : \"http://www.youtube.com/watch?v=\" + getId(url);\n\t\t}\n\t}\n}", "public static class PK {\n\tpublic static final String USERNAME = \"Username\";\n\tpublic static final String REMOTEKEY = \"RemoteKey\";\n\tpublic static final String STARTUP = \"pk_startup\";\n\tpublic static final String LOCALE = \"pk_locale\";\n\tpublic static final String PROXY_USED = \"pk_proxy_active\";\n\tpublic static final String PROXY_HOST = \"pk_proxy_host\";\n\tpublic static final String PROXY_PORT = \"pk_proxy_port\";\n\tpublic static final String PROF_INFO = \"pk_prof_info\";\n\tpublic static final String PROF_LIST = \"pk_prof_list\";\n\tpublic static final String FEED_UPD = \"pk_feed_upd\";\n\tpublic static final String FEED_FOF = \"pk_feed_fof\";\n\tpublic static final String FEED_HID = \"pk_feed_hid\";\n\tpublic static final String FEED_ELC = \"pk_feed_elc\";\n\tpublic static final String FEED_HBK = \"pk_feed_hbk\";\n\tpublic static final String FEED_HBF = \"pk_feed_hbf\";\n\tpublic static final String FEED_SPO = \"pk_feed_spo\";\n\tpublic static final String ENTR_IMCO = \"pk_entry_imco\";\n\tpublic static final String SERV_PROF = \"pk_serv_prof\";\n\tpublic static final String SERV_NOTF = \"pk_serv_notf\";\n\tpublic static final String SERV_MSGS = \"pk_serv_msgs\";\n\tpublic static final String SERV_MSGS_TIME = \"pk_serv_msgs_time\";\n\tpublic static final String SERV_MSGS_CURS = \"pk_serv_msgs_cursor\";\n}", "public class FFAPI {\n\tprivate static final String API_URL = \"http://friendfeed-api.com/v2\";\n\tprivate static final String API_KEY = \"c914bd31ea024b9bade1365cefa8b989\";\n\t\n\t// private static final String API_SEC = \"d5d5e78a0ced4a1da49230fe09696353078d9f37b0a841a888e24c064e88212d\";\n\t\n\tpublic interface FF {\n\t\t\n\t\t// async\n\t\t\n\t\t@GET(\"/feedinfo/{feed_id}\")\n\t\tvoid get_profile(@EncodedPath(\"feed_id\") String feed_id, Callback<FeedInfo> callback);\n\t\t\n\t\t@GET(\"/feedlist\")\n\t\tvoid get_navigation(Callback<FeedList> callback);\n\t\t\n\t\t@GET(\"/short/{short_url}\")\n\t\tvoid rev_short(@Path(\"short_url\") String short_url, Callback<Entry> callback);\n\t\t\n\t\t@GET(\"/entry/{entry_id}\")\n\t\tvoid get_entry_async(@EncodedPath(\"entry_id\") String entry_id, Callback<Entry> callback);\n\t\t\n\t\t@POST(\"/short\")\n\t\tvoid get_short(@Query(\"entry\") String entry_id, Callback<Entry> callback);\n\t\t\n\t\t@POST(\"/entry\")\n\t\tvoid ins_entry(@Body MultipartTypedOutput mto, Callback<Entry> callback);\n\t\t\n\t\t@POST(\"/entry/delete\")\n\t\tvoid del_entry(@Query(\"id\") String entry_id, Callback<Entry> callback);\n\t\t\n\t\t@POST(\"/entry/delete\")\n\t\tvoid und_entry(@Query(\"id\") String entry_id, @Query(\"undelete\") int undelete, Callback<Entry> callback);\n\t\t\n\t\t@POST(\"/hide\")\n\t\tvoid set_hidden(@Query(\"entry\") String entry_id, Callback<Entry> callback);\n\t\t\n\t\t@POST(\"/hide\")\n\t\tvoid set_unhide(@Query(\"entry\") String entry_id, @Query(\"unhide\") int unhide, Callback<Entry> callback);\n\t\t\n\t\t@POST(\"/like\")\n\t\tvoid ins_like(@Query(\"entry\") String entry_id, Callback<Like> callback);\n\t\t\n\t\t@POST(\"/like/delete\")\n\t\tvoid del_like(@Query(\"entry\") String entry_id, Callback<SimpleResponse> callback);\n\t\t\n\t\t@POST(\"/comment\")\n\t\tvoid ins_comment(@Query(\"entry\") String entry_id, @Query(\"body\") String body, Callback<Comment> callback);\n\t\t\n\t\t@POST(\"/comment\")\n\t\tvoid upd_comment(@Query(\"entry\") String entry_id, @Query(\"id\") String comm_id, @Query(\"body\") String body,\n\t\t\tCallback<Comment> callback);\n\t\t\n\t\t@POST(\"/comment/delete\")\n\t\tvoid del_comment(@Query(\"id\") String comm_id, Callback<Comment> callback);\n\t\t\n\t\t@POST(\"/comment/delete\")\n\t\tvoid und_comment(@Query(\"id\") String comm_id, @Query(\"undelete\") int undelete, Callback<Comment> callback);\n\t\t\n\t\t@POST(\"/subscribe\")\n\t\tvoid subscribe(@Query(\"feed\") String feed, @Query(\"list\") String list, Callback<SimpleResponse> callback);\n\t\t\n\t\t@POST(\"/unsubscribe\")\n\t\tvoid unsubscribe(@Query(\"feed\") String feed, @Query(\"list\") String list, Callback<SimpleResponse> callback);\n\t\t\n\t\t// sync\n\t\t\n\t\t@GET(\"/feedinfo/{feed_id}\")\n\t\tFeedInfo get_profile_sync(@Path(\"feed_id\") String feed_id);\n\t\t\n\t\t@GET(\"/feedlist\")\n\t\tFeedList get_navigation_sync();\n\t\t\n\t\t@GET(\"/feed/{feed_id}\")\n\t\tFeed get_feed_normal(@EncodedPath(\"feed_id\") String feed_id, @Query(\"start\") int start, @Query(\"num\") int num);\n\t\t\n\t\t@GET(\"/updates/feed/{feed_id}\")\n\t\tFeed get_feed_updates(@EncodedPath(\"feed_id\") String feed_id, @Query(\"num\") int num,\n\t\t\t@Query(\"cursor\") String cursor, @Query(\"timeout\") int timeout, @Query(\"updates\") int updates);\n\t\t\n\t\t@GET(\"/search\")\n\t\tFeed get_search_normal(@Query(\"q\") String query, @Query(\"start\") int start, @Query(\"num\") int num);\n\t\t\n\t\t@GET(\"/updates/search\")\n\t\tFeed get_search_updates(@Query(\"q\") String query, @Query(\"num\") int num, @Query(\"cursor\") String cursor,\n\t\t\t@Query(\"timeout\") int timeout, @Query(\"updates\") int updates);\n\t\t\n\t\t@GET(\"/entry/{entry_id}\")\n\t\tEntry get_entry(@EncodedPath(\"entry_id\") String entry_id);\n\t}\n\t\n\tpublic static class SimpleResponse {\n\t\tpublic boolean success = false; // unlike & unsubscribe?\n\t\tpublic String status = \"\"; // subscribe & unsubscribe?\n\t}\n\t\n\tstatic class IdentItem {\n\t\tpublic static String accountID = \"\";\n\t\tpublic static String accountName = \"You\";\n\t\tpublic static String accountFeed = \"Your feed\";\n\t\t\n\t\tpublic String id = \"\";\n\t\tpublic List<String> commands = new ArrayList<String>();\n\t\tpublic long timestamp = System.currentTimeMillis();\n\t\t\n\t\tpublic long getAge() {\n\t\t\treturn System.currentTimeMillis() - timestamp;\n\t\t}\n\t\t\n\t\tpublic boolean isIt(String checkId) {\n\t\t\treturn id.trim().toLowerCase(Locale.getDefault()).equals(checkId.trim().toLowerCase(Locale.getDefault()));\n\t\t}\n\t}\n\t\n\tpublic static class BaseFeed extends IdentItem {\n\t\tpublic String name;\n\t\tpublic String type = \"\";\n\t\tpublic String description;\n\t\t\n\t\t@SerializedName(\"private\")\n\t\tpublic Boolean locked = false;\n\t\t\n\t\tpublic boolean isMe() {\n\t\t\treturn !TextUtils.isEmpty(accountID) && isIt(accountID);\n\t\t}\n\t\t\n\t\tpublic boolean isHome() {\n\t\t\treturn isIt(\"home\");\n\t\t}\n\t\t\n\t\tpublic boolean isList() {\n\t\t\treturn type.equals(\"special\") && id.startsWith(\"list/\");\n\t\t}\n\t\t\n\t\tpublic boolean isUser() {\n\t\t\treturn type.equals(\"user\");\n\t\t}\n\t\t\n\t\tpublic boolean isGroup() {\n\t\t\treturn type.equals(\"group\");\n\t\t}\n\t\t\n\t\tpublic boolean canPost() {\n\t\t\treturn commands.contains(\"post\");\n\t\t}\n\t\t\n\t\tpublic boolean canDM() {\n\t\t\treturn commands.contains(\"dm\");\n\t\t}\n\t\t\n\t\tpublic boolean canSetSubscriptions() {\n\t\t\treturn isList() || (commands.contains(\"subscribe\") || commands.contains(\"unsubscribe\"));\n\t\t}\n\t\t\n\t\tpublic boolean isSubscribed() {\n\t\t\treturn commands.contains(\"unsubscribe\");\n\t\t}\n\t\t\n\t\tpublic String getName() {\n\t\t\treturn isMe() ? accountName : name.trim();\n\t\t}\n\t\t\n\t\tpublic String getAvatarUrl() {\n\t\t\treturn \"http://friendfeed-api.com/v2/picture/\" + id + \"?size=large\";\n\t\t}\n\t}\n\t\n\tpublic static class Feed extends BaseFeed {\n\t\tpublic List<Entry> entries = new ArrayList<Entry>();\n\t\tpublic Realtime realtime;\n\t\t\n\t\tpublic static String lastDeletedEntry = \"\";\n\t\t\n\t\tpublic int indexOf(String eid) {\n\t\t\tfor (int i = 0; i < entries.size(); i++)\n\t\t\t\tif (entries.get(i).isIt(eid))\n\t\t\t\t\treturn i;\n\t\t\treturn -1;\n\t\t}\n\t\t\n\t\tpublic Entry find(String eid) {\n\t\t\tfor (Entry e : entries)\n\t\t\t\tif (e.id.equals(eid))\n\t\t\t\t\treturn e;\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tpublic int append(Feed feed) {\n\t\t\tint res = 0;\n\t\t\tfor (Entry e : feed.entries)\n\t\t\t\tif (find(e.id) == null) {\n\t\t\t\t\tentries.add(e);\n\t\t\t\t\te.checkLocalHide();\n\t\t\t\t\tres++;\n\t\t\t\t}\n\t\t\treturn res;\n\t\t}\n\t\t\n\t\tpublic int update(Feed feed, boolean sortLikeSite) {\n\t\t\trealtime = feed.realtime;\n\t\t\ttimestamp = feed.timestamp;\n\t\t\tint res = 0;\n\t\t\tfor (Entry e : feed.entries)\n\t\t\t\tif (e.created) {\n\t\t\t\t\tentries.add(0, e);\n\t\t\t\t\te.checkLocalHide();\n\t\t\t\t\tres++;\n\t\t\t\t} else\n\t\t\t\t\tfor (Entry old : entries)\n\t\t\t\t\t\tif (old.isIt(e.id)) {\n\t\t\t\t\t\t\told.update(e);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\tif (!TextUtils.isEmpty(lastDeletedEntry))\n\t\t\t\tfor (int n = 0; n < entries.size(); n++)\n\t\t\t\t\tif (entries.get(n).id.equals(lastDeletedEntry)) {\n\t\t\t\t\t\tentries.remove(n);\n\t\t\t\t\t\tlastDeletedEntry = \"\";\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\tif (sortLikeSite && res > 0) {\n\t\t\t\tCollections.sort(entries, new Comparator<BaseEntry>() {\n\t\t\t\t @Override\n\t\t\t\t public int compare(BaseEntry o1, BaseEntry o2) {\n\t\t\t\t return o1.date.compareTo(o2.date) * -1;\n\t\t\t\t }\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn res;\n\t\t}\n\t\t\n\t\tpublic int update(Feed feed) {\n\t\t\treturn update(feed, false);\n\t\t}\n\t\t\n\t\tpublic void checkLocalHide() {\n\t\t\tfor (Entry e : entries)\n\t\t\t\te.checkLocalHide();\n\t\t}\n\t\t\n\t\tpublic static class Realtime {\n\t\t\tpublic String cursor;\n\t\t\tpublic final long timestamp = System.currentTimeMillis();\n\t\t}\n\t}\n\t\n\tpublic static class BaseEntry extends IdentItem {\n\t\tpublic BaseFeed from;\n\t\tpublic Date date;\n\t\tpublic String body;\n\t\tpublic String rawBody;\n\t\tpublic Origin via;\n\t\tpublic boolean created;\n\t\tpublic boolean updated;\n\t\tpublic boolean banned = false; // local\n\t\tpublic boolean spoiler = false; // local\n\t\t\n\t\tpublic boolean isMine() {\n\t\t\treturn from.isMe();\n\t\t}\n\t\t\n\t\tpublic boolean canEdit() {\n\t\t\treturn commands.contains(\"edit\");\n\t\t}\n\t\t\n\t\tpublic boolean canDelete() {\n\t\t\treturn commands.contains(\"delete\");\n\t\t}\n\t\t\n\t\tpublic String getFuzzyTime() {\n\t\t\treturn DateUtils.getRelativeTimeSpanString(date.getTime(), System.currentTimeMillis(),\n\t\t\t\tDateUtils.MINUTE_IN_MILLIS).toString();\n\t\t}\n\t\t\n\t\tpublic String getFirstUrl() {\n\t\t\tString res = Commons.firstUrl(rawBody);\n\t\t\tif (res == null)\n\t\t\t\tres = Commons.firstUrl(body);\n\t\t\treturn res;\n\t\t}\n\t\t\n\t\tpublic String getFirstImage() {\n\t\t\tString res = Commons.firstImage(rawBody);\n\t\t\tif (res == null)\n\t\t\t\tres = Commons.firstImage(body);\n\t\t\treturn res;\n\t\t}\n\t\t\n\t\tpublic void update(BaseEntry item) {\n\t\t\tif (!isIt(item.id))\n\t\t\t\treturn;\n\t\t\ttimestamp = item.timestamp;\n\t\t\tcommands = item.commands;\n\t\t\tfrom = item.from; // people and rooms can change name/avatar at any time.\n\t\t\tvia = item.via; // barely useless.\n\t\t\tif (item.updated) {\n\t\t\t\tdate = item.date;\n\t\t\t\tbody = item.body;\n\t\t\t\trawBody = item.rawBody;\n\t\t\t\tupdated = true;\n\t\t\t}\n\t\t\tcheckLocalHide();\n\t\t}\n\t\t\n\t\tpublic void checkLocalHide() {\n\t\t\tbanned = false;\n\t\t\tspoiler = false;\n\t\t\ttry {\n\t\t\t\tString chk = !TextUtils.isEmpty(body) ? body.toLowerCase(Locale.getDefault()).trim() : \"\";\n\t\t\t\tchk += !TextUtils.isEmpty(chk) ? \"\\n\\n\\n\" : \"\";\n\t\t\t\tchk += !TextUtils.isEmpty(rawBody) ? rawBody.toLowerCase(Locale.getDefault()).trim() : \"\";\n\t\t\t\tif (!TextUtils.isEmpty(chk)) {\n\t\t\t\t\tif (!isMine())\n\t\t\t\t\t\tfor (String bw: Commons.bWords)\n\t\t\t\t\t\t\tif (chk.indexOf(bw) >= 0) {\n\t\t\t\t\t\t\t\tbanned = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\tspoiler = Commons.bSpoilers && chk.contains(\"#spoiler\");\n\t\t\t\t}\n\t\t\t} catch (Exception err) {\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic static class Origin {\n\t\t\tpublic String name;\n\t\t\tpublic String url;\n\t\t}\n\t}\n\t\n\tpublic static class Entry extends BaseEntry {\n\t\tpublic String rawLink;\n\t\tpublic String url;\n\t\tpublic List<Comment> comments = new ArrayList<Comment>();\n\t\tpublic List<Like> likes = new ArrayList<Like>();\n\t\tpublic BaseFeed[] to = new BaseFeed[] {};\n\t\tpublic Thumbnail[] thumbnails = new Thumbnail[] {};\n\t\tpublic Fof fof;\n\t\tpublic String fofHtml;\n\t\tpublic String shortId = \"\";\n\t\tpublic String shortUrl = \"\";\n\t\tpublic Attachment[] files = new Attachment[] {};\n\t\tpublic Coordinates geo;\n\t\tpublic boolean hidden = false; // undocumented\n\t\tpublic int thumbpos = 0; // local\n\t\t\n\t\t@Override\n\t\tpublic void update(BaseEntry item) {\n\t\t\tsuper.update(item);\n\t\t\t\n\t\t\tif (!isIt(item.id))\n\t\t\t\treturn;\n\t\t\t\n\t\t\tEntry entry = (Entry) item;\n\n\t\t\turl = entry.url;\n\t\t\tfof = entry.fof;\n\t\t\thidden = entry.hidden;\n\t\t\trawLink = entry.rawLink;\n\t\t\tfofHtml = entry.fofHtml;\n\t\t\tthumbnails = entry.thumbnails;\n\t\t\tfiles = entry.files;\n\t\t\tgeo = entry.geo;\n\n\t\t\tfor (Comment comm : entry.comments)\n\t\t\t\tif (comm.created)\n\t\t\t\t\tcomments.add(comm);\n\t\t\t\telse\n\t\t\t\t\tfor (Comment old : comments)\n\t\t\t\t\t\tif (old.isIt(comm.id)) {\n\t\t\t\t\t\t\told.update(comm);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\n\t\t\tfor (Like like : entry.likes)\n\t\t\t\tif (like.created)\n\t\t\t\t\tlikes.add(like);\n\t\t\t\n\t\t\tupdated = true;\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void checkLocalHide() {\n\t\t\tsuper.checkLocalHide();\n\t\t\t\n\t\t\tif (canUnlike()) {\n\t\t\t\tbanned = false;\n\t\t\t\tspoiler = false;\n\t\t\t} else\n\t\t\t\tfor (BaseFeed bf: to)\n\t\t\t\t\tif (Commons.bFeeds.contains(bf.id)) {\n\t\t\t\t\t\tbanned = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\tfor (Comment c: comments)\n\t\t\t\tc.checkLocalHide();\n\t\t}\n\t\t\n\t\tpublic boolean isDM() {\n\t\t\tif (to.length <= 0)\n\t\t\t\treturn false;\n\t\t\tfor (BaseFeed f: to)\n\t\t\t\tif (!f.isUser() || f.isIt(from.id))\n\t\t\t\t\treturn false;\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\tpublic boolean canComment() {\n\t\t\treturn commands.contains(\"comment\");\n\t\t}\n\t\t\n\t\tpublic boolean canLike() {\n\t\t\treturn commands.contains(\"like\");\n\t\t}\n\t\t\n\t\tpublic boolean canUnlike() {\n\t\t\treturn commands.contains(\"unlike\") || hidden;\n\t\t}\n\t\t\n\t\tpublic boolean canHide() {\n\t\t\treturn commands.contains(\"hide\");// || !hidden;\n\t\t}\n\t\t\n\t\tpublic boolean canUnhide() {\n\t\t\treturn commands.contains(\"unhide\");\n\t\t}\n\t\t\n\t\tpublic String getToLine() {\n\t\t\tif (to.length <= 0 || to.length == 1 && (to[0].id.equals(from.id) || to[0].id.equals(id)))\n\t\t\t\treturn null;\n\t\t\tList<String> lst = new ArrayList<String>();\n\t\t\tfor (BaseFeed f : to)\n\t\t\t\tlst.add(f.isMe() ? IdentItem.accountFeed : f.getName());\n\t\t\treturn TextUtils.join(\", \", lst);\n\t\t}\n\t\t\n\t\tpublic String[] getFofIDs() {\n\t\t\tif (fof == null || TextUtils.isEmpty(fofHtml))\n\t\t\t\treturn null;\n\t\t\tPattern p = Pattern.compile(\"friendfeed\\\\.com/((\\\\d|\\\\w)+)\");\n\t\t\tMatcher m = p.matcher(fofHtml);\n\t\t\tString f1 = null;\n\t\t\tString f2 = null;\n\t\t\tif (m.find()) {\n\t\t\t\tf1 = m.group(1);\n\t\t\t\tif (m.find())\n\t\t\t\t\tf2 = m.group(1);\n\t\t\t}\n\t\t\tif (f2 != null)\n\t\t\t\treturn new String[] { f1, f2 };\n\t\t\tif (f1 != null)\n\t\t\t\treturn new String[] { f1 };\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tpublic int getFilesCount() {\n\t\t\treturn files.length + thumbnails.length;\n\t\t}\n\t\t\n\t\tpublic int getLikesCount() {\n\t\t\tif (likes == null)\n\t\t\t\treturn 0;\n\t\t\tfor (Like l : likes)\n\t\t\t\tif (l.placeholder != null && l.placeholder)\n\t\t\t\t\treturn l.num + likes.size() - 1;\n\t\t\treturn likes.size();\n\t\t}\n\t\t\n\t\tpublic int getCommentsCount() {\n\t\t\tif (comments == null)\n\t\t\t\treturn 0;\n\t\t\tfor (Comment c : comments)\n\t\t\t\tif (c.placeholder != null && c.placeholder)\n\t\t\t\t\treturn c.num + comments.size() - 1;\n\t\t\treturn comments.size();\n\t\t}\n\t\t\n\t\tpublic String[] getMediaUrls(boolean attachments) {\n\t\t\tString[] res = new String[attachments ? thumbnails.length + files.length : thumbnails.length];\n\t\t\tfor (int i = 0; i < thumbnails.length; i++)\n\t\t\t\tres[i] = thumbnails[i].link;\n\t\t\tif (attachments)\n\t\t\t\tfor (int i = 0; i < thumbnails.length; i++)\n\t\t\t\t\tres[thumbnails.length + i] = files[i].url;\n\t\t\treturn res;\n\t\t}\n\t\t\n\t\tpublic int indexOfComment(String cid) {\n\t\t\tComment c;\n\t\t\tfor (int i = 0; i < comments.size(); i++) {\n\t\t\t\tc = comments.get(i);\n\t\t\t\tif (!c.placeholder && c.id.equals(cid))\n\t\t\t\t\treturn i;\n\t\t\t}\n\t\t\treturn -1;\n\t\t}\n\t\t\n\t\tpublic int indexOfLike(String userId) {\n\t\t\tLike l;\n\t\t\tfor (int i = 0; i < likes.size(); i++) {\n\t\t\t\tl = likes.get(i);\n\t\t\t\tif (!l.placeholder && l.from.id.equals(userId))\n\t\t\t\t\treturn i;\n\t\t\t}\n\t\t\treturn -1;\n\t\t}\n\t\t\n\t\tpublic boolean hasSpoilers() {\n\t\t\tfor (Comment c: comments)\n\t\t\t\tif (c.spoiler)\n\t\t\t\t\treturn true;\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tpublic boolean hasReplies() {\n\t\t\tfor (Comment c: comments)\n\t\t\t\tif ((c.created || c.updated) && !c.from.isMe())\n\t\t\t\t\treturn true;\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tpublic void thumbNext() {\n\t\t\tthumbpos = thumbnails.length > 0 ? (thumbpos + 1) % thumbnails.length : 0;\n\t\t}\n\t\t\n\t\tpublic void thumbPrior() {\n\t\t\tthumbpos = thumbnails.length > 0 ? (thumbpos + (thumbnails.length - 1)) % thumbnails.length : 0;\n\t\t}\n\t\t\n\t\tpublic static class Fof {\n\t\t\tpublic String type;\n\t\t\tpublic BaseFeed from;\n\t\t}\n\t\t\n\t\tpublic static class Thumbnail {\n\t\t\tpublic String url = \"\";\n\t\t\tpublic String link = \"\";\n\t\t\tpublic int width = 0;\n\t\t\tpublic int height = 0;\n\t\t\tpublic String player = \"\";\n\t\t\tpublic int rotation = 0; // local\n\t\t\tpublic boolean landscape = true; // local\n\t\t\tpublic String videoId = null; // local\n\t\t\tpublic String videoUrl = null; // local\n\t\t\t\n\t\t\tpublic boolean isFFMediaPic() {\n\t\t\t\treturn link.indexOf(\"/m.friendfeed-media.com/\") > 0;\n\t\t\t}\n\t\t\t\n\t\t\tpublic boolean isSimplePic() {\n\t\t\t\treturn link.endsWith(\".jpg\") || link.endsWith(\".jpeg\") || link.endsWith(\".png\") || link.endsWith(\".gif\");\n\t\t\t}\n\t\t\t\n\t\t\tpublic boolean isYouTube() {\n\t\t\t\tif (TextUtils.isEmpty(player))\n\t\t\t\t\treturn false;\n\t\t\t\tif (!(TextUtils.isEmpty(videoId) || TextUtils.isEmpty(videoUrl)))\n\t\t\t\t\treturn true;\n\t\t\t\tDocument doc = Jsoup.parseBodyFragment(player);\n\t\t\t\tElements emb = doc.getElementsByTag(\"embed\");\n\t\t\t\tif (emb != null && emb.size() > 0 && emb.get(0).hasAttr(\"src\")) {\n\t\t\t\t\tString src = emb.get(0).attr(\"src\");\n\t\t\t\t\tif (Commons.YouTube.isVideoUrl(src)) {\n\t\t\t\t\t\tvideoId = Commons.YouTube.getId(src);\n\t\t\t\t\t\tvideoUrl = Commons.YouTube.getFriendlyUrl(src);\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\tpublic String videoPreview() {\n\t\t\t\treturn isYouTube() ? Commons.YouTube.getPreview(videoUrl) : null;\n\t\t\t}\n\t\t}\n\t\t\n\t\tpublic static class Attachment {\n\t\t\tpublic String url;\n\t\t\tpublic String type;\n\t\t\tpublic String name;\n\t\t\tpublic String icon;\n\t\t\tpublic int size = 0;\n\t\t}\n\t\t\n\t\tpublic static class Coordinates {\n\t\t\tpublic String lat;\n\t\t\t\n\t\t\t@SerializedName(\"long\")\n\t\t\tpublic String lon;\n\t\t}\n\t}\n\t\n\tpublic static class Comment extends BaseEntry {\n\t\t// compact view only (plus body):\n\t\tpublic Boolean placeholder = false;\n\t\tpublic int num;\n\t\t\n\t\t@Override\n\t\tpublic void checkLocalHide() {\n\t\t\tif (placeholder)\n\t\t\t\treturn;\n\t\t\tsuper.checkLocalHide();\n\t\t\tif (body.toLowerCase(Locale.getDefault()).equals(\"sp\") ||\n\t\t\t\tbody.toLowerCase(Locale.getDefault()).equals(\"spoiler\") ||\n\t\t\t\trawBody.toLowerCase(Locale.getDefault()).equals(\"sp\") ||\n\t\t\t\trawBody.toLowerCase(Locale.getDefault()).equals(\"spoiler\"))\n\t\t\t\tspoiler = true;\n\t\t}\n\t}\n\t\n\tpublic static class Like {\n\t\tpublic Date date;\n\t\tpublic BaseFeed from;\n\t\tpublic boolean created;\n\t\tpublic boolean updated;\n\t\t// compact view only:\n\t\tpublic String body;\n\t\tpublic Boolean placeholder = false;\n\t\tpublic int num;\n\t\t\n\t\tpublic boolean isMine() {\n\t\t\treturn from.isMe();\n\t\t}\n\t\t\n\t\tpublic String getFuzzyTime() {\n\t\t\treturn DateUtils.getRelativeTimeSpanString(date.getTime(), System.currentTimeMillis(),\n\t\t\t\tDateUtils.MINUTE_IN_MILLIS).toString();\n\t\t}\n\t}\n\t\n\tpublic static class FeedInfo extends BaseFeed {\n\t\tpublic BaseFeed[] feeds = new BaseFeed[] {}; // lists only\n\t\tpublic BaseFeed[] subscriptions = new BaseFeed[] {}; // users only\n\t\tpublic BaseFeed[] subscribers = new BaseFeed[] {}; // users and groups\n\t\tpublic BaseFeed[] admins = new BaseFeed[] {}; // groups only\n\t\t\n\t\tpublic BaseFeed findFeedById(String fid) {\n\t\t\tfor (BaseFeed f: subscriptions)\n\t\t\t\tif (f.isIt(fid))\n\t\t\t\t\treturn f;\n\t\t\tfor (BaseFeed f: subscribers)\n\t\t\t\tif (f.isIt(fid))\n\t\t\t\t\treturn f;\n\t\t\treturn null;\n\t\t}\n\t}\n\t\n\tpublic static class FeedList {\n\t\tpublic SectionItem[] main;\n\t\tpublic SectionItem[] lists;\n\t\tpublic SectionItem[] groups;\n\t\tpublic SectionItem[] searches;\n\t\tpublic Section[] sections;\n\t\tpublic long timestamp = System.currentTimeMillis();\n\t\t\n\t\tpublic long getAge() {\n\t\t\treturn System.currentTimeMillis() - timestamp;\n\t\t}\n\t\t\n\t\tpublic SectionItem getSectionByFeed(String feed_id) {\n\t\t\tfor (Section s : sections)\n\t\t\t\tfor (SectionItem f : s.feeds)\n\t\t\t\t\tif (f.id.equals(feed_id))\n\t\t\t\t\t\treturn f;\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tpublic static class SectionItem extends BaseFeed {\n\t\t\tpublic String query = \"\";\n\t\t}\n\t\t\n\t\tpublic static class Section {\n\t\t\tpublic String id;\n\t\t\tpublic String name;\n\t\t\tpublic SectionItem[] feeds;\n\t\t\t\n\t\t\tpublic boolean hasFeed(String feed_id) {\n\t\t\t\tfor (SectionItem si : feeds)\n\t\t\t\t\tif (si.id.equals(feed_id))\n\t\t\t\t\t\treturn true;\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static void dropClients() {\n\t\tCLIENT_PROFILE = null;\n\t\tCLIENT_MSGS = null;\n\t\tCLIENT_FEED = null;\n\t\tCLIENT_ENTRY = null;\n\t\tCLIENT_WRITER = null;\n\t}\n\t\n\tprivate static FF CLIENT_PROFILE;\n\tprivate static FF CLIENT_MSGS;\n\tprivate static FF CLIENT_FEED;\n\tprivate static FF CLIENT_ENTRY;\n\tprivate static FF CLIENT_WRITER;\n\t\n\tpublic static FF client_profile(final FFSession session) {\n\t\tif (CLIENT_PROFILE == null)\n\t\t\tCLIENT_PROFILE = new RestAdapter.Builder().setEndpoint(API_URL).setRequestInterceptor(\n\t\t\t\tnew RequestInterceptor() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void intercept(RequestFacade request) {\n\t\t\t\t\t\tString authText = session.getUsername() + \":\" + session.getRemoteKey();\n\t\t\t\t\t\tString authData = \"Basic \" + Base64.encodeToString(authText.getBytes(), 0);\n\t\t\t\t\t\trequest.addHeader(\"Authorization\", authData);\n\t\t\t\t\t\trequest.addHeader(\"User-Agent\", Commons.USER_AGENT);\n\t\t\t\t\t\trequest.addQueryParam(\"locale\", session.getPrefs().getString(PK.LOCALE, \"en\"));\n\t\t\t\t\t}\n\t\t\t\t}).setLogLevel(RestAdapter.LogLevel.NONE).setClient(new WaitingUCC()).build().create(FF.class);\n\t\treturn CLIENT_PROFILE;\n\t}\n\t\n\tpublic static FF client_msgs(final FFSession session) {\n\t\tif (CLIENT_MSGS == null)\n\t\t\tCLIENT_MSGS = new RestAdapter.Builder().setEndpoint(API_URL).setRequestInterceptor(\n\t\t\t\tnew RequestInterceptor() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void intercept(RequestFacade request) {\n\t\t\t\t\t\tString authText = session.getUsername() + \":\" + session.getRemoteKey();\n\t\t\t\t\t\tString authData = \"Basic \" + Base64.encodeToString(authText.getBytes(), 0);\n\t\t\t\t\t\trequest.addHeader(\"Authorization\", authData);\n\t\t\t\t\t\trequest.addHeader(\"User-Agent\", Commons.USER_AGENT);\n\t\t\t\t\t\trequest.addQueryParam(\"locale\", session.getPrefs().getString(PK.LOCALE, \"en\"));\n\t\t\t\t\t\trequest.addQueryParam(\"maxcomments\", \"1000\");\n\t\t\t\t\t\trequest.addQueryParam(\"raw\", \"1\");\n\t\t\t\t\t}\n\t\t\t\t}).setLogLevel(RestAdapter.LogLevel.NONE).setClient(new WaitingUCC()).build().create(FF.class);\n\t\treturn CLIENT_MSGS;\n\t}\n\t\n\tpublic static FF client_feed(final FFSession session) {\n\t\tif (CLIENT_FEED == null)\n\t\t\tCLIENT_FEED = new RestAdapter.Builder().setEndpoint(API_URL).setRequestInterceptor(\n\t\t\t\tnew RequestInterceptor() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void intercept(RequestFacade request) {\n\t\t\t\t\t\tString authText = session.getUsername() + \":\" + session.getRemoteKey();\n\t\t\t\t\t\tString authData = \"Basic \" + Base64.encodeToString(authText.getBytes(), 0);\n\t\t\t\t\t\trequest.addHeader(\"Authorization\", authData);\n\t\t\t\t\t\trequest.addHeader(\"User-Agent\", Commons.USER_AGENT);\n\t\t\t\t\t\trequest.addQueryParam(\"locale\", session.getPrefs().getString(PK.LOCALE, \"en\"));\n\t\t\t\t\t\trequest.addQueryParam(\"maxcomments\", \"auto\");\n\t\t\t\t\t\trequest.addQueryParam(\"maxlikes\", \"auto\");\n\t\t\t\t\t\trequest.addQueryParam(\"raw\", \"1\");\n\t\t\t\t\t\tif (session.getPrefs().getBoolean(PK.FEED_FOF, true))\n\t\t\t\t\t\t\trequest.addQueryParam(\"fof\", \"1\");\n\t\t\t\t\t\tif (session.getPrefs().getBoolean(PK.FEED_HID, true))\n\t\t\t\t\t\t\trequest.addQueryParam(\"hidden\", \"1\");\n\t\t\t\t\t}\n\t\t\t\t}).setLogLevel(RestAdapter.LogLevel.NONE).setClient(new WaitingUCC()).build().create(FF.class);\n\t\treturn CLIENT_FEED;\n\t}\n\t\n\tpublic static FF client_entry(final FFSession session) {\n\t\tif (CLIENT_ENTRY == null)\n\t\t\tCLIENT_ENTRY = new RestAdapter.Builder().setEndpoint(API_URL).setRequestInterceptor(\n\t\t\t\tnew RequestInterceptor() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void intercept(RequestFacade request) {\n\t\t\t\t\t\tString authText = session.getUsername() + \":\" + session.getRemoteKey();\n\t\t\t\t\t\tString authData = \"Basic \" + Base64.encodeToString(authText.getBytes(), 0);\n\t\t\t\t\t\trequest.addHeader(\"Authorization\", authData);\n\t\t\t\t\t\trequest.addHeader(\"User-Agent\", Commons.USER_AGENT);\n\t\t\t\t\t\trequest.addQueryParam(\"locale\", session.getPrefs().getString(PK.LOCALE, \"en\"));\n\t\t\t\t\t\trequest.addQueryParam(\"raw\", \"1\");\n\t\t\t\t\t}\n\t\t\t\t}).setLogLevel(RestAdapter.LogLevel.NONE).setClient(new WaitingUCC()).build().create(FF.class);\n\t\treturn CLIENT_ENTRY;\n\t}\n\t\n\tpublic static FF client_write(final FFSession session) {\n\t\tif (CLIENT_WRITER == null)\n\t\t\tCLIENT_WRITER = new RestAdapter.Builder().setEndpoint(API_URL).setRequestInterceptor(\n\t\t\t\tnew RequestInterceptor() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void intercept(RequestFacade request) {\n\t\t\t\t\t\tString authText = session.getUsername() + \":\" + session.getRemoteKey();\n\t\t\t\t\t\tString authData = \"Basic \" + Base64.encodeToString(authText.getBytes(), 0);\n\t\t\t\t\t\trequest.addHeader(\"Authorization\", authData);\n\t\t\t\t\t\trequest.addQueryParam(\"appid\", API_KEY);\n\t\t\t\t\t}\n\t\t\t\t}).setLogLevel(RestAdapter.LogLevel.NONE).setClient(new WaitingUCC()).build().create(FF.class);\n\t\treturn CLIENT_WRITER;\n\t}\n\t\n\tstatic class WaitingUCC extends UrlConnectionClient {\n\t\t@Override\n\t\tprotected HttpURLConnection openConnection(Request request) throws IOException {\n\t\t\tHttpURLConnection connection = super.openConnection(request);\n\t\t\tconnection.setConnectTimeout(20 * 1000); // 20 sec\n\t\t\tconnection.setReadTimeout(60 * 1000); // 60 sec\n\t\t\treturn connection;\n\t\t}\n\t}\n}", "public static class Entry extends BaseEntry {\n\tpublic String rawLink;\n\tpublic String url;\n\tpublic List<Comment> comments = new ArrayList<Comment>();\n\tpublic List<Like> likes = new ArrayList<Like>();\n\tpublic BaseFeed[] to = new BaseFeed[] {};\n\tpublic Thumbnail[] thumbnails = new Thumbnail[] {};\n\tpublic Fof fof;\n\tpublic String fofHtml;\n\tpublic String shortId = \"\";\n\tpublic String shortUrl = \"\";\n\tpublic Attachment[] files = new Attachment[] {};\n\tpublic Coordinates geo;\n\tpublic boolean hidden = false; // undocumented\n\tpublic int thumbpos = 0; // local\n\t\t\n\t@Override\n\tpublic void update(BaseEntry item) {\n\t\tsuper.update(item);\n\t\t\t\n\t\tif (!isIt(item.id))\n\t\t\treturn;\n\t\t\t\n\t\tEntry entry = (Entry) item;\n\n\t\turl = entry.url;\n\t\tfof = entry.fof;\n\t\thidden = entry.hidden;\n\t\trawLink = entry.rawLink;\n\t\tfofHtml = entry.fofHtml;\n\t\tthumbnails = entry.thumbnails;\n\t\tfiles = entry.files;\n\t\tgeo = entry.geo;\n\n\t\tfor (Comment comm : entry.comments)\n\t\t\tif (comm.created)\n\t\t\t\tcomments.add(comm);\n\t\t\telse\n\t\t\t\tfor (Comment old : comments)\n\t\t\t\t\tif (old.isIt(comm.id)) {\n\t\t\t\t\t\told.update(comm);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\n\t\tfor (Like like : entry.likes)\n\t\t\tif (like.created)\n\t\t\t\tlikes.add(like);\n\t\t\t\n\t\tupdated = true;\n\t}\n\t\t\n\t@Override\n\tpublic void checkLocalHide() {\n\t\tsuper.checkLocalHide();\n\t\t\t\n\t\tif (canUnlike()) {\n\t\t\tbanned = false;\n\t\t\tspoiler = false;\n\t\t} else\n\t\t\tfor (BaseFeed bf: to)\n\t\t\t\tif (Commons.bFeeds.contains(bf.id)) {\n\t\t\t\t\tbanned = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\tfor (Comment c: comments)\n\t\t\tc.checkLocalHide();\n\t}\n\t\t\n\tpublic boolean isDM() {\n\t\tif (to.length <= 0)\n\t\t\treturn false;\n\t\tfor (BaseFeed f: to)\n\t\t\tif (!f.isUser() || f.isIt(from.id))\n\t\t\t\treturn false;\n\t\treturn true;\n\t}\n\t\t\n\tpublic boolean canComment() {\n\t\treturn commands.contains(\"comment\");\n\t}\n\t\t\n\tpublic boolean canLike() {\n\t\treturn commands.contains(\"like\");\n\t}\n\t\t\n\tpublic boolean canUnlike() {\n\t\treturn commands.contains(\"unlike\") || hidden;\n\t}\n\t\t\n\tpublic boolean canHide() {\n\t\treturn commands.contains(\"hide\");// || !hidden;\n\t}\n\t\t\n\tpublic boolean canUnhide() {\n\t\treturn commands.contains(\"unhide\");\n\t}\n\t\t\n\tpublic String getToLine() {\n\t\tif (to.length <= 0 || to.length == 1 && (to[0].id.equals(from.id) || to[0].id.equals(id)))\n\t\t\treturn null;\n\t\tList<String> lst = new ArrayList<String>();\n\t\tfor (BaseFeed f : to)\n\t\t\tlst.add(f.isMe() ? IdentItem.accountFeed : f.getName());\n\t\treturn TextUtils.join(\", \", lst);\n\t}\n\t\t\n\tpublic String[] getFofIDs() {\n\t\tif (fof == null || TextUtils.isEmpty(fofHtml))\n\t\t\treturn null;\n\t\tPattern p = Pattern.compile(\"friendfeed\\\\.com/((\\\\d|\\\\w)+)\");\n\t\tMatcher m = p.matcher(fofHtml);\n\t\tString f1 = null;\n\t\tString f2 = null;\n\t\tif (m.find()) {\n\t\t\tf1 = m.group(1);\n\t\t\tif (m.find())\n\t\t\t\tf2 = m.group(1);\n\t\t}\n\t\tif (f2 != null)\n\t\t\treturn new String[] { f1, f2 };\n\t\tif (f1 != null)\n\t\t\treturn new String[] { f1 };\n\t\treturn null;\n\t}\n\t\t\n\tpublic int getFilesCount() {\n\t\treturn files.length + thumbnails.length;\n\t}\n\t\t\n\tpublic int getLikesCount() {\n\t\tif (likes == null)\n\t\t\treturn 0;\n\t\tfor (Like l : likes)\n\t\t\tif (l.placeholder != null && l.placeholder)\n\t\t\t\treturn l.num + likes.size() - 1;\n\t\treturn likes.size();\n\t}\n\t\t\n\tpublic int getCommentsCount() {\n\t\tif (comments == null)\n\t\t\treturn 0;\n\t\tfor (Comment c : comments)\n\t\t\tif (c.placeholder != null && c.placeholder)\n\t\t\t\treturn c.num + comments.size() - 1;\n\t\treturn comments.size();\n\t}\n\t\t\n\tpublic String[] getMediaUrls(boolean attachments) {\n\t\tString[] res = new String[attachments ? thumbnails.length + files.length : thumbnails.length];\n\t\tfor (int i = 0; i < thumbnails.length; i++)\n\t\t\tres[i] = thumbnails[i].link;\n\t\tif (attachments)\n\t\t\tfor (int i = 0; i < thumbnails.length; i++)\n\t\t\t\tres[thumbnails.length + i] = files[i].url;\n\t\treturn res;\n\t}\n\t\t\n\tpublic int indexOfComment(String cid) {\n\t\tComment c;\n\t\tfor (int i = 0; i < comments.size(); i++) {\n\t\t\tc = comments.get(i);\n\t\t\tif (!c.placeholder && c.id.equals(cid))\n\t\t\t\treturn i;\n\t\t}\n\t\treturn -1;\n\t}\n\t\t\n\tpublic int indexOfLike(String userId) {\n\t\tLike l;\n\t\tfor (int i = 0; i < likes.size(); i++) {\n\t\t\tl = likes.get(i);\n\t\t\tif (!l.placeholder && l.from.id.equals(userId))\n\t\t\t\treturn i;\n\t\t}\n\t\treturn -1;\n\t}\n\t\t\n\tpublic boolean hasSpoilers() {\n\t\tfor (Comment c: comments)\n\t\t\tif (c.spoiler)\n\t\t\t\treturn true;\n\t\treturn false;\n\t}\n\t\t\n\tpublic boolean hasReplies() {\n\t\tfor (Comment c: comments)\n\t\t\tif ((c.created || c.updated) && !c.from.isMe())\n\t\t\t\treturn true;\n\t\treturn false;\n\t}\n\t\t\n\tpublic void thumbNext() {\n\t\tthumbpos = thumbnails.length > 0 ? (thumbpos + 1) % thumbnails.length : 0;\n\t}\n\t\t\n\tpublic void thumbPrior() {\n\t\tthumbpos = thumbnails.length > 0 ? (thumbpos + (thumbnails.length - 1)) % thumbnails.length : 0;\n\t}\n\t\t\n\tpublic static class Fof {\n\t\tpublic String type;\n\t\tpublic BaseFeed from;\n\t}\n\t\t\n\tpublic static class Thumbnail {\n\t\tpublic String url = \"\";\n\t\tpublic String link = \"\";\n\t\tpublic int width = 0;\n\t\tpublic int height = 0;\n\t\tpublic String player = \"\";\n\t\tpublic int rotation = 0; // local\n\t\tpublic boolean landscape = true; // local\n\t\tpublic String videoId = null; // local\n\t\tpublic String videoUrl = null; // local\n\t\t\t\n\t\tpublic boolean isFFMediaPic() {\n\t\t\treturn link.indexOf(\"/m.friendfeed-media.com/\") > 0;\n\t\t}\n\t\t\t\n\t\tpublic boolean isSimplePic() {\n\t\t\treturn link.endsWith(\".jpg\") || link.endsWith(\".jpeg\") || link.endsWith(\".png\") || link.endsWith(\".gif\");\n\t\t}\n\t\t\t\n\t\tpublic boolean isYouTube() {\n\t\t\tif (TextUtils.isEmpty(player))\n\t\t\t\treturn false;\n\t\t\tif (!(TextUtils.isEmpty(videoId) || TextUtils.isEmpty(videoUrl)))\n\t\t\t\treturn true;\n\t\t\tDocument doc = Jsoup.parseBodyFragment(player);\n\t\t\tElements emb = doc.getElementsByTag(\"embed\");\n\t\t\tif (emb != null && emb.size() > 0 && emb.get(0).hasAttr(\"src\")) {\n\t\t\t\tString src = emb.get(0).attr(\"src\");\n\t\t\t\tif (Commons.YouTube.isVideoUrl(src)) {\n\t\t\t\t\tvideoId = Commons.YouTube.getId(src);\n\t\t\t\t\tvideoUrl = Commons.YouTube.getFriendlyUrl(src);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t\t\t\n\t\tpublic String videoPreview() {\n\t\t\treturn isYouTube() ? Commons.YouTube.getPreview(videoUrl) : null;\n\t\t}\n\t}\n\t\t\n\tpublic static class Attachment {\n\t\tpublic String url;\n\t\tpublic String type;\n\t\tpublic String name;\n\t\tpublic String icon;\n\t\tpublic int size = 0;\n\t}\n\t\t\n\tpublic static class Coordinates {\n\t\tpublic String lat;\n\t\t\t\n\t\t@SerializedName(\"long\")\n\t\tpublic String lon;\n\t}\n}", "public static class Feed extends BaseFeed {\n\tpublic List<Entry> entries = new ArrayList<Entry>();\n\tpublic Realtime realtime;\n\t\t\n\tpublic static String lastDeletedEntry = \"\";\n\t\t\n\tpublic int indexOf(String eid) {\n\t\tfor (int i = 0; i < entries.size(); i++)\n\t\t\tif (entries.get(i).isIt(eid))\n\t\t\t\treturn i;\n\t\treturn -1;\n\t}\n\t\t\n\tpublic Entry find(String eid) {\n\t\tfor (Entry e : entries)\n\t\t\tif (e.id.equals(eid))\n\t\t\t\treturn e;\n\t\treturn null;\n\t}\n\t\t\n\tpublic int append(Feed feed) {\n\t\tint res = 0;\n\t\tfor (Entry e : feed.entries)\n\t\t\tif (find(e.id) == null) {\n\t\t\t\tentries.add(e);\n\t\t\t\te.checkLocalHide();\n\t\t\t\tres++;\n\t\t\t}\n\t\treturn res;\n\t}\n\t\t\n\tpublic int update(Feed feed, boolean sortLikeSite) {\n\t\trealtime = feed.realtime;\n\t\ttimestamp = feed.timestamp;\n\t\tint res = 0;\n\t\tfor (Entry e : feed.entries)\n\t\t\tif (e.created) {\n\t\t\t\tentries.add(0, e);\n\t\t\t\te.checkLocalHide();\n\t\t\t\tres++;\n\t\t\t} else\n\t\t\t\tfor (Entry old : entries)\n\t\t\t\t\tif (old.isIt(e.id)) {\n\t\t\t\t\t\told.update(e);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\tif (!TextUtils.isEmpty(lastDeletedEntry))\n\t\t\tfor (int n = 0; n < entries.size(); n++)\n\t\t\t\tif (entries.get(n).id.equals(lastDeletedEntry)) {\n\t\t\t\t\tentries.remove(n);\n\t\t\t\t\tlastDeletedEntry = \"\";\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\tif (sortLikeSite && res > 0) {\n\t\t\tCollections.sort(entries, new Comparator<BaseEntry>() {\n\t\t\t @Override\n\t\t\t public int compare(BaseEntry o1, BaseEntry o2) {\n\t\t\t return o1.date.compareTo(o2.date) * -1;\n\t\t\t }\n\t\t\t});\n\t\t}\n\t\treturn res;\n\t}\n\t\t\n\tpublic int update(Feed feed) {\n\t\treturn update(feed, false);\n\t}\n\t\t\n\tpublic void checkLocalHide() {\n\t\tfor (Entry e : entries)\n\t\t\te.checkLocalHide();\n\t}\n\t\t\n\tpublic static class Realtime {\n\t\tpublic String cursor;\n\t\tpublic final long timestamp = System.currentTimeMillis();\n\t}\n}", "public static class Like {\n\tpublic Date date;\n\tpublic BaseFeed from;\n\tpublic boolean created;\n\tpublic boolean updated;\n\t// compact view only:\n\tpublic String body;\n\tpublic Boolean placeholder = false;\n\tpublic int num;\n\t\t\n\tpublic boolean isMine() {\n\t\treturn from.isMe();\n\t}\n\t\t\n\tpublic String getFuzzyTime() {\n\t\treturn DateUtils.getRelativeTimeSpanString(date.getTime(), System.currentTimeMillis(),\n\t\t\tDateUtils.MINUTE_IN_MILLIS).toString();\n\t}\n}", "public static class SimpleResponse {\n\tpublic boolean success = false; // unlike & unsubscribe?\n\tpublic String status = \"\"; // subscribe & unsubscribe?\n}" ]
import java.util.Timer; import java.util.TimerTask; import net.ggelardi.flucso.data.FeedAdapter; import net.ggelardi.flucso.data.SubscrListAdapter; import net.ggelardi.flucso.serv.Commons; import net.ggelardi.flucso.serv.Commons.PK; import net.ggelardi.flucso.serv.FFAPI; import net.ggelardi.flucso.serv.FFAPI.Entry; import net.ggelardi.flucso.serv.FFAPI.Feed; import net.ggelardi.flucso.serv.FFAPI.Like; import net.ggelardi.flucso.serv.FFAPI.SimpleResponse; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.DataSetObserver; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.squareup.picasso.Picasso.LoadedFrom; import com.squareup.picasso.Target;
package net.ggelardi.flucso; public class FeedFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, OnClickListener { public static final String FRAGMENT_TAG = "net.ggelardi.flucso.FeedFragment"; private static final int AMOUNT_BASE = 30; private static final int AMOUNT_INCR = 20;
private FeedAdapter adapter;
0
bonigarcia/dualsub
src/test/java/io/github/bonigarcia/dualsub/test/TestTranslation.java
[ "public class DualSub {\n\n\tprivate static final Logger log = LoggerFactory.getLogger(DualSub.class);\n\n\t// Preferences and Properties\n\tprivate Preferences preferences;\n\tprivate Properties properties;\n\n\t// UI Elements\n\tprivate JFrame frame;\n\tprivate JList<File> leftSubtitles;\n\tprivate JList<File> rightSubtitles;\n\tprivate JTextField outputFolder;\n\tprivate Splash splash;\n\tprivate Cursor cursor;\n\tprivate MergeButtonListener mergeButtonListener;\n\tprivate AddFileListener leftFileListener;\n\tprivate AddFileListener rightFileListener;\n\tprivate AddFolderListener folderListener;\n\tprivate Menu menu;\n\tprivate JProgressBar progressBar;\n\tprivate Color background;\n\tprivate JButton mergeButton;\n\n\t// Panels (options)\n\tprivate PanelTiming panelTiming;\n\tprivate PanelPlayer panelPlayer;\n\tprivate PanelOutput panelOutput;\n\tprivate PanelTranslation panelTranslation;\n\n\t// Dialogs\n\tprivate ExceptionDialog exception;\n\tprivate HelpPlayerDialog helpPlayer;\n\tprivate HelpTimingDialog helpTiming;\n\tprivate HelpOutputDialog helpOutput;\n\tprivate HelpTranslationDialog helpTranslation;\n\tprivate HelpSubtitlesDialog helpSubtitles;\n\tprivate KeyTranslationDialog keyTranslationDialog;\n\n\t/**\n\t * Create the GUI.\n\t * \n\t * @throws IOException\n\t */\n\tpublic DualSub() throws IOException {\n\t\t// Look and feel\n\t\ttry {\n\t\t\t// UIManager.setLookAndFeel(new NimbusLookAndFeel());\n\n\t\t\tUIManager.setLookAndFeel(new Plastic3DLookAndFeel());\n\t\t\tJFrame.setDefaultLookAndFeelDecorated(false);\n\t\t\tJDialog.setDefaultLookAndFeelDecorated(false);\n\n\t\t\t// UIManager.setLookAndFeel(UIManager\n\t\t\t// .getCrossPlatformLookAndFeelClassName());\n\t\t\t// JFrame.setDefaultLookAndFeelDecorated(true);\n\t\t\t// JDialog.setDefaultLookAndFeelDecorated(true);\n\t\t} catch (Exception e) {\n\t\t\tlog.warn(e.getMessage());\n\t\t}\n\n\t\tsplash = new Splash(ClassLoader.getSystemResource(\"img/splash.png\"));\n\t\tcursor = new Cursor(Cursor.HAND_CURSOR);\n\n\t\tloadProperties();\n\n\t\t// Default language\n\t\tString locale = preferences.get(\"locale\",\n\t\t\t\tproperties.getProperty(\"locale\"));\n\t\tif (!locale.isEmpty()) {\n\t\t\tI18N.setLocale(locale);\n\t\t}\n\n\t\tinitialize();\n\n\t\tmenu = new Menu(this, locale);\n\t\tmenu.addMenu(leftFileListener, rightFileListener, folderListener,\n\t\t\t\tmergeButtonListener);\n\t\tshowFrame();\n\t}\n\n\tpublic void close() {\n\t\tframe.dispose();\n\t}\n\n\tprivate void loadProperties() throws IOException {\n\t\t// Load properties\n\t\tproperties = new Properties();\n\t\tInputStream inputStream = Thread.currentThread().getContextClassLoader()\n\t\t\t\t.getResourceAsStream(\"dualsub.properties\");\n\t\tReader reader = new InputStreamReader(inputStream, Charset.ISO88591);\n\t\tproperties.load(reader);\n\t\tFont.setProperties(properties);\n\n\t\t// Instantiate preferences\n\t\tpreferences = Preferences.userNodeForPackage(DualSub.class);\n\t}\n\n\t/**\n\t * Initialize the contents of the frame.\n\t */\n\tprivate void initialize() {\n\t\tframe = new JFrame();\n\t\tbackground = new Color(240, 240, 240);\n\t\tframe.getContentPane().setBackground(background);\n\n\t\t// Alert initialization\n\t\tAlert.setFrame(frame);\n\n\t\t// Progress bar\n\t\tprogressBar = new JProgressBar();\n\t\tprogressBar.setIndeterminate(true);\n\t\tprogressBar.setBounds(308, 110, 95, 15);\n\t\tprogressBar.setBackground(background);\n\t\tprogressBar.setVisible(false);\n\t\tframe.getContentPane().add(progressBar);\n\n\t\t// Left subtitles\n\t\tJScrollPane leftSubtitlesScroll = new JScrollPane();\n\t\tleftSubtitlesScroll.setBounds(46, 37, 260, 121);\n\t\tframe.getContentPane().add(leftSubtitlesScroll);\n\t\tleftSubtitles = new JList<File>(new DefaultListModel<File>());\n\t\tleftSubtitles.addKeyListener(new KeyAdapter() {\n\t\t\tpublic void keyPressed(KeyEvent key) {\n\t\t\t\tif (key.getKeyCode() == KeyEvent.VK_DELETE) {\n\t\t\t\t\tValidator.deleteSelected(leftSubtitles);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tleftSubtitles.setCellRenderer(new FileCellRenderer());\n\t\tleftSubtitles\n\t\t\t\t.setTransferHandler(new ListTransferHandler(leftSubtitles));\n\t\tleftSubtitles.setDragEnabled(true);\n\t\tleftSubtitles.setDropMode(javax.swing.DropMode.INSERT);\n\t\tleftSubtitles.setBorder(\n\t\t\t\tnew TitledBorder(UIManager.getBorder(\"TitledBorder.border\"),\n\t\t\t\t\t\tI18N.getHtmlText(\"Window.leftSubtitles.borderTitle\")));\n\t\tString leftColor = preferences.get(\"leftColor\", \"\");\n\t\tif (leftColor != null && !leftColor.isEmpty()) {\n\t\t\tleftSubtitles.setBackground(Color.decode(leftColor));\n\t\t\tSrtUtils.setLeftColor(leftColor);\n\t\t}\n\t\tleftSubtitlesScroll.setViewportView(leftSubtitles);\n\n\t\t// Right subtitles\n\t\tJScrollPane rightSubtitlesScroll = new JScrollPane();\n\t\trightSubtitlesScroll.setBounds(405, 37, 260, 121);\n\t\tframe.getContentPane().add(rightSubtitlesScroll);\n\t\trightSubtitles = new JList<File>(new DefaultListModel<File>());\n\t\trightSubtitles.addKeyListener(new KeyAdapter() {\n\t\t\tpublic void keyPressed(KeyEvent key) {\n\t\t\t\tif (key.getKeyCode() == KeyEvent.VK_DELETE) {\n\t\t\t\t\tValidator.deleteSelected(rightSubtitles);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\trightSubtitles.setCellRenderer(new FileCellRenderer());\n\t\trightSubtitles\n\t\t\t\t.setTransferHandler(new ListTransferHandler(rightSubtitles));\n\t\trightSubtitles.setDragEnabled(true);\n\t\trightSubtitles.setDropMode(javax.swing.DropMode.INSERT);\n\t\trightSubtitles.setBorder(\n\t\t\t\tnew TitledBorder(UIManager.getBorder(\"TitledBorder.border\"),\n\t\t\t\t\t\tI18N.getHtmlText(\"Window.rightSubtitles.borderTitle\")));\n\t\tString rightColor = preferences.get(\"rightColor\", \"\");\n\t\tif (rightColor != null && !rightColor.isEmpty()) {\n\t\t\trightSubtitles.setBackground(Color.decode(rightColor));\n\t\t\tSrtUtils.setRightColor(rightColor);\n\t\t}\n\t\trightSubtitlesScroll.setViewportView(rightSubtitles);\n\n\t\t// Output folder\n\t\tJButton outputFolderButton = new JButton(\n\t\t\t\tI18N.getHtmlText(\"Window.outputFolderButton.text\"));\n\t\toutputFolderButton.setBounds(46, 180, 117, 29);\n\t\toutputFolderButton.setCursor(cursor);\n\t\tframe.getContentPane().add(outputFolderButton);\n\t\toutputFolder = new JTextField();\n\t\toutputFolder.setBounds(165, 181, 500, 28);\n\t\toutputFolder.setColumns(10);\n\t\toutputFolder.setText(\n\t\t\t\tpreferences.get(\"output\", properties.getProperty(\"output\")));\n\t\tframe.getContentPane().add(outputFolder);\n\t\tfolderListener = new AddFolderListener(frame, outputFolder);\n\t\toutputFolderButton.addActionListener(folderListener);\n\n\t\t// Left buttons\n\t\tleftFileListener = new AddFileListener(frame, leftSubtitles);\n\t\tnew LateralButtons(cursor, frame, leftSubtitles, leftFileListener, 16);\n\n\t\t// Right buttons\n\t\trightFileListener = new AddFileListener(frame, rightSubtitles);\n\t\tnew LateralButtons(cursor, frame, rightSubtitles, rightFileListener,\n\t\t\t\t673);\n\n\t\t// Color Buttons\n\t\tnew ColorButtons(cursor, frame, leftSubtitles, rightSubtitles);\n\n\t\t// Merge Button\n\t\tmergeButton = new JButton(I18N.getHtmlText(\"Window.mergeButton.text\"));\n\t\tmergeButtonListener = new MergeButtonListener(this);\n\t\tmergeButton.addActionListener(mergeButtonListener);\n\t\tmergeButton.setBounds(308, 80, 95, 29);\n\t\tmergeButton.setCursor(cursor);\n\t\tframe.getContentPane().add(mergeButton);\n\n\t\t// Timing panel\n\t\tpanelTiming = new PanelTiming(this);\n\t\tframe.getContentPane().add(panelTiming);\n\n\t\t// Player panel\n\t\tpanelPlayer = new PanelPlayer(this);\n\t\tframe.getContentPane().add(panelPlayer);\n\n\t\t// Output panel\n\t\tpanelOutput = new PanelOutput(this);\n\t\tframe.getContentPane().add(panelOutput);\n\n\t\t// Translation panel\n\t\tpanelTranslation = new PanelTranslation(this);\n\t\tframe.getContentPane().add(panelTranslation);\n\n\t\t// Help\n\t\tJButton buttonHelpSub = new JButton(\n\t\t\t\tnew ImageIcon(ClassLoader.getSystemResource(\"img/help.png\")));\n\t\tbuttonHelpSub.setBounds(345, 50, 22, 22);\n\t\tbuttonHelpSub.setCursor(cursor);\n\t\tfinal DualSub top = this;\n\t\tbuttonHelpSub.addActionListener(new ActionListener() {\n\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\tHelpSubtitlesDialog helpSubtitlesDialog = getHelpSubtitles();\n\t\t\t\tif (helpSubtitlesDialog == null) {\n\t\t\t\t\thelpSubtitlesDialog = new HelpSubtitlesDialog(top, true);\n\t\t\t\t}\n\t\t\t\thelpSubtitlesDialog.setVisible();\n\t\t\t}\n\t\t});\n\t\tframe.add(buttonHelpSub);\n\n\t\t// Frame\n\t\tframe.setBounds(100, 100, 720, 520);\n\t\tDimension dim = Toolkit.getDefaultToolkit().getScreenSize();\n\t\tframe.setLocation((dim.width - frame.getWidth()) / 2,\n\t\t\t\t(dim.height - frame.getHeight()) / 2);\n\t\tframe.setResizable(false);\n\t\tframe.setIconImage(\n\t\t\t\tnew ImageIcon(ClassLoader.getSystemResource(\"img/dualsub.png\"))\n\t\t\t\t\t\t.getImage());\n\t\tframe.setTitle(I18N.getText(\"Window.name.text\"));\n\t\tframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);\n\t\tframe.addWindowListener(new ExitListener(this));\n\t\tframe.getContentPane().setLayout(null);\n\n\t}\n\n\tprivate void showFrame() {\n\t\tif (!frame.isVisible()) {\n\t\t\tsplash.setVisible(false);\n\t\t\tframe.setVisible(true);\n\t\t\tframe.requestFocus();\n\t\t}\n\t}\n\n\tpublic JFrame getFrame() {\n\t\treturn frame;\n\t}\n\n\tpublic PanelTiming getPanelTiming() {\n\t\treturn panelTiming;\n\t}\n\n\tpublic PanelPlayer getPanelPlayer() {\n\t\treturn panelPlayer;\n\t}\n\n\tpublic PanelOutput getPanelOutput() {\n\t\treturn panelOutput;\n\t}\n\n\tpublic PanelTranslation getPanelTranslation() {\n\t\treturn panelTranslation;\n\t}\n\n\tpublic Preferences getPreferences() {\n\t\treturn preferences;\n\t}\n\n\tpublic Properties getProperties() {\n\t\treturn properties;\n\t}\n\n\tpublic Cursor getCursor() {\n\t\treturn cursor;\n\t}\n\n\tpublic Color getBackground() {\n\t\treturn background;\n\t}\n\n\tpublic JProgressBar getProgressBar() {\n\t\treturn progressBar;\n\t}\n\n\tpublic JList<File> getLeftSubtitles() {\n\t\treturn leftSubtitles;\n\t}\n\n\tpublic JList<File> getRightSubtitles() {\n\t\treturn rightSubtitles;\n\t}\n\n\tpublic JTextField getOutputFolder() {\n\t\treturn outputFolder;\n\t}\n\n\tpublic ExceptionDialog getException() {\n\t\treturn exception;\n\t}\n\n\tpublic void setException(ExceptionDialog exception) {\n\t\tthis.exception = exception;\n\t}\n\n\tpublic HelpPlayerDialog getHelpPlayer() {\n\t\treturn helpPlayer;\n\t}\n\n\tpublic HelpTimingDialog getHelpTiming() {\n\t\treturn helpTiming;\n\t}\n\n\tpublic HelpOutputDialog getHelpOutput() {\n\t\treturn helpOutput;\n\t}\n\n\tpublic HelpTranslationDialog getHelpTranslation() {\n\t\treturn helpTranslation;\n\t}\n\n\tpublic HelpSubtitlesDialog getHelpSubtitles() {\n\t\treturn helpSubtitles;\n\t}\n\n\tpublic void setHelpPlayer(HelpPlayerDialog helpPlayer) {\n\t\tthis.helpPlayer = helpPlayer;\n\t}\n\n\tpublic void setHelpTiming(HelpTimingDialog helpTiming) {\n\t\tthis.helpTiming = helpTiming;\n\t}\n\n\tpublic void setHelpOutput(HelpOutputDialog helpOutput) {\n\t\tthis.helpOutput = helpOutput;\n\t}\n\n\tpublic void setHelpTranslation(HelpTranslationDialog helpTranslation) {\n\t\tthis.helpTranslation = helpTranslation;\n\t}\n\n\tpublic void setHelpSubtitles(HelpSubtitlesDialog helpSubtitles) {\n\t\tthis.helpSubtitles = helpSubtitles;\n\t}\n\n\tpublic KeyTranslationDialog getKeyTranslationDialog() {\n\t\treturn keyTranslationDialog;\n\t}\n\n\tpublic void setKeyTranslationDialog(\n\t\t\tKeyTranslationDialog keyTranslationDialog) {\n\t\tthis.keyTranslationDialog = keyTranslationDialog;\n\t}\n\n\tpublic Menu getMenu() {\n\t\treturn menu;\n\t}\n\n\tpublic JButton getMergeButton() {\n\t\treturn mergeButton;\n\t}\n\n\t/**\n\t * Launch the application.\n\t * \n\t * @throws IOException\n\t */\n\tpublic static void main(String[] args) throws IOException {\n\t\tnew DualSub();\n\t}\n}", "public class DualSrt {\n\n\tprivate static final Logger log = LoggerFactory.getLogger(DualSrt.class);\n\n\tprivate TreeMap<String, Entry[]> subtitles;\n\n\tprivate int signatureGap;\n\tprivate int signatureTime;\n\tprivate int gap;\n\tprivate int desync;\n\tprivate int extension;\n\tprivate boolean extend;\n\tprivate boolean progressive;\n\n\tprivate final String SPACE_HTML = \"&nbsp;\";\n\n\tpublic DualSrt(Properties properties, int desync, boolean extend,\n\t\t\tint extension, boolean progressive) {\n\t\tthis.extend = extend;\n\t\tthis.extension = extension;\n\t\tthis.progressive = progressive;\n\n\t\tthis.subtitles = new TreeMap<String, Entry[]>();\n\n\t\tthis.signatureGap = Integer\n\t\t\t\t.parseInt(properties.getProperty(\"signatureGap\")); // seconds\n\t\tthis.signatureTime = Integer\n\t\t\t\t.parseInt(properties.getProperty(\"signatureTime\")); // seconds\n\t\tthis.gap = Integer.parseInt(properties.getProperty(\"gap\")); // milliseconds\n\t\tthis.desync = desync;\n\t}\n\n\tpublic void addEntry(String time, Entry[] entries) {\n\t\tthis.subtitles.put(time, entries);\n\t}\n\n\tpublic void addAll(Map<String, Entry> allSubs) {\n\t\tfor (String t : allSubs.keySet()) {\n\t\t\taddEntry(t, new Entry[] { allSubs.get(t) });\n\t\t}\n\t}\n\n\tpublic void log() {\n\t\tString left = null, right = null, line = \"\";\n\t\tfor (String time : subtitles.keySet()) {\n\t\t\tfor (int i = 0; i < Math.max(subtitles.get(time)[0].size(),\n\t\t\t\t\tsubtitles.get(time)[1].size()); i++) {\n\t\t\t\tleft = i < subtitles.get(time)[0].size()\n\t\t\t\t\t\t? subtitles.get(time)[0].get(i)\n\t\t\t\t\t\t: SrtUtils.getBlankLine();\n\t\t\t\tright = i < subtitles.get(time)[1].size()\n\t\t\t\t\t\t? subtitles.get(time)[1].get(i)\n\t\t\t\t\t\t: SrtUtils.getBlankLine();\n\t\t\t\tline = left + right;\n\t\t\t\tlog.info(time + \" \" + line + \" \" + SrtUtils.getWidth(line));\n\t\t\t}\n\t\t\tlog.info(\"\");\n\t\t}\n\t}\n\n\tprivate void addPadding() {\n\t\tMap<String, Entry[]> output = new TreeMap<String, Entry[]>();\n\t\tEntry[] newEntry;\n\n\t\tfor (String t : subtitles.keySet()) {\n\t\t\tnewEntry = new Entry[2];\n\t\t\tfor (int i = 0; i < 2; i++) {\n\t\t\t\tif (isLong(subtitles.get(t)[i])) {\n\t\t\t\t\tnewEntry[i] = this.splitEntry(subtitles.get(t)[i]);\n\t\t\t\t} else {\n\t\t\t\t\tnewEntry[i] = this.noSplitEntry(subtitles.get(t)[i]);\n\t\t\t\t}\n\t\t\t\toutput.put(t, newEntry);\n\t\t\t}\n\t\t}\n\t\tsubtitles = new TreeMap<String, Entry[]>(output);\n\t}\n\n\t/**\n\t * It checks whether or not an entry (collection of entries) is long (width\n\t * upper than half_width)\n\t * \n\t * @param entry\n\t * @return\n\t */\n\tprivate boolean isLong(Entry entry) {\n\t\tboolean split = false;\n\t\tfloat width;\n\t\tfor (int i = 0; i < entry.size(); i++) {\n\t\t\twidth = SrtUtils.getWidth(entry.get(i));\n\t\t\tif (width > SrtUtils.getHalfWidth()) {\n\t\t\t\tsplit = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn split;\n\t}\n\n\t/**\n\t * It converts and entry adding the padding and splitting lines.\n\t * \n\t * @param entry\n\t * @return\n\t */\n\tprivate Entry splitEntry(Entry entry) {\n\t\tEntry newEntry = new Entry();\n\n\t\tString append = \"\";\n\t\tfor (int i = 0; i < entry.size(); i++) {\n\t\t\tappend += entry.get(i) + SrtUtils.getSpace();\n\t\t}\n\t\tappend = append.trim();\n\t\tString[] words = append.split(SrtUtils.getSpace());\n\n\t\tList<String> ensuredArray = ensureArray(words);\n\n\t\tString newLine = \"\";\n\t\tfor (int i = 0; i < ensuredArray.size(); i++) {\n\t\t\tif (SrtUtils.getWidth(newLine + ensuredArray.get(i)) < SrtUtils\n\t\t\t\t\t.getHalfWidth()) {\n\t\t\t\tnewLine += ensuredArray.get(i) + SrtUtils.getSpace();\n\t\t\t} else {\n\t\t\t\tnewEntry.add(convertLine(newLine.trim()));\n\t\t\t\tnewLine = ensuredArray.get(i) + SrtUtils.getSpace();\n\t\t\t}\n\t\t}\n\t\tif (!newLine.isEmpty()) {\n\t\t\tnewEntry.add(convertLine(newLine.trim()));\n\t\t}\n\n\t\treturn newEntry;\n\t}\n\n\t/**\n\t * It converts and entry adding the padding but without splitting lines.\n\t * \n\t * @param entry\n\t * @return\n\t */\n\tprivate Entry noSplitEntry(Entry entry) {\n\t\tEntry newEntry = new Entry(entry);\n\t\tfor (int i = 0; i < entry.size(); i++) {\n\t\t\tnewEntry.set(i, convertLine(entry.get(i)));\n\t\t}\n\t\treturn newEntry;\n\t}\n\n\t/**\n\t * Ensures that each word in the arrays in no longer than MAXWIDTH\n\t * \n\t * @param words\n\t * @return\n\t */\n\tprivate List<String> ensureArray(String[] words) {\n\t\tList<String> ensured = new LinkedList<String>();\n\t\tfor (String s : words) {\n\t\t\tif (SrtUtils.getWidth(s) <= SrtUtils.getHalfWidth()) {\n\t\t\t\tensured.add(s);\n\t\t\t} else {\n\t\t\t\tint sLength = s.length();\n\t\t\t\tensured.add(s.substring(0, sLength / 2));\n\t\t\t\tensured.add(s.substring(sLength / 2, sLength / 2));\n\t\t\t}\n\t\t}\n\t\treturn ensured;\n\t}\n\n\t/**\n\t * It adds the padding (SEPARATOR + SPACEs) to a single line.\n\t * \n\t * @param line\n\t * @return\n\t */\n\tprivate String convertLine(String line) {\n\t\tfloat width = SrtUtils.getWidth(line);\n\t\tdouble diff = ((SrtUtils.getHalfWidth() - width)\n\t\t\t\t/ SrtUtils.getSpaceWidth()) / 2;\n\t\tdouble rest = diff % 1;\n\t\tint numSpaces = (int) Math.floor(diff);\n\t\tString additional = (rest >= 0.5) ? SrtUtils.getPadding() : \"\";\n\n\t\tif (numSpaces < 0) {\n\t\t\tnumSpaces = 0;\n\t\t}\n\t\tString newLine = SrtUtils.getSeparator()\n\t\t\t\t+ SrtUtils.repeat(SrtUtils.getPadding(), numSpaces + 1)\n\t\t\t\t+ additional + line\n\t\t\t\t+ SrtUtils.repeat(SrtUtils.getPadding(), numSpaces + 1)\n\t\t\t\t+ SrtUtils.getSeparator();\n\n\t\treturn newLine;\n\t}\n\n\tpublic void processDesync(String time, Entry desyncEntry)\n\t\t\tthrows ParseException {\n\t\tTreeMap<String, Entry[]> newSubtitles = new TreeMap<String, Entry[]>();\n\n\t\tDate inTime = SrtUtils.getInitTime(time);\n\t\tDate enTime = SrtUtils.getEndTime(time);\n\t\tlong initTime = inTime != null ? inTime.getTime() : 0;\n\t\tlong endTime = enTime != null ? enTime.getTime() : 0;\n\t\tlong iTime, jTime;\n\t\tint top = 0, down = subtitles.keySet().size();\n\t\tboolean topOver = false, downOver = false;\n\t\tint from, to;\n\n\t\tfor (String t : subtitles.keySet()) {\n\t\t\tinTime = SrtUtils.getInitTime(time);\n\t\t\tenTime = SrtUtils.getEndTime(time);\n\n\t\t\t// Added to ensure format\n\t\t\tif (!t.contains(\"-->\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tiTime = inTime != null ? SrtUtils.getInitTime(t).getTime() : 0;\n\t\t\tjTime = enTime != null ? SrtUtils.getEndTime(t).getTime() : 0;\n\n\t\t\tif (iTime <= initTime) {\n\t\t\t\ttop++;\n\t\t\t}\n\t\t\tif (jTime >= endTime) {\n\t\t\t\tdown--;\n\t\t\t}\n\t\t\tif (iTime <= initTime && jTime >= initTime) {\n\t\t\t\ttopOver = true;\n\t\t\t}\n\t\t\tif (iTime <= endTime && jTime >= endTime) {\n\t\t\t\tdownOver = true;\n\t\t\t}\n\t\t}\n\t\tfrom = top - 1 + (topOver ? 0 : 1);\n\t\tto = down - (downOver ? 0 : 1);\n\n\t\tlog.debug(time + \" TOP \" + top + \" DOWN \" + down + \" TOPOVER \" + topOver\n\t\t\t\t+ \" DOWNOVER \" + downOver + \" SIZE \" + subtitles.size()\n\t\t\t\t+ \" FROM \" + from + \" TO \" + to + \" \"\n\t\t\t\t+ desyncEntry.getSubtitleLines());\n\t\tString mixedTime = mixTime(initTime, endTime, from, to);\n\t\tlog.debug(mixedTime);\n\n\t\tEntry newEntryLeft = new Entry();\n\t\tEntry newEntryRight = new Entry();\n\t\tfor (int i = from; i <= to; i++) {\n\t\t\tnewEntryLeft\n\t\t\t\t\t.addAll(subtitles.get(subtitles.keySet().toArray()[i])[0]);\n\t\t\tnewEntryRight\n\t\t\t\t\t.addAll(subtitles.get(subtitles.keySet().toArray()[i])[1]);\n\t\t}\n\t\tnewEntryRight.addAll(desyncEntry);\n\n\t\tif (top != 0) {\n\t\t\tnewSubtitles.putAll(subtitles.subMap(subtitles.firstKey(), true,\n\t\t\t\t\t(String) subtitles.keySet().toArray()[top - 1], !topOver));\n\t\t}\n\t\tnewSubtitles.put(mixedTime,\n\t\t\t\tnew Entry[] { newEntryLeft, newEntryRight });\n\t\tif (down != subtitles.size()) {\n\t\t\tnewSubtitles.putAll(subtitles.subMap(\n\t\t\t\t\t(String) subtitles.keySet().toArray()[down], !downOver,\n\t\t\t\t\tsubtitles.lastKey(), true));\n\t\t}\n\n\t\tsubtitles = newSubtitles;\n\t}\n\n\tprivate String mixTime(long initTime, long endTime, int from, int to)\n\t\t\tthrows ParseException {\n\n\t\tlong initCandidate = initTime;\n\t\tlong endCandidate = endTime;\n\t\tlong initFromTime = initTime;\n\t\tlong endToTime = endTime;\n\n\t\tif (to > 0 && to >= from) {\n\t\t\tif (from < subtitles.size()) {\n\t\t\t\tDate iTime = SrtUtils.getInitTime(\n\t\t\t\t\t\t(String) subtitles.keySet().toArray()[from]);\n\t\t\t\tif (iTime != null) {\n\t\t\t\t\tinitFromTime = iTime.getTime();\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (to < subtitles.size()) {\n\t\t\t\tDate eTime = SrtUtils\n\t\t\t\t\t\t.getEndTime((String) subtitles.keySet().toArray()[to]);\n\t\t\t\tif (eTime != null) {\n\t\t\t\t\tendToTime = eTime.getTime();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tswitch (getDesync()) {\n\t\t\tcase 0:\n\t\t\t\t// Left\n\t\t\t\tinitCandidate = initFromTime;\n\t\t\t\tendCandidate = endToTime;\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\t// Right\n\t\t\t\tinitCandidate = initTime;\n\t\t\t\tendCandidate = endTime;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\t// Max\n\t\t\t\tinitCandidate = Math.min(initTime, initFromTime);\n\t\t\t\tendCandidate = Math.max(endTime, endToTime);\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\t// Min\n\t\t\t\tinitCandidate = Math.max(initTime, initFromTime);\n\t\t\t\tendCandidate = Math.min(endTime, endToTime);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn SrtUtils.createSrtTime(new Date(initCandidate),\n\t\t\t\tnew Date(endCandidate));\n\t}\n\n\t/**\n\t * It writes a new subtitle file (SRT) from a subtitle map.\n\t * \n\t * @param subs\n\t * @param fileOuput\n\t * @throws IOException\n\t * @throws ParseException\n\t */\n\tpublic void writeSrt(String fileOuput, String charsetStr, boolean translate,\n\t\t\tboolean merge) throws IOException, ParseException {\n\n\t\tboolean horizontal = SrtUtils.isHorizontal();\n\t\tif (!horizontal && (!translate || (translate & merge))) {\n\t\t\taddPadding();\n\t\t}\n\t\tif (extend) {\n\t\t\tshiftSubs(extension, progressive);\n\t\t}\n\n\t\tString blankLine = horizontal ? \"\" : SrtUtils.getBlankLine();\n\n\t\tFileOutputStream fileOutputStream = new FileOutputStream(\n\t\t\t\tnew File(fileOuput));\n\t\tFileChannel fileChannel = fileOutputStream.getChannel();\n\n\t\tCharset charset = Charset.forName(charsetStr);\n\t\tCharsetEncoder encoder = charset.newEncoder();\n\t\tencoder.onMalformedInput(CodingErrorAction.IGNORE);\n\t\tencoder.onUnmappableCharacter(CodingErrorAction.IGNORE);\n\n\t\tCharBuffer uCharBuffer;\n\t\tByteBuffer byteBuffer;\n\n\t\tif (horizontal) {\n\t\t\tfor (String key : subtitles.keySet()) {\n\t\t\t\tEntry[] entries = subtitles.get(key);\n\t\t\t\tfor (int j = 0; j < entries.length; j++) {\n\t\t\t\t\tList<String> subtitleLines = entries[j].getSubtitleLines();\n\t\t\t\t\tString newLine = \"\";\n\t\t\t\t\tfor (String s : subtitleLines) {\n\t\t\t\t\t\tnewLine += s + \" \";\n\t\t\t\t\t}\n\t\t\t\t\tsubtitleLines.clear();\n\t\t\t\t\tsubtitleLines.add(newLine.trim());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tString left = \"\", right = \"\", time = \"\";\n\t\tString separator = SrtUtils.getSeparator().trim().isEmpty() ? SPACE_HTML\n\t\t\t\t: SrtUtils.getSeparator();\n\t\tString horizontalSeparator = SrtUtils.EOL\n\t\t\t\t+ (SrtUtils.isUsingSeparator() ? separator + SrtUtils.EOL : \"\");\n\t\tfor (int j = 0; j < subtitles.keySet().size(); j++) {\n\t\t\ttime = (String) subtitles.keySet().toArray()[j];\n\t\t\tbyteBuffer = ByteBuffer.wrap((String.valueOf(j + 1) + SrtUtils.EOL)\n\t\t\t\t\t.getBytes(Charset.forName(charsetStr)));\n\t\t\tfileChannel.write(byteBuffer);\n\t\t\tbyteBuffer = ByteBuffer.wrap((time + SrtUtils.EOL)\n\t\t\t\t\t.getBytes(Charset.forName(charsetStr)));\n\t\t\tfileChannel.write(byteBuffer);\n\n\t\t\tint limit = subtitles.get(time).length > 1\n\t\t\t\t\t? Math.max(subtitles.get(time)[0].size(),\n\t\t\t\t\t\t\tsubtitles.get(time)[1].size())\n\t\t\t\t\t: subtitles.get(time)[0].size();\n\t\t\tfor (int i = 0; i < limit; i++) {\n\t\t\t\tleft = i < subtitles.get(time)[0].size()\n\t\t\t\t\t\t? subtitles.get(time)[0].get(i) : blankLine;\n\t\t\t\tif (subtitles.get(time).length > 1) {\n\t\t\t\t\tright = i < subtitles.get(time)[1].size()\n\t\t\t\t\t\t\t? subtitles.get(time)[1].get(i) : blankLine;\n\t\t\t\t}\n\n\t\t\t\tString leftColor = SrtUtils.getParsedLeftColor();\n\t\t\t\tif (leftColor != null) {\n\t\t\t\t\tleft = String.format(leftColor, left);\n\t\t\t\t}\n\t\t\t\tString rightColor = SrtUtils.getParsedRightColor();\n\t\t\t\tif (rightColor != null) {\n\t\t\t\t\tright = String.format(rightColor, right);\n\t\t\t\t}\n\n\t\t\t\tif (horizontal) {\n\t\t\t\t\tuCharBuffer = CharBuffer.wrap(\n\t\t\t\t\t\t\tleft + horizontalSeparator + right + SrtUtils.EOL);\n\t\t\t\t} else {\n\t\t\t\t\tuCharBuffer = CharBuffer.wrap(left + right + SrtUtils.EOL);\n\t\t\t\t}\n\t\t\t\tbyteBuffer = encoder.encode(uCharBuffer);\n\n\t\t\t\tlog.debug(new String(byteBuffer.array(),\n\t\t\t\t\t\tCharset.forName(charsetStr)));\n\n\t\t\t\tfileChannel.write(byteBuffer);\n\t\t\t}\n\t\t\tbyteBuffer = ByteBuffer\n\t\t\t\t\t.wrap(SrtUtils.EOL.getBytes(Charset.forName(charsetStr)));\n\t\t\tfileChannel.write(byteBuffer);\n\t\t}\n\n\t\tfor (String s : signature(translate, merge)) {\n\t\t\tbyteBuffer = ByteBuffer.wrap(\n\t\t\t\t\t(s + SrtUtils.EOL).getBytes(Charset.forName(charsetStr)));\n\t\t\tfileChannel.write(byteBuffer);\n\t\t}\n\t\tbyteBuffer = ByteBuffer\n\t\t\t\t.wrap(SrtUtils.EOL.getBytes(Charset.forName(charsetStr)));\n\t\tfileChannel.write(byteBuffer);\n\t\tfileChannel.close();\n\n\t\tfileOutputStream.close();\n\t}\n\n\t/**\n\t * Adds an entry in the end of the merged subtitles with the program author.\n\t * \n\t * @param subs\n\t * @throws ParseException\n\t */\n\tprivate List<String> signature(boolean translate, boolean merge)\n\t\t\tthrows ParseException {\n\t\tString lastEntryTime = (String) subtitles.keySet()\n\t\t\t\t.toArray()[subtitles.keySet().size() - 1];\n\t\tDate end = SrtUtils.getEndTime(lastEntryTime);\n\t\tfinal Date newDateInit = new Date(end.getTime() + signatureGap);\n\t\tfinal Date newDateEnd = new Date(end.getTime() + signatureTime);\n\t\tString newTime = SrtUtils.createSrtTime(newDateInit, newDateEnd);\n\t\tList<String> signature = new LinkedList<String>();\n\t\tsignature.add(String.valueOf(subtitles.size() + 1));\n\t\tsignature.add(newTime);\n\t\tString signatureText = \"\";\n\t\tif (translate & merge) {\n\t\t\tsignatureText = I18N.getText(\"Merger.signatureboth.text\");\n\t\t} else if (translate & !merge) {\n\t\t\tsignatureText = I18N.getText(\"Merger.signaturetranslated.text\");\n\t\t} else {\n\t\t\tsignatureText = I18N.getText(\"Merger.signature.text\");\n\t\t}\n\t\tsignature.add(signatureText);\n\t\tsignature.add(I18N.getText(\"Merger.signature.url\"));\n\t\treturn signature;\n\t}\n\n\t/**\n\t * This method extends the duration of each subtitle 1 second (EXTENSION).\n\t * If the following subtitle is located inside that extension, the extension\n\t * will be only until the beginning of this next subtitle minus 20\n\t * milliseconds (GAP).\n\t * \n\t * @throws ParseException\n\t */\n\tpublic void shiftSubs(int extension, boolean progressive)\n\t\t\tthrows ParseException {\n\t\tTreeMap<String, Entry[]> newSubtitles = new TreeMap<String, Entry[]>();\n\n\t\tString timeBefore = \"\";\n\t\tDate init;\n\t\tDate tsBeforeInit = new Date();\n\t\tDate tsBeforeEnd = new Date();\n\t\tString newTime = \"\";\n\t\tEntry[] entries;\n\t\tint shiftTime = extension;\n\n\t\tfor (String t : subtitles.keySet()) {\n\t\t\tif (!timeBefore.isEmpty()) {\n\t\t\t\tinit = SrtUtils.getInitTime(t);\n\t\t\t\tif (init != null) {\n\t\t\t\t\tentries = subtitles.get(timeBefore);\n\t\t\t\t\tif (progressive) {\n\t\t\t\t\t\tshiftTime = entries.length > 1 ? extension\n\t\t\t\t\t\t\t\t* Math.max(entries[0].size(), entries[1].size())\n\t\t\t\t\t\t\t\t: entries[0].size();\n\t\t\t\t\t}\n\t\t\t\t\tif (tsBeforeEnd.getTime() + shiftTime < init.getTime()) {\n\t\t\t\t\t\tnewTime = SrtUtils.createSrtTime(tsBeforeInit,\n\t\t\t\t\t\t\t\tnew Date(tsBeforeEnd.getTime() + shiftTime));\n\t\t\t\t\t\tlog.debug(\"Shift \" + timeBefore + \" to \" + newTime\n\t\t\t\t\t\t\t\t+ \" ... extension \" + shiftTime);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnewTime = SrtUtils.createSrtTime(tsBeforeInit,\n\t\t\t\t\t\t\t\tnew Date(init.getTime() - gap));\n\t\t\t\t\t\tlog.debug(\"Shift \" + timeBefore + \" to \" + newTime);\n\t\t\t\t\t}\n\t\t\t\t\tnewSubtitles.put(newTime, entries);\n\t\t\t\t}\n\t\t\t}\n\t\t\ttimeBefore = t;\n\t\t\ttsBeforeInit = SrtUtils.getInitTime(timeBefore);\n\t\t\ttsBeforeEnd = SrtUtils.getEndTime(timeBefore);\n\t\t\tif (tsBeforeInit == null || tsBeforeEnd == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\t// Last entry\n\t\tentries = subtitles.get(timeBefore);\n\t\tif (entries != null && tsBeforeInit != null && tsBeforeEnd != null) {\n\t\t\tif (progressive) {\n\t\t\t\textension *= entries.length > 1\n\t\t\t\t\t\t? Math.max(entries[0].size(), entries[1].size())\n\t\t\t\t\t\t: entries[0].size();\n\t\t\t}\n\t\t\tnewTime = SrtUtils.createSrtTime(tsBeforeInit,\n\t\t\t\t\tnew Date(tsBeforeEnd.getTime() + extension));\n\t\t\tnewSubtitles.put(newTime, entries);\n\t\t}\n\n\t\tsubtitles = newSubtitles;\n\t}\n\n\tpublic int size() {\n\t\treturn subtitles.size();\n\t}\n\n\tpublic int getDesync() {\n\t\treturn desync;\n\t}\n\n}", "public class Merger {\n\n\tprivate static final Logger log = LoggerFactory.getLogger(Merger.class);\n\n\tprivate String outputFolder;\n\tprivate int extension;\n\tprivate boolean extend;\n\tprivate boolean progressive;\n\tprivate Properties properties;\n\tprivate String charset;\n\tprivate int desynch;\n\tprivate boolean translate;\n\tprivate boolean merge;\n\n\tpublic Merger(String outputFolder, boolean extend, int extension,\n\t\t\tboolean progressive, Properties properties, String charset,\n\t\t\tint desynch, boolean translate, boolean merge) {\n\t\tthis.outputFolder = outputFolder;\n\t\tthis.extend = extend;\n\t\t// Extension should be in ms, and GUI asks for it in seconds\n\t\tthis.extension = 1000 * extension;\n\t\tthis.progressive = progressive;\n\t\tthis.properties = properties;\n\t\tthis.charset = charset;\n\t\tthis.desynch = desynch;\n\t\tthis.translate = translate;\n\t\tthis.merge = merge;\n\t}\n\n\tpublic DualSrt mergeSubs(Srt srtLeft, Srt srtRigth) throws ParseException {\n\t\tDualSrt dualSrt = new DualSrt(properties, getDesynch(), extend,\n\t\t\t\textension, progressive);\n\n\t\tMap<String, Entry> subtitlesLeft = new TreeMap<String, Entry>(\n\t\t\t\tsrtLeft.getSubtitles());\n\t\tMap<String, Entry> subtitlesRight = new TreeMap<String, Entry>(\n\t\t\t\tsrtRigth.getSubtitles());\n\n\t\tif (subtitlesLeft.isEmpty() || subtitlesRight.isEmpty()) {\n\t\t\tif (subtitlesLeft.isEmpty()) {\n\t\t\t\tdualSrt.addAll(subtitlesRight);\n\t\t\t} else if (subtitlesRight.isEmpty()) {\n\t\t\t\tdualSrt.addAll(subtitlesLeft);\n\t\t\t}\n\t\t} else {\n\t\t\tfor (String t : subtitlesLeft.keySet()) {\n\t\t\t\tif (subtitlesRight.containsKey(t)) {\n\t\t\t\t\tdualSrt.addEntry(t, new Entry[] { subtitlesLeft.get(t),\n\t\t\t\t\t\t\tsubtitlesRight.get(t) });\n\t\t\t\t\tsubtitlesRight.remove(t);\n\t\t\t\t} else {\n\t\t\t\t\tdualSrt.addEntry(t, new Entry[] { subtitlesLeft.get(t),\n\t\t\t\t\t\t\tnew Entry() });\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!subtitlesRight.isEmpty()) {\n\t\t\t\tfor (String t : subtitlesRight.keySet()) {\n\t\t\t\t\tlog.debug(\"Desynchronization on \" + t + \" \"\n\t\t\t\t\t\t\t+ subtitlesRight.get(t).subtitleLines);\n\t\t\t\t\tdualSrt.processDesync(t, subtitlesRight.get(t));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn dualSrt;\n\t}\n\n\tpublic String getMergedFileName(Srt subs1, Srt subs2) {\n\t\tString mergedFileName = \"\";\n\t\tif (translate) {\n\t\t\tSrt srt = subs1.getFileName() == null ? subs2 : subs1;\n\t\t\tFile file = new File(srt.getFileName());\n\t\t\tString fileName = file.getName();\n\t\t\tint i = fileName.lastIndexOf('.');\n\t\t\ti = i == -1 ? fileName.length() - 1 : i;\n\t\t\tString extension = fileName.substring(i);\n\t\t\tmergedFileName = getOutputFolder() + File.separator\n\t\t\t\t\t+ fileName.substring(0, i);\n\t\t\tif (merge) {\n\t\t\t\tmergedFileName += \" \" + I18N.getText(\"Merger.merged.text\");\n\t\t\t} else {\n\t\t\t\tmergedFileName += \" \" + I18N.getText(\"Merger.translated.text\");\n\t\t\t}\n\t\t\tmergedFileName += extension;\n\t\t} else {\n\t\t\tmergedFileName = getOutputFolder() + File.separator\n\t\t\t\t\t+ compareNames(subs1.getFileName(), subs2.getFileName());\n\t\t}\n\t\treturn mergedFileName;\n\t}\n\n\t/**\n\t * It compares the input names of the SRTs (files) and get the part of those\n\t * name which is the same.\n\t * \n\t * @param str1\n\t * @param str2\n\t * @return\n\t */\n\tprivate String compareNames(String str1, String str2) {\n\t\tstr1 = str1.substring(str1.lastIndexOf(File.separator) + 1).replaceAll(\n\t\t\t\tSrtUtils.SRT_EXT, \"\");\n\t\tstr2 = str2.substring(str2.lastIndexOf(File.separator) + 1).replaceAll(\n\t\t\t\tSrtUtils.SRT_EXT, \"\");\n\n\t\tList<String> set1 = new ArrayList<String>(Arrays.asList(str1\n\t\t\t\t.split(\" |_|\\\\.\")));\n\t\tList<String> set2 = new ArrayList<String>(Arrays.asList(str2\n\t\t\t\t.split(\" |_|\\\\.\")));\n\t\tset1.retainAll(set2);\n\n\t\tStringBuilder sb = new StringBuilder();\n\t\tfor (String s : set1) {\n\t\t\tsb.append(s).append(SrtUtils.getSpace());\n\t\t}\n\t\tString finalName = sb.toString().trim();\n\t\tif (finalName.isEmpty()) {\n\t\t\tfinalName = I18N.getText(\"Merger.finalName.text\").trim();\n\t\t}\n\t\treturn finalName + SrtUtils.SRT_EXT;\n\t}\n\n\tpublic String getOutputFolder() {\n\t\treturn outputFolder;\n\t}\n\n\tpublic boolean isProgressive() {\n\t\treturn progressive;\n\t}\n\n\tpublic void setCharset(String charset) {\n\t\tthis.charset = charset;\n\t}\n\n\tpublic String getCharset() {\n\t\treturn charset;\n\t}\n\n\tpublic boolean isTranslate() {\n\t\treturn translate;\n\t}\n\n\tpublic boolean isMerge() {\n\t\treturn merge;\n\t}\n\n\t/**\n\t * 0 = left; 1 = right; 2 = max; 3 = min\n\t * \n\t * @return\n\t */\n\tpublic int getDesynch() {\n\t\treturn desynch;\n\t}\n\n}", "public class Srt {\n\n\tprivate static final Logger log = LoggerFactory.getLogger(Merger.class);\n\n\tprivate Map<String, Entry> subtitles;\n\tprivate String fileName;\n\tprivate String charset;\n\n\tpublic Srt(String fileName) throws IOException {\n\t\tthis.fileName = fileName;\n\t\tthis.subtitles = new TreeMap<String, Entry>();\n\t\tthis.readSrt(fileName);\n\t}\n\n\tpublic Srt(Srt inputSrt, String fromLang, String toLang, String charset,\n\t\t\tDualSub parent) throws IOException {\n\t\tthis.subtitles = new TreeMap<String, Entry>();\n\t\tMap<String, Entry> subtitlesToTranslate = inputSrt.getSubtitles();\n\t\tString lineToTranslate;\n\t\tEntry translatedEntry;\n\n\t\tPreferences preferences;\n\t\tProperties properties;\n\n\t\tif (parent != null) {\n\t\t\tpreferences = parent.getPreferences();\n\t\t\tproperties = parent.getProperties();\n\t\t} else {\n\t\t\tpreferences = Preferences.userNodeForPackage(DualSub.class);\n\n\t\t\tproperties = new Properties();\n\t\t\tInputStream inputStream = Thread.currentThread()\n\t\t\t\t\t.getContextClassLoader()\n\t\t\t\t\t.getResourceAsStream(\"dualsub.properties\");\n\t\t\tReader reader = new InputStreamReader(inputStream,\n\t\t\t\t\tCharset.ISO88591);\n\t\t\tproperties.load(reader);\n\t\t}\n\n\t\tTranslator.getInstance().setPreferences(preferences);\n\n\t\tList<String> inputLines = new ArrayList<String>();\n\n\t\tfor (String time : subtitlesToTranslate.keySet()) {\n\t\t\tlineToTranslate = \"\";\n\t\t\tfor (String line : subtitlesToTranslate.get(time)\n\t\t\t\t\t.getSubtitleLines()) {\n\t\t\t\tlineToTranslate += line + \" \";\n\t\t\t}\n\t\t\tinputLines.add(lineToTranslate);\n\t\t}\n\n\t\tint max = Integer\n\t\t\t\t.parseInt(properties.getProperty(\"maxTranslationBatch\"));\n\t\tint size = inputLines.size();\n\t\tint rounds = 1 + (size / max);\n\t\tlog.trace(\"Number of rounds {} (total lines {})\", rounds, size);\n\n\t\tList<String> translations = new ArrayList<String>();\n\t\tfor (int i = 0; i < rounds; i++) {\n\t\t\tint fromIndex = i * max;\n\t\t\tint toIndex = fromIndex + max;\n\t\t\tif (toIndex > size) {\n\t\t\t\ttoIndex = size;\n\t\t\t}\n\n\t\t\tlog.trace(\"Round {}/{} ... from {} to {}\", i + 1, rounds, fromIndex,\n\t\t\t\t\ttoIndex);\n\n\t\t\tList<String> roundTranslation = Translator.getInstance().translate(\n\t\t\t\t\tinputLines.subList(fromIndex, toIndex), fromLang, toLang);\n\n\t\t\tlog.trace(\"Adding {} translation to result\",\n\t\t\t\t\troundTranslation.size());\n\t\t\tlog.trace(\"Translation list {} \", roundTranslation);\n\t\t\ttranslations.addAll(roundTranslation);\n\t\t}\n\n\t\tIterator<String> iterator = translations.iterator();\n\n\t\tfor (String time : subtitlesToTranslate.keySet()) {\n\t\t\ttranslatedEntry = new Entry();\n\t\t\ttranslatedEntry.add(iterator.next());\n\t\t\tsubtitles.put(time, translatedEntry);\n\t\t}\n\n\t}\n\n\t/**\n\t * Converts a subtitle file (SRT) into a Map, in which key in the timing of\n\t * each subtitle entry, and the value is a List of String with the content\n\t * of the entry.\n\t * \n\t * @param file\n\t * @throws IOException\n\t */\n\tprivate void readSrt(String file) throws IOException {\n\t\tEntry entry = new Entry();\n\t\tint i = 0;\n\t\tString time = \"\";\n\t\tInputStream isForDetection = readSrtInputStream(file);\n\t\tInputStream isForReading = readSrtInputStream(file);\n\t\tcharset = Charset.detect(isForDetection);\n\t\tlog.info(file + \" detected charset \" + charset);\n\n\t\tBufferedReader br = new BufferedReader(\n\t\t\t\tnew InputStreamReader(isForReading, charset));\n\t\ttry {\n\t\t\tString line = br.readLine();\n\t\t\twhile (line != null) {\n\t\t\t\tif (line.isEmpty()) {\n\t\t\t\t\tif (entry.size() > 0) {\n\t\t\t\t\t\tsubtitles.put(time, entry);\n\t\t\t\t\t\tentry = new Entry();\n\t\t\t\t\t\ti = 0;\n\t\t\t\t\t\ttime = \"\";\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (i == 1) {\n\t\t\t\t\t\ttime = line;\n\t\t\t\t\t}\n\t\t\t\t\tif (i >= 2) {\n\t\t\t\t\t\t// Not adding first two lines of subtitles (index and\n\t\t\t\t\t\t// time)\n\t\t\t\t\t\tif (line.indexOf(SrtUtils.TAG_INIT) != -1\n\t\t\t\t\t\t\t\t&& line.indexOf(SrtUtils.TAG_END) != -1) {\n\t\t\t\t\t\t\tline = removeTags(line);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tentry.add(line);\n\t\t\t\t\t\tlog.debug(line);\n\t\t\t\t\t}\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\tline = br.readLine();\n\t\t\t}\n\t\t} finally {\n\t\t\tbr.close();\n\t\t\tisForReading.close();\n\t\t}\n\t}\n\n\tpublic InputStream readSrtInputStream(String file)\n\t\t\tthrows FileNotFoundException {\n\t\tInputStream inputStream = Thread.currentThread().getContextClassLoader()\n\t\t\t\t.getResourceAsStream(file);\n\t\tif (inputStream == null) {\n\t\t\tinputStream = new BufferedInputStream(new FileInputStream(file));\n\t\t}\n\t\treturn inputStream;\n\t}\n\n\tpublic static String removeTags(String line) {\n\t\tPattern pattern = Pattern.compile(\"<([^>]+)>\");\n\t\tMatcher matcher = pattern.matcher(line);\n\t\treturn matcher.replaceAll(\"\");\n\t}\n\n\tpublic void log() {\n\t\tEntry list;\n\t\tfor (String time : subtitles.keySet()) {\n\t\t\tlist = subtitles.get(time);\n\t\t\tfor (int i = 0; i < list.size(); i++) {\n\t\t\t\tlog.info(time + \" \" + list.get(i) + \" \");\n\t\t\t}\n\t\t\tlog.info(\"\");\n\t\t}\n\t}\n\n\tpublic Map<String, Entry> getSubtitles() {\n\t\treturn subtitles;\n\t}\n\n\tpublic void resetSubtitles() {\n\t\tsubtitles.clear();\n\t}\n\n\tpublic String getFileName() {\n\t\treturn fileName;\n\t}\n\n\tpublic String getCharset() {\n\t\treturn charset;\n\t}\n\n}", "public class SrtUtils {\n\n\tprivate static final Logger log = LoggerFactory.getLogger(Merger.class);\n\n\tprivate static final String SPACE = \" \";\n\tprivate static final String HARD_SPACE = \"\\\\h\";\n\n\tpublic static final String SEP_SRT = \" --> \";\n\tpublic static final String SRT_EXT = \".srt\";\n\tpublic static final String TAG_INIT = \"<\";\n\tpublic static final String TAG_END = \">\";\n\tpublic static final String EOL = \"\\r\\n\";\n\tpublic static final String FONT_INIT = \"<font color=\\\"%s\\\">\";\n\tpublic static final String FONT_END = \"%s</font>\";\n\n\tprivate Font font;\n\tprivate FontMetrics fontMetrics;\n\tprivate float maxWidth;\n\tprivate float separatorWidth;\n\tprivate float spaceWidth;\n\tprivate float halfWidth;\n\tprivate String blankLine;\n\tprivate SimpleDateFormat simpleDateFormat;\n\tprivate String padding;\n\tprivate String separator;\n\tprivate boolean usingSpace;\n\tprivate boolean usingSeparator;\n\tprivate boolean horizontal;\n\tprivate String leftColor;\n\tprivate String rightColor;\n\n\tprivate static SrtUtils singleton = null;\n\n\tpublic static SrtUtils getSingleton() {\n\t\tif (singleton == null) {\n\t\t\tsingleton = new SrtUtils();\n\t\t}\n\t\treturn singleton;\n\t}\n\n\t// Default constructor\n\tpublic SrtUtils() {\n\t}\n\n\t@SuppressWarnings(\"deprecation\")\n\tpublic static void init(String maxWidth, String fontFamily, int fontSize,\n\t\t\tboolean space, boolean separator, String separatorChar, int guard,\n\t\t\tboolean horizontal, String leftColor, String rightColor) {\n\t\tlog.debug(\"maxWidth \" + maxWidth + \" fontFamily \" + fontFamily\n\t\t\t\t+ \" fontSize \" + fontSize + \" space \" + space + \" separator \"\n\t\t\t\t+ separator + \" separatorChar \" + separatorChar + \" guard \"\n\t\t\t\t+ guard);\n\t\tSrtUtils srtUtils = getSingleton();\n\t\tsrtUtils.font = new Font(fontFamily, Font.PLAIN, fontSize);\n\t\tsrtUtils.maxWidth = Float.parseFloat(maxWidth) - guard;\n\t\tsrtUtils.fontMetrics = Toolkit.getDefaultToolkit().getFontMetrics(\n\t\t\t\tsrtUtils.font);\n\t\tsrtUtils.simpleDateFormat = new SimpleDateFormat(\"HH:mm:ss,SSS\");\n\t\tsrtUtils.separator = separator ? separatorChar : \"\";\n\t\tsrtUtils.padding = space ? SrtUtils.SPACE : SrtUtils.HARD_SPACE;\n\t\tsrtUtils.usingSpace = space;\n\t\tsrtUtils.usingSeparator = separator;\n\t\tsrtUtils.horizontal = horizontal;\n\t\tsrtUtils.separatorWidth = separator & !horizontal ? getWidth(srtUtils.separator)\n\t\t\t\t: 0;\n\n\t\t// Even if hard space is used, the width of the padding is the same\n\t\t// as the normal space\n\t\tsrtUtils.spaceWidth = getWidth(SPACE);\n\n\t\t// Gap of two characters (space + separator)\n\t\tsrtUtils.halfWidth = (srtUtils.maxWidth / 2) - 2\n\t\t\t\t* (srtUtils.spaceWidth + srtUtils.separatorWidth);\n\n\t\t// Blank line\n\t\tint numSpaces = (int) Math.round(srtUtils.halfWidth / getSpaceWidth());\n\n\t\tif (separator) {\n\t\t\tsrtUtils.blankLine = SrtUtils.getSeparator()\n\t\t\t\t\t+ repeat(SrtUtils.getPadding(), numSpaces)\n\t\t\t\t\t+ SrtUtils.getSeparator();\n\t\t} else {\n\t\t\tsrtUtils.blankLine = repeat(SrtUtils.getPadding(), numSpaces);\n\t\t}\n\t}\n\n\tpublic static int getWidth(String message) {\n\t\tfinal int width = SrtUtils.getSingleton().fontMetrics\n\t\t\t\t.stringWidth(message);\n\t\tlog.debug(\"getWidth \" + message + \" \" + width);\n\t\treturn width;\n\t}\n\n\t/**\n\t * \n\t * @param str\n\t * @param times\n\t * @return\n\t */\n\tpublic static String repeat(String str, int times) {\n\t\treturn new String(new char[times]).replace(\"\\0\", str);\n\t}\n\n\t/**\n\t * It reads the initial time of a subtitle entry\n\t * \n\t * @param line\n\t * @return\n\t * @throws ParseException\n\t */\n\tpublic static Date getInitTime(String line) throws ParseException {\n\t\tDate out = null;\n\t\tint i = line.indexOf(SrtUtils.SEP_SRT);\n\t\tif (i != -1) {\n\t\t\tString time = line.substring(0, i).trim();\n\t\t\tif (time.length() == 8) {\n\t\t\t\t// Time without milliseconds (e.g. 01:27:40)\n\t\t\t\ttime += \",000\";\n\t\t\t}\n\t\t\tout = SrtUtils.getSingleton().parse(time);\n\t\t}\n\t\treturn out;\n\t}\n\n\t/**\n\t * It reads the ending time of a subtitle entry\n\t * \n\t * @param line\n\t * @return\n\t * @throws ParseException\n\t */\n\tpublic static Date getEndTime(String line) throws ParseException {\n\t\tDate out = null;\n\t\tint i = line.indexOf(SrtUtils.SEP_SRT);\n\t\tif (i != -1) {\n\t\t\tString time = line.substring(i + SrtUtils.SEP_SRT.length());\n\t\t\tif (time.length() == 8) {\n\t\t\t\t// Time without milliseconds (e.g. 01:27:40)\n\t\t\t\ttime += \",000\";\n\t\t\t}\n\t\t\tout = SrtUtils.getSingleton().parse(time);\n\n\t\t}\n\t\treturn out;\n\t}\n\n\tpublic static String createSrtTime(Date dateFrom, Date dateTo) {\n\t\treturn SrtUtils.format(dateFrom) + SrtUtils.SEP_SRT\n\t\t\t\t+ SrtUtils.format(dateTo);\n\t}\n\n\tpublic static Font getFont() {\n\t\treturn SrtUtils.getSingleton().font;\n\t}\n\n\tpublic static float getMaxWidth() {\n\t\treturn SrtUtils.getSingleton().maxWidth;\n\t}\n\n\tpublic static FontMetrics getFontMetrics() {\n\t\treturn SrtUtils.getSingleton().fontMetrics;\n\t}\n\n\tpublic static float getSeparatorWidth() {\n\t\treturn SrtUtils.getSingleton().separatorWidth;\n\t}\n\n\tpublic static float getSpaceWidth() {\n\t\treturn SrtUtils.getSingleton().spaceWidth;\n\t}\n\n\tpublic static float getHalfWidth() {\n\t\treturn SrtUtils.getSingleton().halfWidth;\n\t}\n\n\tpublic static String format(Date date) {\n\t\treturn SrtUtils.getSingleton().simpleDateFormat.format(date);\n\t}\n\n\tpublic Date parse(String date) throws ParseException {\n\t\tDate out = null;\n\t\ttry {\n\t\t\tout = SrtUtils.getSingleton().simpleDateFormat.parse(date);\n\t\t} catch (ParseException e) {\n\t\t\tout = new SimpleDateFormat(\"HH:mm:ss.SSS\").parse(date);\n\t\t}\n\t\treturn out;\n\t}\n\n\tpublic static String getBlankLine() {\n\t\treturn SrtUtils.getSingleton().blankLine;\n\t}\n\n\tpublic static String getSeparator() {\n\t\treturn SrtUtils.getSingleton().separator;\n\t}\n\n\tpublic static String getPadding() {\n\t\treturn SrtUtils.getSingleton().padding;\n\t}\n\n\tpublic static boolean isUsingSpace() {\n\t\treturn SrtUtils.getSingleton().usingSpace;\n\t}\n\n\tpublic static boolean isUsingSeparator() {\n\t\treturn SrtUtils.getSingleton().usingSeparator;\n\t}\n\n\tpublic static String getSpace() {\n\t\treturn SrtUtils.SPACE;\n\t}\n\n\tpublic static boolean isHorizontal() {\n\t\treturn SrtUtils.getSingleton().horizontal;\n\t}\n\n\tpublic static String getLeftColor() {\n\t\treturn SrtUtils.getSingleton().leftColor;\n\t}\n\n\tpublic static String getParsedLeftColor() {\n\t\treturn getLeftColor() != null ? String\n\t\t\t\t.format(FONT_INIT, getLeftColor()) + FONT_END : \"%s\";\n\t}\n\n\tpublic static String getRightColor() {\n\t\treturn SrtUtils.getSingleton().rightColor;\n\t}\n\n\tpublic static String getParsedRightColor() {\n\t\treturn getRightColor() != null ? String.format(FONT_INIT,\n\t\t\t\tgetRightColor()) + FONT_END : \"%s\";\n\t}\n\n\tpublic static void setLeftColor(String leftColor) {\n\t\tSrtUtils.getSingleton().leftColor = leftColor;\n\t}\n\n\tpublic static void setRightColor(String rightColor) {\n\t\tSrtUtils.getSingleton().rightColor = rightColor;\n\t}\n\n}", "public class Language {\n\tpublic static final String AFRIKAANS = \"af\";\n\tpublic static final String ALBANIAN = \"sq\";\n\tpublic static final String ARABIC = \"ar\";\n\tpublic static final String ARMENIAN = \"hy\";\n\tpublic static final String AZERBAIJANI = \"az\";\n\tpublic static final String BASQUE = \"eu\";\n\tpublic static final String BELARUSIAN = \"be\";\n\tpublic static final String BENGALI = \"bn\";\n\tpublic static final String BULGARIAN = \"bg\";\n\tpublic static final String CATALAN = \"ca\";\n\tpublic static final String CHINESE = \"zh-CN\";\n\tpublic static final String CROATIAN = \"hr\";\n\tpublic static final String CZECH = \"cs\";\n\tpublic static final String DANISH = \"da\";\n\tpublic static final String DUTCH = \"nl\";\n\tpublic static final String ENGLISH = \"en\";\n\tpublic static final String ESTONIAN = \"et\";\n\tpublic static final String FILIPINO = \"tl\";\n\tpublic static final String FINNISH = \"fi\";\n\tpublic static final String FRENCH = \"fr\";\n\tpublic static final String GALICIAN = \"gl\";\n\tpublic static final String GEORGIAN = \"ka\";\n\tpublic static final String GERMAN = \"de\";\n\tpublic static final String GREEK = \"el\";\n\tpublic static final String GUJARATI = \"gu\";\n\tpublic static final String HAITIAN_CREOLE = \"ht\";\n\tpublic static final String HEBREW = \"iw\";\n\tpublic static final String HINDI = \"hi\";\n\tpublic static final String HUNGARIAN = \"hu\";\n\tpublic static final String ICELANDIC = \"is\";\n\tpublic static final String INDONESIAN = \"id\";\n\tpublic static final String IRISH = \"ga\";\n\tpublic static final String ITALIAN = \"it\";\n\tpublic static final String JAPANESE = \"ja\";\n\tpublic static final String KANNADA = \"kn\";\n\tpublic static final String KOREAN = \"ko\";\n\tpublic static final String LATIN = \"la\";\n\tpublic static final String LATVIAN = \"lv\";\n\tpublic static final String LITHUANIAN = \"lt\";\n\tpublic static final String MACEDONIAN = \"mk\";\n\tpublic static final String MALAY = \"ms\";\n\tpublic static final String MALTESE = \"mt\";\n\tpublic static final String NORWEGIAN = \"no\";\n\tpublic static final String PERSIAN = \"fa\";\n\tpublic static final String POLISH = \"pl\";\n\tpublic static final String PORTUGUESE = \"pt\";\n\tpublic static final String ROMANIAN = \"ro\";\n\tpublic static final String RUSSIAN = \"ru\";\n\tpublic static final String SERBIAN = \"sr\";\n\tpublic static final String SLOVAK = \"sk\";\n\tpublic static final String SLOVENIAN = \"sl\";\n\tpublic static final String SPANISH = \"es\";\n\tpublic static final String SWAHILI = \"sw\";\n\tpublic static final String SWEDISH = \"sv\";\n\tpublic static final String TAMIL = \"ta\";\n\tpublic static final String TELUGU = \"te\";\n\tpublic static final String THAI = \"th\";\n\tpublic static final String TURKISH = \"tr\";\n\tpublic static final String UKRAINIAN = \"uk\";\n\tpublic static final String URDU = \"ur\";\n\tpublic static final String VIETNAMESE = \"vi\";\n\tpublic static final String WELSH = \"cy\";\n\tpublic static final String YIDDISH = \"yi\";\n\tpublic static final String CHINESE_SIMPLIFIED = \"zh-CN\";\n\tpublic static final String CHINESE_TRADITIONAL = \"zh-TW\";\n\n\tprivate static Language singleton;\n\n\tpublic static Language getInstance() {\n\t\tif (singleton == null) {\n\t\t\tsingleton = new Language();\n\t\t}\n\t\treturn singleton;\n\t}\n\n}", "public class Translator {\n\n\tprivate static final Logger log = LoggerFactory.getLogger(Translator.class);\n\n\tprivate static Translator singleton = null;\n\n\tprivate Preferences preferences;\n\n\tprivate Translate translate;\n\n\tpublic static Translator getInstance() {\n\t\tif (singleton == null) {\n\t\t\tsingleton = new Translator();\n\t\t}\n\t\treturn singleton;\n\t}\n\n\tpublic String translate(String text, String languageFrom,\n\t\t\tString languageTo) {\n\t\tTranslation translation = translate.translate(text,\n\t\t\t\tTranslateOption.sourceLanguage(languageFrom),\n\t\t\t\tTranslateOption.targetLanguage(languageTo));\n\n\t\tString translatedText = translation.getTranslatedText();\n\t\tlog.trace(\"Translating {} [{}] to [{}] ... result={}\", text,\n\t\t\t\tlanguageFrom, languageTo, translatedText);\n\t\treturn translatedText;\n\t}\n\n\tpublic List<String> translate(List<String> text, String languageFrom,\n\t\t\tString languageTo) {\n\t\tList<Translation> translation = translate.translate(text,\n\t\t\t\tTranslateOption.sourceLanguage(languageFrom),\n\t\t\t\tTranslateOption.targetLanguage(languageTo));\n\n\t\tList<String> out = new ArrayList<String>();\n\t\tfor (Translation t : translation) {\n\t\t\tString translatedText = t.getTranslatedText();\n\t\t\tout.add(translatedText);\n\t\t\tlog.trace(\"Translating {} [{}] to [{}] ... result={}\", text,\n\t\t\t\t\tlanguageFrom, languageTo, translatedText);\n\t\t}\n\t\treturn out;\n\t}\n\n\tpublic void setPreferences(Preferences preferences) {\n\t\tthis.preferences = preferences;\n\t\tupdateInstance();\n\t}\n\n\tprivate void updateInstance() {\n\t\tString key = preferences.get(\"googleTranslateKey\", \"\");\n\n\t\tif (key != null && !key.equals(\"\")) {\n\t\t\ttranslate = TranslateOptions.newBuilder().setApiKey(key).build()\n\t\t\t\t\t.getService();\n\t\t} else {\n\t\t\t// This should not happen (GUI forces the user to insert a key,\n\t\t\t// otherwise translation is not allowed)\n\t\t\tthrow new RuntimeException(\n\t\t\t\t\t\"Key for Google Translate service not defined\");\n\t\t}\n\t}\n}", "public class Charset {\n\n\tpublic static String ISO88591 = \"ISO-8859-1\";\n\tpublic static String UTF8 = \"UTF-8\";\n\n\tprivate static Charset singleton = null;\n\n\tprivate UniversalDetector detector;\n\n\tpublic Charset() {\n\t\tdetector = new UniversalDetector(null);\n\t}\n\n\tpublic static Charset getSingleton() {\n\t\tif (singleton == null) {\n\t\t\tsingleton = new Charset();\n\t\t}\n\t\treturn singleton;\n\t}\n\n\tpublic static String detect(String file) throws IOException {\n\t\tInputStream inputStream = Thread.currentThread()\n\t\t\t\t.getContextClassLoader().getResourceAsStream(file);\n\t\tif (inputStream == null) {\n\t\t\tinputStream = new BufferedInputStream(new FileInputStream(file));\n\t\t}\n\t\treturn Charset.detect(inputStream);\n\t}\n\n\tpublic static String detect(InputStream inputStream) throws IOException {\n\t\tUniversalDetector detector = Charset.getSingleton()\n\t\t\t\t.getCharsetDetector();\n\t\tbyte[] buf = new byte[4096];\n\t\tint nread;\n\t\twhile ((nread = inputStream.read(buf)) > 0 && !detector.isDone()) {\n\t\t\tdetector.handleData(buf, 0, nread);\n\t\t}\n\t\tdetector.dataEnd();\n\t\tString encoding = detector.getDetectedCharset();\n\t\tdetector.reset();\n\t\tinputStream.close();\n\t\tif (encoding == null) {\n\t\t\t// If none encoding is detected, we assume UTF-8\n\t\t\tencoding = UTF8;\n\t\t}\n\t\treturn encoding;\n\t}\n\n\tpublic UniversalDetector getCharsetDetector() {\n\t\treturn detector;\n\t}\n\n}" ]
import io.github.bonigarcia.dualsub.srt.Srt; import io.github.bonigarcia.dualsub.srt.SrtUtils; import io.github.bonigarcia.dualsub.translate.Language; import io.github.bonigarcia.dualsub.translate.Translator; import io.github.bonigarcia.dualsub.util.Charset; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.util.Properties; import java.util.prefs.Preferences; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.github.bonigarcia.dualsub.gui.DualSub; import io.github.bonigarcia.dualsub.srt.DualSrt; import io.github.bonigarcia.dualsub.srt.Merger;
/* * (C) Copyright 2014 Boni Garcia (http://bonigarcia.github.io/) * * 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 io.github.bonigarcia.dualsub.test; /** * TestTranslation. * * @author Boni Garcia ([email protected]) * @since 1.0.0 */ public class TestTranslation { private static final Logger log = LoggerFactory .getLogger(TestTranslation.class); @Test public void testTranslation() {
Translator translate = Translator.getInstance();
6
leelit/STUer-client
app/src/main/java/com/leelit/stuer/module_treehole/CommentActivity.java
[ "public class TreeholeComment {\n\n int likeCount;\n\n int unlikeCount;\n\n List<Comment> comments;\n\n public int getLikeCount() {\n return likeCount;\n }\n\n public void setLikeCount(int likeCount) {\n this.likeCount = likeCount;\n }\n\n public int getUnlikeCount() {\n return unlikeCount;\n }\n\n public void setUnlikeCount(int unlikeCount) {\n this.unlikeCount = unlikeCount;\n }\n\n public List<Comment> getComments() {\n return comments;\n }\n\n public void setComments(List<Comment> comments) {\n this.comments = comments;\n }\n\n @Override\n public String toString() {\n return \"TreeholeComment{\" +\n \"likeCount=\" + likeCount +\n \", unlikeCount=\" + unlikeCount +\n \", comments=\" + comments +\n '}';\n }\n\n public static class Comment {\n String uniquecode;\n String name;\n String dt;\n String comment;\n String imei;\n\n public String getUniquecode() {\n return uniquecode;\n }\n\n public void setUniquecode(String uniquecode) {\n this.uniquecode = uniquecode;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getDt() {\n return dt;\n }\n\n public void setDt(String dt) {\n this.dt = dt;\n }\n\n public String getComment() {\n return comment;\n }\n\n public void setComment(String comment) {\n this.comment = comment;\n }\n\n public String getImei() {\n return imei;\n }\n\n public void setImei(String imei) {\n this.imei = imei;\n }\n\n @Override\n public String toString() {\n return \"Comment{\" +\n \"uniquecode='\" + uniquecode + '\\'' +\n \", name='\" + name + '\\'' +\n \", dt='\" + dt + '\\'' +\n \", comment='\" + comment + '\\'' +\n \", imei='\" + imei + '\\'' +\n '}';\n }\n }\n}", "public class TreeholeLocalInfo extends TreeholeInfo {\n\n boolean like;\n\n boolean unlike;\n\n public boolean isLike() {\n return like;\n }\n\n public void setLike(boolean like) {\n this.like = like;\n }\n\n public boolean isUnlike() {\n return unlike;\n }\n\n public void setUnlike(boolean unlike) {\n this.unlike = unlike;\n }\n\n @Override\n public String toString() {\n return \"TreeholeLocalInfo{\" +\n \"datetime='\" + datetime + '\\'' +\n \", state='\" + state + '\\'' +\n \", picAddress='\" + picAddress + '\\'' +\n \", uniquecode='\" + uniquecode + '\\'' +\n \", like=\" + like +\n \", unlike=\" + unlike +\n \"} \";\n }\n}", "public class TreeholeDao {\n\n private static final String[] keys = {\"dt\", \"state\", \"picaddress\", \"uniquecode\", \"like\", \"unlike\"};\n\n public static final int TRUE = 1;\n public static final int FALSE = 0;\n\n public static void save(List<TreeholeInfo> infos) {\n SQLiteDatabase db = DatabaseHelper.getInstance().getWritableDatabase();\n db.beginTransaction();\n for (TreeholeInfo info : infos) {\n ContentValues values = new ContentValues();\n values.put(keys[0], info.getDatetime());\n values.put(keys[1], info.getState());\n values.put(keys[2], info.getPicAddress());\n values.put(keys[3], info.getUniquecode());\n values.put(keys[4], FALSE);\n values.put(keys[5], FALSE);\n db.insert(\"treehole\", null, values);\n }\n db.setTransactionSuccessful();\n db.endTransaction();\n }\n\n public static String getLatestDatetime() {\n String str = \"\";\n SQLiteDatabase db = DatabaseHelper.getInstance().getReadableDatabase();\n Cursor cursor = db.rawQuery(\"SELECT * FROM treehole ORDER BY id DESC LIMIT 1\", null);\n if (cursor.moveToFirst()) {\n str = cursor.getString(cursor.getColumnIndex(\"dt\"));\n }\n cursor.close();\n return str;\n }\n\n public static List<TreeholeLocalInfo> getAll() {\n List<TreeholeLocalInfo> result = new ArrayList<>();\n SQLiteDatabase db = DatabaseHelper.getInstance().getReadableDatabase();\n db.beginTransaction();\n Cursor cursor = db.query(\"treehole\", null, null, null, null, null, null);\n if (cursor.moveToFirst()) {\n do {\n TreeholeLocalInfo comment = new TreeholeLocalInfo();\n comment.setDatetime(cursor.getString(cursor.getColumnIndex(keys[0])));\n comment.setState(cursor.getString(cursor.getColumnIndex(keys[1])));\n comment.setPicAddress(cursor.getString(cursor.getColumnIndex(keys[2])));\n comment.setUniquecode(cursor.getString(cursor.getColumnIndex(keys[3])));\n comment.setLike(TRUE == cursor.getInt(cursor.getColumnIndex(keys[4])));\n comment.setUnlike(TRUE == cursor.getInt(cursor.getColumnIndex(keys[5])));\n result.add(comment);\n } while (cursor.moveToNext());\n }\n cursor.close();\n db.setTransactionSuccessful();\n db.endTransaction();\n return result;\n }\n\n public static TreeholeLocalInfo getComment(String uniquecode) {\n SQLiteDatabase db = DatabaseHelper.getInstance().getReadableDatabase();\n Cursor cursor = db.query(\"treehole\", null, \"uniquecode = ?\", new String[]{uniquecode}, null, null, null);\n TreeholeLocalInfo comment = new TreeholeLocalInfo();\n cursor.moveToFirst();\n comment.setDatetime(cursor.getString(cursor.getColumnIndex(keys[0])));\n comment.setState(cursor.getString(cursor.getColumnIndex(keys[1])));\n comment.setPicAddress(cursor.getString(cursor.getColumnIndex(keys[2])));\n comment.setUniquecode(cursor.getString(cursor.getColumnIndex(keys[3])));\n comment.setLike(TRUE == cursor.getInt(cursor.getColumnIndex(keys[4])));\n comment.setUnlike(TRUE == cursor.getInt(cursor.getColumnIndex(keys[5])));\n cursor.close();\n return comment;\n }\n\n public static void updateLikeOfComment(String uniquecode, int isLike) {\n SQLiteDatabase db = DatabaseHelper.getInstance().getWritableDatabase();\n ContentValues values = new ContentValues();\n values.put(keys[4], isLike);\n db.update(\"treehole\", values, \"uniquecode = ?\", new String[]{uniquecode});\n }\n\n public static void updateUnlikeOfComment(String uniquecode, int isUnlike) {\n SQLiteDatabase db = DatabaseHelper.getInstance().getWritableDatabase();\n ContentValues values = new ContentValues();\n values.put(keys[5], isUnlike);\n db.update(\"treehole\", values, \"uniquecode = ?\", new String[]{uniquecode});\n }\n}", "public class CommentPresenter implements IPresenter{\n\n private TreeholeModel mModel = new TreeholeModel();\n\n private ICommentView mView;\n private Subscriber<ResponseBody> mSubscriber1;\n private Subscriber<TreeholeComment> mSubscriber2;\n\n public CommentPresenter(ICommentView view) {\n mView = view;\n }\n\n public void doLikeJob(String uniquecode, boolean isLike) {\n mModel.doLikeJob(uniquecode, AppInfoUtils.getImei(), isLike);\n }\n\n public void doUnlikeJob(String uniquecode, boolean isUnlike) {\n mModel.doUnlikeJob(uniquecode, AppInfoUtils.getImei(), isUnlike);\n }\n\n public void doSendComment(String uniquecode, String commentText) {\n TreeholeComment.Comment comment = new TreeholeComment.Comment();\n comment.setUniquecode(uniquecode);\n comment.setName(SPUtils.getString(LoginActivity.INFOS[0]));\n comment.setComment(commentText);\n comment.setImei(AppInfoUtils.getImei());\n mView.sendingCommentProgressDialog();\n mSubscriber1 = new Subscriber<ResponseBody>() {\n @Override\n public void onCompleted() {\n\n }\n\n @Override\n public void onError(Throwable e) {\n mView.dismissProgressDialog();\n mView.netError();\n }\n\n @Override\n public void onNext(ResponseBody responseBody) {\n mView.dismissProgressDialog();\n mView.succeededInSending();\n }\n };\n mModel.sendComment(comment, mSubscriber1);\n }\n\n public void doLoadingComments(String uniquecode) {\n mView.loadingCommentProgressDialog();\n mSubscriber2 = new Subscriber<TreeholeComment>() {\n @Override\n public void onCompleted() {\n\n }\n\n @Override\n public void onError(Throwable e) {\n mView.dismissProgressDialog();\n mView.netError();\n }\n\n @Override\n public void onNext(TreeholeComment comment) {\n mView.dismissProgressDialog();\n mView.refreshLikeAndUnlike(comment);\n if (comment.getComments().isEmpty()) {\n mView.noComment();\n } else {\n List<TreeholeComment.Comment> comments = comment.getComments();\n Collections.reverse(comments);\n mView.showComments(comments);\n }\n }\n };\n mModel.doLoadingComments(uniquecode, mSubscriber2);\n }\n\n @Override\n public void doClear() {\n if (mSubscriber1 != null) {\n mSubscriber1.unsubscribe();\n }\n if (mSubscriber2 != null) {\n mSubscriber2.unsubscribe();\n }\n mView = null;\n }\n}", "public interface ICommentView {\n void sendingCommentProgressDialog();\n\n void dismissProgressDialog();\n\n void netError();\n\n void loadingCommentProgressDialog();\n\n void refreshLikeAndUnlike(TreeholeComment comment);\n\n void succeededInSending();\n\n void noComment();\n\n void showComments(List<TreeholeComment.Comment> comment);\n}", "public class ProgressDialogUtils {\n\n private static ProgressDialog progressDialog;\n\n public static void show(Context context) {\n show(context, \"\");\n }\n\n public static void show(Context context, String text) {\n progressDialog = new ProgressDialog(context);\n progressDialog.setCancelable(false); // 只能同时操作一个ProgressDialog\n if (!TextUtils.isEmpty(text)) {\n progressDialog.setMessage(text);\n }\n progressDialog.show();\n }\n\n public static void dismiss() {\n progressDialog.dismiss();\n progressDialog = null;\n }\n\n}", "public class SharedAnimation {\n\n public static void postScaleAnimation(View v) {\n ScaleAnimation scaleAnimation1 = new ScaleAnimation(1.0f, 0.5f, 1.0f, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);\n scaleAnimation1.setDuration(200);\n ScaleAnimation scaleAnimation2 = new ScaleAnimation(0.5f, 1.5f, 0.5f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);\n scaleAnimation2.setDuration(100);\n AnimationSet set = new AnimationSet(true);\n set.addAnimation(scaleAnimation1);\n set.addAnimation(scaleAnimation2);\n v.startAnimation(set);\n }\n}", "public class UiUtils {\n\n @TargetApi(19)\n public static void setTranslucentStatusBar(Activity activity, NavigationView navigationView) {\n if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT && navigationView != null) {\n // fix 天坑 4.4 + drawerlayout + navigationView\n tianKeng(activity, activity.getResources().getColor(R.color.primary), navigationView);\n } else {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {\n activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);\n SystemBarTintManager tintManager = new SystemBarTintManager(activity);\n tintManager.setStatusBarTintEnabled(true);\n tintManager.setStatusBarTintColor(activity.getResources().getColor(R.color.primary));\n }\n }\n }\n\n @TargetApi(19)\n public static void setTranslucentStatusBar(Activity activity) {\n setTranslucentStatusBar(activity, null);\n }\n\n /**\n * snippet from https://github.com/niorgai/StatusBarCompat\n * <p/>\n * 直接使用会引起NavigationView上面空白一部分,需要将其margin - statusBarHeight\n */\n @TargetApi(19)\n private static void tianKeng(Activity activity, int statusColor, NavigationView navigationView) {\n Window window = activity.getWindow();\n window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);\n\n int statusBarHeight = getStatusBarHeight(activity);\n\n ViewGroup mContentView = (ViewGroup) activity.findViewById(Window.ID_ANDROID_CONTENT);\n\n View mChildView = mContentView.getChildAt(0);\n if (mChildView != null) {\n FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mChildView.getLayoutParams();\n //if margin top has already set, just skip.\n if (lp != null && lp.topMargin < statusBarHeight && lp.height != statusBarHeight) {\n //do not use fitsSystemWindows\n ViewCompat.setFitsSystemWindows(mChildView, false);\n //add margin to content\n lp.topMargin += statusBarHeight;\n mChildView.setLayoutParams(lp);\n }\n }\n\n View statusBarView = mContentView.getChildAt(0);\n if (statusBarView != null && statusBarView.getLayoutParams() != null && statusBarView.getLayoutParams().height == statusBarHeight) {\n //if fake status bar view exist, we can setBackgroundColor and return.\n statusBarView.setBackgroundColor(statusColor);\n return;\n }\n statusBarView = new View(activity);\n ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, statusBarHeight);\n statusBarView.setBackgroundColor(statusColor);\n mContentView.addView(statusBarView, 0, lp);\n\n DrawerLayout.LayoutParams nvLp = (DrawerLayout.LayoutParams) navigationView.getLayoutParams();\n nvLp.topMargin -= statusBarHeight;\n navigationView.setLayoutParams(nvLp);\n }\n\n public static int getStatusBarHeight(Context context) {\n int result = 0;\n int resId = context.getResources().getIdentifier(\"status_bar_height\", \"dimen\", \"android\");\n if (resId > 0) {\n result = context.getResources().getDimensionPixelOffset(resId);\n }\n return result;\n }\n\n public static void initBaseToolBar(final AppCompatActivity activity, Toolbar mToolbar, String title) {\n activity.setSupportActionBar(mToolbar);\n mToolbar.setTitle(title);\n mToolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);\n mToolbar.setNavigationOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n activity.finish();\n }\n });\n }\n\n public static boolean isNightMode(AppCompatActivity activity) {\n int uiMode = activity.getResources().getConfiguration().uiMode;\n int dayNightUiMode = uiMode & Configuration.UI_MODE_NIGHT_MASK;\n if (SPUtils.getBoolean(MainActivity.CURRENT_NIGHT_MODE) && dayNightUiMode != Configuration.UI_MODE_NIGHT_YES) {\n activity.getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);\n activity.recreate();\n return true;\n }\n return false;\n }\n}" ]
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.leelit.stuer.R; import com.leelit.stuer.bean.TreeholeComment; import com.leelit.stuer.bean.TreeholeLocalInfo; import com.leelit.stuer.dao.TreeholeDao; import com.leelit.stuer.module_treehole.presenter.CommentPresenter; import com.leelit.stuer.module_treehole.viewinterface.ICommentView; import com.leelit.stuer.utils.ProgressDialogUtils; import com.leelit.stuer.utils.SharedAnimation; import com.leelit.stuer.utils.UiUtils; import java.util.ArrayList; import java.util.List; import butterknife.ButterKnife; import butterknife.InjectView;
package com.leelit.stuer.module_treehole; public class CommentActivity extends AppCompatActivity implements ICommentView { @InjectView(R.id.toolbar) Toolbar mToolbar; @InjectView(R.id.treeholeView) TreeholeView mTreeholeView; @InjectView(R.id.likePic) ImageView mLikePic; @InjectView(R.id.likeCount) TextView mLikeCount; @InjectView(R.id.unlikePic) ImageView mUnlikePic; @InjectView(R.id.unlikeCount) TextView mUnlikeCount; @InjectView(R.id.recyclerView) RecyclerView mRecyclerView; @InjectView(R.id.likeLayout) LinearLayout mLikeLayout; @InjectView(R.id.unlikeLayout) LinearLayout mUnlikeLayout; @InjectView(R.id.text) EditText mText; @InjectView(R.id.send) ImageView mSend; @InjectView(R.id.nocomment) TextView mNoComment; private boolean isLike; private boolean isUnlike; private boolean mOriginalIsLike; private boolean mOriginalIsUnlike;
private TreeholeLocalInfo mTreeholeLocalInfo;
1
maker56/UltimateSurvivalGames
UltimateSurvivalGames/src/me/maker56/survivalgames/game/GameManager.java
[ "public class Util {\r\n\t\r\n\t// ITEMSTACK\r\n\tpublic static boolean debug = false;\r\n\tprivate static Random random = new Random();\r\n\t\r\n\t@SuppressWarnings(\"deprecation\")\r\n\tpublic static ItemStack parseItemStack(String s) {\r\n\t\ttry {\r\n\t\t\tString[] gSplit = s.split(\" \");\r\n\t\t\tItemStack is = null;\r\n\t\t\t\r\n\t\t\t// ITEM ID / MATERIAL / SUBID\r\n\t\t\tString[] idsSplit = gSplit[0].split(\":\");\r\n\t\t\ttry {\r\n\t\t\t\tis = new ItemStack(Integer.parseInt(idsSplit[0]));\r\n\t\t\t} catch(NumberFormatException e) {\r\n\t\t\t\tis = new ItemStack(Material.valueOf(idsSplit[0]));\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif(idsSplit.length > 1)\r\n\t\t\t\tis.setDurability(Short.parseShort(idsSplit[1]));\r\n\t\t\t\r\n\t\t\tif(gSplit.length > 1) {\r\n\t\t\t\tint metaStart = 2;\r\n\t\t\t\t\r\n\t\t\t\ttry {\r\n\t\t\t\t\tis.setAmount(Integer.parseInt(gSplit[1]));\r\n\t\t\t\t} catch(NumberFormatException e) {\r\n\t\t\t\t\tmetaStart = 1;\r\n\t\t\t\t}\r\n\t\t\t\tItemMeta im = is.getItemMeta();\r\n\t\t\t\tfor(int meta = metaStart; meta < gSplit.length; meta++) {\r\n\t\t\t\t\tString rawKey = gSplit[meta];\r\n\t\t\t\t\tString[] split = rawKey.split(\":\");\r\n\t\t\t\t\tString key = split[0];\r\n\t\t\t\t\t\r\n\t\t\t\t\tif(key.equalsIgnoreCase(\"name\")) {\r\n\t\t\t\t\t\tim.setDisplayName(ChatColor.translateAlternateColorCodes('&', split[1]).replace(\"_\", \" \"));\r\n\t\t\t\t\t} else if(key.equalsIgnoreCase(\"lore\")) {\r\n\t\t\t\t\t\tList<String> lore = new ArrayList<>();\r\n\t\t\t\t\t\tfor(String line : split[1].split(\"//\")) {\r\n\t\t\t\t\t\t\tlore.add(ChatColor.translateAlternateColorCodes('&', line).replace(\"_\", \" \"));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tim.setLore(lore);\r\n\t\t\t\t\t} else if(key.equalsIgnoreCase(\"color\") && im instanceof LeatherArmorMeta) {\r\n\t\t\t\t\t\tLeatherArmorMeta lam = (LeatherArmorMeta) im;\r\n\t\t\t\t\t\tString[] csplit = split[1].split(\",\");\r\n\t\t\t\t\t\tColor color = Color.fromBGR(Integer.parseInt(csplit[0]), Integer.parseInt(csplit[1]), Integer.parseInt(csplit[2]));\r\n\t\t\t\t\t\tlam.setColor(color);\r\n\t\t\t\t\t} else if(key.equalsIgnoreCase(\"effect\") && im instanceof PotionMeta) {\r\n\t\t\t\t\t\tPotionMeta pm = (PotionMeta) im;\r\n\t\t\t\t\t\tString[] psplit = split[1].split(\",\");\r\n\t\t\t\t\t\tpm.addCustomEffect(new PotionEffect(PotionEffectType.getByName(psplit[0]), Integer.parseInt(psplit[1]) * 20, Integer.parseInt(psplit[2])), true);\r\n\t\t\t\t\t} else if(key.equalsIgnoreCase(\"player\") && im instanceof SkullMeta) {\r\n\t\t\t\t\t\t((SkullMeta)im).setOwner(split[1]);\r\n\t\t\t\t\t} else if(key.equalsIgnoreCase(\"enchant\")) {\r\n\t\t\t\t\t\tString[] esplit = split[1].split(\",\");\r\n\t\t\t\t\t\tim.addEnchant(getEnchantment(esplit[0]), Integer.parseInt(esplit[1]), true);\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\tis.setItemMeta(im);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\treturn is;\r\n\t\t} catch(Exception e) {\r\n\t\t\tSystem.err.println(\"[SurvivalGames] Cannot parse ItemStack: \" + s + \" - Mabye this is the reason: \" + e.toString());\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static Vector calculateVector(Location from, Location to) {\r\n Location a = from, b = to;\r\n \r\n double dX = a.getX() - b.getX();\r\n double dY = a.getY() - b.getY();\r\n double dZ = a.getZ() - b.getZ();\r\n double yaw = Math.atan2(dZ, dX);\r\n double pitch = Math.atan2(Math.sqrt(dZ * dZ + dX * dX), dY) + Math.PI;\r\n double x = Math.sin(pitch) * Math.cos(yaw);\r\n double y = Math.sin(pitch) * Math.sin(yaw);\r\n double z = Math.cos(pitch);\r\n \r\n Vector vector = new Vector(x, z, y);\r\n \r\n return vector;\r\n }\r\n\t\r\n\tpublic static void shootRandomFirework(Location loc, int height) {\r\n\t\tFirework f = (Firework) loc.getWorld().spawnEntity(loc, EntityType.FIREWORK);\r\n\t\tFireworkMeta fm = f.getFireworkMeta();\r\n\t\tfm.setPower(height);\r\n\t\tint effectAmount = random.nextInt(3) + 1;\r\n\t\tfor(int i = 0; i < effectAmount; i++) {\r\n\t\t\tBuilder b = FireworkEffect.builder();\r\n\t\t\tint colorAmount = random.nextInt(3) + 1;\r\n\t\t\tfor(int ii = 0; ii < colorAmount; ii++) {\r\n\t\t\t\tb.withColor(Color.fromBGR(random.nextInt(256), random.nextInt(256), random.nextInt(256)));\r\n\t\t\t}\r\n\t\t\tb.with(Type.values()[random.nextInt(Type.values().length)]);\r\n\t\t\tb.flicker(random.nextInt(2) == 0 ? false : true);\r\n\t\t\tb.trail(random.nextInt(2) == 0 ? false : true);\r\n\t\t\tfm.addEffect(b.build());\r\n\t\t}\r\n\t\tf.setFireworkMeta(fm);\r\n\t}\r\n\t\r\n\t// EXP PERCENT\r\n\t\r\n\tpublic static float getExpPercent(float value, float max) {\r\n\t\tif(value == 0)\r\n\t\t\treturn 0;\r\n\t\treturn value / max;\r\n\t}\r\n\t\r\n\t// ENCHANTMENT\r\n\tpublic static Enchantment getEnchantment(String enc) {\r\n\t\tenc = enc.toUpperCase();\r\n\t\tEnchantment en = Enchantment.getByName(enc);\r\n\t\t\r\n\t\tif(en == null) {\r\n\t\t\tswitch (enc) {\r\n\t\t\tcase \"PROTECTION\":\r\n\t\t\t\ten = Enchantment.PROTECTION_ENVIRONMENTAL;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"FIRE_PROTECTION\":\r\n\t\t\t\ten = Enchantment.PROTECTION_FIRE;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"FEATHER_FALLING\":\r\n\t\t\t\ten = Enchantment.PROTECTION_FALL;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"BLAST_PROTECTION\":\r\n\t\t\t\ten = Enchantment.PROTECTION_EXPLOSIONS;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"PROJECTILE_PROTCETION\":\r\n\t\t\t\ten = Enchantment.PROTECTION_PROJECTILE;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"RESPIRATION\":\r\n\t\t\t\ten = Enchantment.OXYGEN;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"AQUA_AFFINITY\":\r\n\t\t\t\ten = Enchantment.WATER_WORKER;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"SHARPNESS\":\r\n\t\t\t\ten = Enchantment.DAMAGE_ALL;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"SMITE\":\r\n\t\t\t\ten = Enchantment.DAMAGE_UNDEAD;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"BANE_OF_ARTHROPODS\":\r\n\t\t\t\ten = Enchantment.DAMAGE_ARTHROPODS;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"LOOTING\":\r\n\t\t\t\ten = Enchantment.LOOT_BONUS_MOBS;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"EFFICIENCY\":\r\n\t\t\t\ten = Enchantment.DIG_SPEED;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"UNBREAKING\":\r\n\t\t\t\ten = Enchantment.DURABILITY;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"FORTUNE\":\r\n\t\t\t\ten = Enchantment.LOOT_BONUS_BLOCKS;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"POWER\":\r\n\t\t\t\ten = Enchantment.ARROW_DAMAGE;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"PUNCH\":\r\n\t\t\t\ten = Enchantment.ARROW_KNOCKBACK;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"FLAME\":\r\n\t\t\t\ten = Enchantment.ARROW_FIRE;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"INFINITY\":\r\n\t\t\t\ten = Enchantment.ARROW_INFINITE;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"LUCK_OF_THE_SEA\":\r\n\t\t\t\ten = Enchantment.LUCK;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\treturn en;\r\n\t}\r\n\t// TIME\r\n\t\r\n\tpublic static String getFormatedTime(int seconds) {\r\n\t\tint minutes = seconds / 60;\r\n\t\tint hours = minutes / 60;\r\n\t\tint days = hours / 24;\r\n\t\t\r\n\t\tseconds -= minutes * 60;\r\n\t\tminutes -= hours * 60;\r\n\t\thours -= days * 24;\r\n\t\t\r\n\t\tString s = \"\";\r\n\t\tif(days > 0)\r\n\t\t\ts += days + \"d\";\r\n\t\tif(hours > 0)\r\n\t\t\ts += hours + \"h\";\r\n\t\tif(minutes > 0)\r\n\t\t\ts += minutes + \"m\";\r\n\t\tif(seconds > 0) \r\n\t\t\ts += seconds + \"s\";\r\n\t\r\n\t\treturn s;\r\n\t}\r\n\t\r\n\t// LOCATION\r\n\t\r\n\tpublic static Location parseLocation(String s) {\r\n\t\tString[] split = s.split(\",\");\r\n\t\tLocation loc = null;\r\n\t\t\r\n\t\t\r\n\t\ttry {\r\n\t\t\tWorld world = Bukkit.getWorld(split[0]);\r\n\t\t\tif(split.length == 6) {\r\n\t\t\t\tdouble x = Double.parseDouble(split[1]);\r\n\t\t\t\tdouble y = Double.parseDouble(split[2]);\r\n\t\t\t\tdouble z = Double.parseDouble(split[3]);\r\n\t\t\t\t\r\n\t\t\t\tfloat yaw = Float.parseFloat(split[4]);\r\n\t\t\t\tfloat pitch = Float.parseFloat(split[5]);\r\n\t\t\t\tloc = new Location(world, x, y, z, yaw, pitch);\r\n\t\t\t} else if(split.length == 4) {\r\n\t\t\t\tint x = Integer.parseInt(split[1]);\r\n\t\t\t\tint y = Integer.parseInt(split[2]);\r\n\t\t\t\tint z = Integer.parseInt(split[3]);\r\n\t\t\t\t\r\n\t\t\t\tloc = new Location(world, x, y, z);\r\n\t\t\t}\r\n\t\t} catch(NumberFormatException | ArrayIndexOutOfBoundsException e) {\r\n\t\t\tSystem.err.println(\"[SurvivalGames] Cannot parse location from string: \" + s);\r\n\t\t}\r\n\t\t\r\n\t\treturn loc;\r\n\t}\r\n\t\r\n\tpublic static String serializeLocation(Location l, boolean exact) {\r\n\t\tif(l != null) {\r\n\t\t\tString key = l.getWorld().getName() + \",\";\r\n\t\t\tif(exact) {\r\n\t\t\t\tkey += l.getX() + \",\" + l.getY() + \",\" + l.getZ() + \",\" + l.getYaw() + \",\" + l.getPitch();\r\n\t\t\t} else {\r\n\t\t\t\tkey += l.getBlockX() + \",\" + l.getBlockY() + \",\" + l.getBlockZ();\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\treturn key;\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\tpublic static void debug(Object object) {\r\n\t\tif(debug) {\r\n\t\t\tSystem.out.println(\"[SurvivalGames] [Debug] \" + object.toString());\r\n\t\t\tfor(Player p : Bukkit.getOnlinePlayers()) {\r\n\t\t\t\tif(p.isOp()) \r\n\t\t\t\t\tp.sendMessage(\"§7[Debug] \" + object.toString());\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\t// TEMPORARY UPDATE METHODS\r\n\t\r\n\tpublic static void checkForOutdatedArenaSaveFiles() {\r\n\t\tFile f = new File(\"plugins/SurvivalGames/reset/\");\r\n\t\tList<String> outdated = new ArrayList<>();\r\n\t\tif(f.exists()) {\r\n\t\t\tfor(String key : f.list()) {\r\n\t\t\t\tif(!key.endsWith(\".map\"))\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\tFile file = new File(\"plugins/SurvivalGames/reset/\" + key);\r\n\t\t\t\tSchematicFormat sf = SchematicFormat.getFormat(file);\r\n\t\t\t\tif(sf == null) {\r\n\t\t\t\t\toutdated.add(key);\r\n\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tString s = null;\r\n\t\tif(!outdated.isEmpty()) {\r\n\t\t\ts = MessageHandler.getMessage(\"prefix\") + \"§cThe format of \" + outdated.size() + \" map saves is outdated§7: §e\";\r\n\t\t\tfor(int i = 0; i < outdated.size(); i++) {\r\n\t\t\t\ts+= outdated.get(i);\r\n\t\t\t\tif(i != outdated.size() - 1) {\r\n\t\t\t\t\ts+= \"§7, §e\";\r\n\t\t\t\t} else {\r\n\t\t\t\t\ts+= \" §c! \";\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\r\n\t\t\t}\r\n\t\t\ts+= \"Select all the arenas with §l/sg arena select §cand type §c§l/sg arena save§c! In the old format, the arenas will not reset!\";\r\n\t\t}\r\n\t\tUpdateListener.setOutdatedMaps(s);\r\n\t}\r\n\r\n}\r", "public class SurvivalGames extends JavaPlugin {\r\n\t\r\n\tpublic static SurvivalGames instance;\r\n\tpublic static FileConfiguration messages, database, signs, reset, chestloot, scoreboard, kits;\r\n\t\r\n\tpublic static ArenaManager arenaManager;\r\n\tpublic static GameManager gameManager;\r\n\tpublic static ChestManager chestManager;\r\n\tpublic static UserManager userManger;\r\n\tpublic static SignManager signManager;\r\n\tpublic static ScoreBoardManager scoreBoardManager;\r\n\t\r\n\tpublic static Economy econ;\r\n\t\r\n\tpublic static String version = \"SurvivalGames - Version \";\r\n\t\r\n\tprivate static PluginManager pm = Bukkit.getPluginManager();\r\n\t\r\n\tpublic void onDisable() {\r\n\t\tif(gameManager != null) {\r\n\t\t\tfor(Game game : gameManager.getGames()) {\r\n\t\t\t\tgame.kickall();\r\n\t\t\t}\r\n\t\t}\r\n\t\tDatabaseManager.close();\r\n\t}\r\n\t\r\n\tpublic void onEnable() {\r\n\t\tif(!Bukkit.getVersion().toLowerCase().contains(\"spigot\")) {\r\n\t\t\tSystem.err.println(\"[SurvivalGames] ###################################################################\");\r\n\t\t\tSystem.err.println(\"[SurvivalGames] ######### THIS PLUGIN REQUIRES SPIGOT TO RUN ##########\");\r\n\t\t\tSystem.err.println(\"[SurvivalGames] ######### Please use it instead of craftbukkit! ##########\");\r\n\t\t\tSystem.err.println(\"[SurvivalGames] ######### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##########\");\r\n\t\t\tSystem.err.println(\"[SurvivalGames] ######### Download: http://www.spigotmc.org/ ##########\");\r\n\t\t\tSystem.err.println(\"[SurvivalGames] ###################################################################\");\r\n\t\t\tBukkit.getPluginManager().disablePlugin(this);\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tif(!Bukkit.getPluginManager().isPluginEnabled(\"WorldEdit\")) {\r\n\t\t\tSystem.err.println(\"[SurvivalGames] ##########################################################\");\r\n\t\t\tSystem.err.println(\"[SurvivalGames] ######### NO WORLDEDIT FOUND! DISABLE PLUGIN... ##########\");\r\n\t\t\tSystem.err.println(\"[SurvivalGames] ##########################################################\");\r\n\t\t\tBukkit.getPluginManager().disablePlugin(this);\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tinstance = this;\r\n\t\tversion += getDescription().getVersion();\r\n\t\t\r\n\t\tnew ConfigLoader().load();\r\n\t\tDatabaseManager.open();\r\n\t\tDatabaseManager.load();\r\n\t\t\r\n\t\tstartUpdateChecker();\r\n\t\t\r\n\t\tPermissionHandler.reinitializeDatabase();\r\n\t\tGame.reinitializeDatabase();\r\n\t\tMessageHandler.reload();\r\n\t\t\r\n\t\tif(setupEconomy())\r\n\t\t\tSystem.out.println(\"[SurvivalGames] Vault found!\");\r\n\t\t\r\n\t\t// TEMPORARY\r\n\t\tUtil.checkForOutdatedArenaSaveFiles();\r\n\r\n\t\tchestManager = new ChestManager();\r\n\t\tscoreBoardManager = new ScoreBoardManager();\r\n\t\tarenaManager = new ArenaManager();\r\n\t\tgameManager = new GameManager();\r\n\t\tuserManger = new UserManager();\r\n\t\tsignManager = new SignManager();\r\n\t\t\r\n\t\tgetCommand(\"sg\").setExecutor(new CommandSG());\r\n\t\t\r\n\t\tpm.registerEvents(new SelectionListener(), this);\r\n\t\tpm.registerEvents(new PlayerListener(), this);\r\n\t\tpm.registerEvents(new ChestListener(), this);\r\n\t\tpm.registerEvents(new SignListener(), this);\r\n\t\tpm.registerEvents(new ResetListener(), this);\r\n\t\tpm.registerEvents(new UpdateListener(), this);\r\n\t\tpm.registerEvents(new SpectatorListener(), this);\r\n\t\tpm.registerEvents(new ChatListener(), this);\r\n\t\t\r\n\t\ttry {\r\n\t\t\tnew Metrics(this).start();\r\n\t\t} catch (IOException e) {\r\n\t\t\tSystem.err.println(\"[SurvivalGames] Cannot load metrics: \" + e.getMessage());\r\n\t\t}\r\n\t\t\r\n\t\tif(getWorldEdit() != null) {\r\n\t\t\tSystem.out.println(\"[SurvivalGames] Plugin enabled. WorldEdit found!\");\r\n\t\t} else {\r\n\t\t\tSystem.out.println(\"[SurvivalGames] Plugin enabled.\");\r\n\t\t}\r\n\t\t\r\n\t\tsignManager.updateSigns();\r\n\t}\r\n\t\r\n\t// UPDATE CHECKING\r\n\r\n\tpublic void startUpdateChecker() {\r\n\t\tBukkit.getScheduler().runTaskTimer(this, new Runnable() {\r\n\t\t\tpublic void run() {\r\n\t\t\t\tnew UpdateCheck(SurvivalGames.instance, 61788);\r\n\t\t\t}\r\n\t\t}, 0L, 216000);\r\n\t}\r\n\t\r\n\t// VAULT\r\n\t\r\n\tprivate boolean setupEconomy() {\r\n\t\tif(Bukkit.getPluginManager().isPluginEnabled(\"Vault\")) {\r\n\t\t\tRegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(Economy.class);\r\n\t if (economyProvider != null) {\r\n\t econ = economyProvider.getProvider();\r\n\t }\r\n\t\t}\r\n\r\n return (econ != null);\r\n\t}\r\n\t\r\n\t// FILECONFIGURATION SAVE\r\n\t\r\n\tpublic static void saveMessages() {\r\n\t\ttry {\r\n\t\t\tmessages.save(\"plugins/SurvivalGames/messages.yml\");\r\n\t\t} catch (IOException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static void saveDataBase() {\r\n\t\ttry {\r\n\t\t\tdatabase.save(\"plugins/SurvivalGames/database.yml\");\r\n\t\t} catch (IOException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static void saveSigns() {\r\n\t\ttry {\r\n\t\t\tsigns.save(\"plugins/SurvivalGames/signs.yml\");\r\n\t\t} catch(IOException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static void saveReset() {\r\n\t\ttry {\r\n\t\t\treset.save(\"plugins/SurvivalGames/reset.yml\");\r\n\t\t} catch (IOException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static void saveChests() {\r\n\t\ttry {\r\n\t\t\tchestloot.save(\"plugins/SurvivalGames/chestloot.yml\");\r\n\t\t} catch (IOException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static void saveScoreboard() {\r\n\t\ttry {\r\n\t\t\tscoreboard.save(\"plugins/SurvivalGames/scoreboard.yml\");\r\n\t\t} catch (IOException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static void saveKits() {\r\n\t\ttry {\r\n\t\t\tkits.save(\"plugins/SurvivalGames/kits.yml\");\r\n\t\t} catch(IOException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t}\r\n\t\r\n\t// WORLDEDIT\r\n\t\r\n\tpublic static WorldEditPlugin getWorldEdit() {\r\n\t\tif(!pm.isPluginEnabled(\"WorldEdit\")) {\r\n\t\t\treturn null;\r\n\t\t} else {\r\n\t\t\treturn (WorldEditPlugin) pm.getPlugin(\"WorldEdit\");\r\n\t\t}\r\n\t}\r\n\t\r\n\t// API\r\n\t\r\n\tpublic static GameManager getGameManager() {\r\n\t\treturn gameManager;\r\n\t}\r\n\t\r\n\tpublic static ArenaManager getArenaManager() {\r\n\t\treturn arenaManager;\r\n\t}\r\n\t\r\n\tpublic static ChestManager getChestManager() {\r\n\t\treturn chestManager;\r\n\t}\r\n\t\r\n\tpublic static UserManager getUserManager() {\r\n\t\treturn userManger;\r\n\t}\r\n\t\r\n\tpublic static SignManager getSignManager() {\r\n\t\treturn signManager;\r\n\t}\r\n\t\r\n\tpublic static ScoreBoardManager getScoreboardManager() {\r\n\t\treturn scoreBoardManager;\r\n\t}\r\n\t\r\n\tpublic static SurvivalGames getInstance() {\r\n\t\treturn instance;\r\n\t}\r\n\r\n}\r", "public class Arena implements Cloneable {\r\n\r\n\tprivate Location min, max;\r\n\tprivate List<Location> spawns;\r\n\tprivate int graceperiod;\r\n\tprivate String name;\r\n\tprivate String game;\r\n\tprivate List<Integer> allowedBlocks;\r\n\tprivate double moneyKill, moneyWin;\r\n\t\r\n\tprivate Material chesttype;\r\n\tprivate int chestdata;\r\n\t\r\n\tprivate boolean deathmatch, refill;\r\n\tprivate List<Location> deathmatchSpawns;\r\n\t\r\n\tprivate int autodeathmatch, playerdeathmatch;\r\n\t\r\n\tprivate int votes = 0;\r\n\t\r\n\tpublic Arena(Location min, Location max, List<Location> spawns, Material chesttype, int chestdata, int graceperiod, String name, String game, boolean deathmatch, List<Location> deathmatchspawns, List<Integer> allowedBlocks, int autodeathmatch, int playerdeathmatch, double moneyKill, double moneyWin, boolean chestrefill, Location domeMiddle, int domeRadius) {\r\n\t\tthis.min = min;\r\n\t\tthis.max = max;\r\n\t\tthis.spawns = spawns;\r\n\t\tthis.graceperiod = graceperiod;\r\n\t\tthis.name = name;\r\n\t\tthis.game = game;\r\n\t\tthis.allowedBlocks = allowedBlocks;\r\n\t\tthis.chesttype = chesttype;\r\n\t\tthis.chestdata = chestdata;\r\n\t\tthis.moneyKill = moneyKill;\r\n\t\tthis.moneyWin = moneyWin;\r\n\t\tthis.refill = chestrefill;\r\n\t\t\r\n\t\tthis.deathmatch = deathmatch;\r\n\t\tthis.deathmatchSpawns = deathmatchspawns;\r\n\t\t\r\n\t\tif(deathmatchSpawns.isEmpty())\r\n\t\t\tthis.deathmatch = false;\r\n\t\t\r\n\t\t\r\n\t\tthis.autodeathmatch = autodeathmatch;\r\n\t\tthis.playerdeathmatch = playerdeathmatch;\r\n\t\tthis.domeRadius = domeRadius;\r\n\t\tif(domeRadius > 0) {\r\n\t\t\tthis.domeMiddle = domeMiddle;\r\n\t\t\tthis.domeMiddle.setY(0);\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic int getAutomaticlyDeathmatchTime() {\r\n\t\treturn autodeathmatch;\r\n\t}\r\n\t\r\n\tpublic int getPlayerDeathmatchAmount() {\r\n\t\treturn playerdeathmatch;\r\n\t}\r\n\t\r\n\tpublic boolean isDeathmatchEnabled() {\r\n\t\treturn deathmatch;\r\n\t}\r\n\t\r\n\tpublic List<Location> getDeathmatchSpawns() {\r\n\t\treturn deathmatchSpawns;\r\n\t}\r\n\t\r\n\tpublic void setVotes(int votes) {\r\n\t\tthis.votes = votes;\r\n\t}\r\n\t\r\n\tpublic int getVotes() {\r\n\t\treturn votes;\r\n\t}\r\n\t\r\n\tpublic Material getChestType() {\r\n\t\treturn chesttype;\r\n\t}\r\n\t\r\n\tpublic int getChestData() {\r\n\t\treturn chestdata;\r\n\t}\r\n\t\r\n\tpublic List<Integer> getAllowedMaterials() {\r\n\t\treturn allowedBlocks;\r\n\t}\r\n\t\r\n\tpublic double getMoneyOnKill() {\r\n\t\treturn moneyKill;\r\n\t}\r\n\t\r\n\tpublic double getMoneyOnWin() {\r\n\t\treturn moneyWin;\r\n\t}\r\n\t\r\n\tpublic boolean chestRefill() {\r\n\t\treturn refill;\r\n\t}\r\n\t\r\n\tpublic boolean containsBlock(Location loc) {\r\n\t\tdouble x = loc.getX();\r\n\t\tdouble y = loc.getY();\r\n\t\tdouble z = loc.getZ();\r\n\t\treturn (loc.getWorld().equals(min.getWorld()) && x >= min.getX() && x <= max.getX() && y >= min.getY() && y <= max.getY() && z >= min.getZ() && z <= max.getZ());\r\n\t}\r\n\t\r\n\tpublic Location getMinimumLocation() {\r\n\t\treturn min;\r\n\t}\r\n\t\r\n\tpublic Location getMaximumLocation() {\r\n\t\treturn max;\r\n\t}\r\n\t\r\n\tpublic List<Location> getSpawns() {\r\n\t\treturn spawns;\r\n\t}\r\n\t\r\n\tpublic int getGracePeriod() {\r\n\t\treturn graceperiod;\r\n\t}\r\n\t\r\n\tpublic String getName() {\r\n\t\treturn name;\r\n\t}\r\n\t\r\n\tpublic String getGame() {\r\n\t\treturn game;\r\n\t}\r\n\t\r\n\t// ADJUSTABLE DOME\r\n\tprivate Location domeMiddle;\r\n\tprivate int domeRadius;\r\n\t\r\n\tpublic Location getDomeMiddle() {\r\n\t\treturn domeMiddle;\r\n\t}\r\n\t\r\n\tpublic int getDomeRadius() {\r\n\t\treturn domeRadius;\r\n\t}\r\n\t\r\n\tpublic double domeDistance(Location loc) {\r\n\t\tLocation bloc = loc.clone();\r\n\t\tbloc.setY(0);\r\n\t\treturn domeMiddle.distance(bloc);\r\n\t}\r\n\t\r\n\tpublic boolean isDomeEnabled() {\r\n\t\treturn domeMiddle != null;\r\n\t}\r\n\t\r\n}\r", "public class MessageHandler {\r\n\t\r\n\tprivate static HashMap<String, String> messages = new HashMap<>();\r\n\tprivate static List<String> withoutPrefix = new ArrayList<>();\r\n\t\r\n\tpublic static void reload() {\r\n\t\tmessages.clear();\r\n\t\tfor(String key : SurvivalGames.messages.getConfigurationSection(\"\").getKeys(false)) {\r\n\t\t\tmessages.put(key, replaceColors(SurvivalGames.messages.getString(key)));\r\n\t\t}\r\n\t\t\r\n\t\twithoutPrefix.add(\"prefix\");\r\n\t\twithoutPrefix.add(\"stats-kills\");\r\n\t\twithoutPrefix.add(\"stats-deaths\");\r\n\t\twithoutPrefix.add(\"stats-kdr\");\r\n\t\twithoutPrefix.add(\"stats-wins\");\r\n\t\twithoutPrefix.add(\"stats-played\");\r\n\t\twithoutPrefix.add(\"stats-points\");\r\n\t\twithoutPrefix.add(\"stats-footer\");\r\n\t\t\r\n\t\tSystem.out.println(\"[SurvivalGames] \" + messages.size() + \" messages loaded!\");\r\n\t}\r\n\t\r\n\tpublic static String getMessage(String name) {\r\n\t\tif(messages.containsKey(name)) {\r\n\t\t\tif(withoutPrefix.contains(name)) {\r\n\t\t\t\treturn messages.get(name);\r\n\t\t\t} else {\r\n\t\t\t\treturn messages.get(\"prefix\") + messages.get(name);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\treturn \"§cMessage not found!\";\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static String replaceColors(String s) {\r\n\t\treturn ChatColor.translateAlternateColorCodes('&', s);\r\n\t}\r\n\r\n}\r", "public class CooldownPhase {\r\n\t\r\n\tprivate Game game;\r\n\tprivate BukkitTask task;\r\n\tprivate boolean running;\r\n\tprivate int time;\r\n\tprivate Arena arena;\r\n\t\r\n\tpublic CooldownPhase(Game game, Arena arena) {\r\n\t\tthis.game = game;\r\n\t\tthis.arena = arena;\r\n\t}\r\n\t\r\n\tpublic void load() {\r\n\t\tgame.setCurrentArena(arena);\r\n\t\ttime = game.getCooldownTime();\r\n\t\tgame.setState(GameState.COOLDOWN);\r\n\t\tgame.setScoreboardPhase(SurvivalGames.getScoreboardManager().getNewScoreboardPhase(GameState.COOLDOWN));\r\n\t\tgame.updateScoreboard();\r\n\t\tstart();\r\n\t}\r\n\t\r\n\tpublic void start() {\r\n\t\trunning = true;\r\n\t\t\r\n\t\tif(game.getArenas().size() > 1) {\r\n\t\t\tfor(int i = 0; i < game.getUsers().size(); i++) {\r\n\t\t\t\tUser user = game.getUsers().get(i);\r\n\t\t\t\t\r\n\t\t\t\tuser.setSpawnIndex(i);\r\n\t\t\t\tuser.getPlayer().teleport(arena.getSpawns().get(i));\r\n\t\t\t\t\r\n\t\t\t\tfor(User ouser : game.getUsers()) {\r\n\t\t\t\t\tuser.getPlayer().showPlayer(ouser.getPlayer());\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\t\r\n\t\ttask = Bukkit.getScheduler().runTaskTimer(SurvivalGames.instance, new Runnable() {\r\n\t\t\tpublic void run() {\r\n\t\t\t\t\r\n\t\t\t\tfor(User user : game.getUsers()) {\r\n\t\t\t\t\tuser.getPlayer().setLevel(time);\r\n\t\t\t\t\tuser.getPlayer().setExp(Util.getExpPercent((float)time, (float)game.getCooldownTime()));\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif(time == 27) {\r\n\t\t\t\t\tgame.sendMessage(MessageHandler.getMessage(\"prefix\") + \"MAPINFO §7- §eName: §b\" + arena.getName());\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif(time > 0 && (time % 5 == 0 || (time <= 10 && time > 0))) {\r\n\t\t\t\t\tgame.sendMessage(MessageHandler.getMessage(\"game-cooldown\").replace(\"%0%\", Util.getFormatedTime(time)));\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif(time <= 5 && time > 0) {\r\n\t\t\t\t\tfor(User user : game.getUsers()) {\r\n\t\t\t\t\t\tuser.getPlayer().playSound(user.getPlayer().getLocation(), Sound.NOTE_STICKS, 8.0F, 1.0F);\r\n\t\t\t\t\t}\r\n\t\t\t\t} else if(time == 0) {\r\n\t\t\t\t\tfor(User user : game.getUsers()) {\r\n\t\t\t\t\t\tuser.getPlayer().playSound(user.getPlayer().getLocation(), Sound.NOTE_PLING, 8.0F, 1.0F);\r\n\t\t\t\t\t\tuser.clearInventory();\r\n\t\t\t\t\t}\r\n\t\t\t\t\ttask.cancel();\r\n\t\t\t\t\trunning = false;\r\n\t\t\t\t\ttime = game.getCooldownTime();\r\n\t\t\t\t\tgame.startIngame();\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tgame.updateScoreboard();\r\n\t\t\t\ttime--;\r\n\t\t\t}\r\n\t\t}, 0L, 20L);\r\n\t}\r\n\t\r\n\tpublic int getTime() {\r\n\t\treturn time;\r\n\t}\r\n\t\r\n\tpublic void cancelTask() {\r\n\t\tif(task != null)\r\n\t\t\ttask.cancel();\r\n\t\trunning = false;\r\n\t\ttime = game.getCooldownTime();\r\n\t}\r\n\t\r\n\tpublic boolean isRunning() {\r\n\t\treturn running;\r\n\t}\r\n\r\n}\r", "public class DeathmatchPhase {\r\n\t\r\n\tprivate int time = 600, starttime = time;\r\n\tprivate BukkitTask task;\r\n\tprivate Game game;\r\n\t\r\n\tpublic DeathmatchPhase(Game game) {\r\n\t\tthis.game = game;\r\n\t}\r\n\t\r\n\tpublic void load() {\r\n\t\tgame.setScoreboardPhase(SurvivalGames.getScoreboardManager().getNewScoreboardPhase(GameState.DEATHMATCH));\r\n\t\tstart();\r\n\t}\r\n\t\r\n\tpublic void start() {\r\n\t\tgame.sendMessage(MessageHandler.getMessage(\"game-deathmatch-start\"));\r\n\t\tgame.setState(GameState.DEATHMATCH);\r\n\t\t\r\n\t\tList<Location> spawns = game.getCurrentArena().getDeathmatchSpawns();\r\n\t\tint i = 0;\r\n\t\tfor(User user : game.getUsers()) {\r\n\t\t\tif(i >= spawns.size())\r\n\t\t\t\ti = 0;\r\n\t\t\tuser.getPlayer().teleport(spawns.get(i));\r\n\t\t\ti++;\r\n\t\t}\r\n\t\t\r\n\t\tLocation suloc = spawns.get(0);\r\n\t\tfor(SpectatorUser su : game.getSpecators()) {\r\n\t\t\tsu.getPlayer().teleport(suloc);\r\n\t\t\tVector v = new Vector(0, 2, 0);\r\n\t\t\tv.multiply(1.25);\r\n\t\t\tsu.getPlayer().getLocation().setDirection(v);\r\n\t\t}\r\n\t\t\r\n\t\ttask = Bukkit.getScheduler().runTaskTimer(SurvivalGames.instance, new Runnable() {\r\n\t\t\tpublic void run() {\r\n\t\t\t\tif(time == 60) {\r\n\t\t\t\t\tgame.sendMessage(MessageHandler.getMessage(\"game-deathmatch-timeout-warning\"));\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\tif(time % 60 == 0 && time != 0) {\r\n\t\t\t\t\tgame.sendMessage(MessageHandler.getMessage(\"game-deathmatch-timeout\").replace(\"%0%\", Util.getFormatedTime(time)));\r\n\t\t\t\t} else if(time % 10 == 0 && time < 60 && time > 10) {\r\n\t\t\t\t\tgame.sendMessage(MessageHandler.getMessage(\"game-deathmatch-timeout\").replace(\"%0%\", Util.getFormatedTime(time)));\r\n\t\t\t\t} else if(time <= 10 && time > 0) {\r\n\t\t\t\t\tgame.sendMessage(MessageHandler.getMessage(\"game-deathmatch-timeout\").replace(\"%0%\", Util.getFormatedTime(time)));\r\n\t\t\t\t} else if(time == 0) {\r\n\t\t\t\t\tArena a = game.getCurrentArena();\r\n\t\t\t\t\tUser user = null;\r\n\t\t\t\t\t\r\n\t\t\t\t\tif(a.isDomeEnabled()) {\r\n\t\t\t\t\t\tdouble nearest = a.getDomeRadius() + 50;\r\n\t\t\t\t\t\tfor(User u : game.getUsers()) {\r\n\t\t\t\t\t\t\tdouble distance = a.domeDistance(u.getPlayer().getLocation());\r\n\t\t\t\t\t\t\tif(distance <= nearest) {\r\n\t\t\t\t\t\t\t\tnearest = distance;\r\n\t\t\t\t\t\t\t\tuser = u;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tCollections.shuffle(game.getUsers());\r\n\t\t\t\t\t\tuser = game.getUsers().get(0);\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\tfor(User u : game.getUsers()) {\r\n\t\t\t\t\t\tif(!u.equals(user)) {\r\n\t\t\t\t\t\t\tu.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.WITHER, 10000000, 3));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\r\n\t\t\t\tgame.updateScoreboard();\r\n\t\t\t\ttime--;\r\n\t\t\t}\r\n\t\t}, 0L, 20L);\r\n\t}\r\n\t\r\n\tpublic int getTime() {\r\n\t\treturn time;\r\n\t}\r\n\t\r\n\t\r\n\tpublic void cancelTask() {\r\n\t\tif(task != null)\r\n\t\t\ttask.cancel();\r\n\t}\r\n\t\r\n\tpublic int getStartTime() {\r\n\t\treturn starttime;\r\n\t}\r\n\r\n}\r", "public class IngamePhase {\r\n\r\n\tprivate Game game;\r\n\tpublic BukkitTask task;\r\n\tprivate boolean running;\r\n\tprivate int time;\r\n\tprivate UserManager um = SurvivalGames.userManger;\r\n\tprivate boolean braodcastWin = SurvivalGames.instance.getConfig().getBoolean(\"broadcast-win\");\r\n\t\r\n\tprivate boolean lightningOD = SurvivalGames.instance.getConfig().getBoolean(\"Lightning.on-death\");\r\n\tprivate boolean lightningFP = SurvivalGames.instance.getConfig().getBoolean(\"Lightning.on-few-players\");\r\n\tprivate int lightningFPc = SurvivalGames.instance.getConfig().getInt(\"Lightning.few-players\");\r\n\tprivate int lightningFPt = SurvivalGames.instance.getConfig().getInt(\"Lightning.few-players-time\");\r\n\tprivate BukkitTask lTask;\r\n\t\r\n\tpublic boolean grace = false;\r\n\tprivate int period; \r\n\t\r\n\t// GAME STATISTIC\r\n\tprivate long start = System.currentTimeMillis();\r\n\tprivate int players;\r\n\t// GAME STATISTIC END\r\n\t\r\n\tprivate BukkitTask deathmatch, chestrefill, gracetask;\r\n\t\r\n\tpublic IngamePhase(Game game) {\r\n\t\tthis.game = game;\r\n\t\tthis.period = game.getCurrentArena().getGracePeriod();\r\n\t\tthis.time = game.getCurrentArena().getAutomaticlyDeathmatchTime();\r\n\t}\r\n\t\r\n\tpublic void load() {\r\n\t\tgame.setScoreboardPhase(SurvivalGames.getScoreboardManager().getNewScoreboardPhase(GameState.INGAME));\r\n\t\tstart();\r\n\t}\r\n\t\r\n\tpublic void start() {\t\t\r\n\t\tgame.setState(GameState.INGAME);\r\n\t\tgame.sendMessage(MessageHandler.getMessage(\"game-start\").replace(\"%0%\", Integer.valueOf(game.getPlayingUsers()).toString()));\r\n\t\trunning = true;\r\n\t\tgame.redefinePlayerNavigatorInventory();\r\n\t\tplayers = game.getPlayingUsers();\r\n\t\t\r\n\t\tgame.getCurrentArena().getMinimumLocation().getWorld().setTime(0);\r\n\t\t\r\n\t\tif(game.getCurrentArena().chestRefill()) {\r\n\t\t\tchestrefill = Bukkit.getScheduler().runTaskLater(SurvivalGames.instance, new Runnable() {\r\n\t\t\t\tpublic void run() {\r\n\t\t\t\t\tlong time = game.getCurrentArena().getMinimumLocation().getWorld().getTime();\r\n\t\t\t\t\tif(time >= 18000 && time <= 18200) {\r\n\t\t\t\t\t\tfor(Chest c : game.getRegisteredChests()) {\r\n\t\t\t\t\t\t\tc.getLocation().getWorld().playEffect(c.getLocation(), Effect.MOBSPAWNER_FLAMES, 1);\r\n\t\t\t\t\t\t\tc.getLocation().getWorld().playSound(c.getLocation(), Sound.LEVEL_UP, 4.0F, 1.0F);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tgame.getRegisteredChests().clear();\r\n\t\t\t\t\t\tgame.sendMessage(MessageHandler.getMessage(\"game-chestrefill\"));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}, 18001);\r\n\t\t}\r\n\t\t\r\n\t\tif(period != 0) {\r\n\t\t\tgame.sendMessage(MessageHandler.getMessage(\"game-grace-period\").replace(\"%0%\", Integer.valueOf(period).toString()));\r\n\t\t\tgrace = true;\r\n\t\t\t\r\n\t\t\tgracetask = Bukkit.getScheduler().runTaskLater(SurvivalGames.instance, new Runnable() {\r\n\t\t\t\tpublic void run() {\r\n\t\t\t\t\tgame.sendMessage(MessageHandler.getMessage(\"game-grace-period-ended\"));\r\n\t\t\t\t\tgrace = false;\r\n\t\t\t\t\tstartTask();\r\n\t\t\t\t}\r\n\t\t\t}, period * 20);\r\n\t\t} else {\r\n\t\t\tstartTask();\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate void startTask() {\r\n\t\tif(lightningFP) {\r\n\t\t\tstartLightningTask();\r\n\t\t}\r\n\t\ttask = Bukkit.getScheduler().runTaskTimer(SurvivalGames.instance, new Runnable() {\r\n\t\t\tpublic void run() {\r\n\t\t\t\t\r\n\t\t\t\tif(game.getCurrentArena().isDeathmatchEnabled()) {\r\n\t\t\t\t\tif(time % 600 == 0 && time > 300) {\r\n\t\t\t\t\t\tgame.sendMessage(MessageHandler.getMessage(\"game-deathmatch-cooldown\").replace(\"%0%\", Util.getFormatedTime(time)));\r\n\t\t\t\t\t} else if(time <= 300 && time % 60 == 0 && time > 60) {\r\n\t\t\t\t\t\tgame.sendMessage(MessageHandler.getMessage(\"game-deathmatch-cooldown\").replace(\"%0%\", Util.getFormatedTime(time)));\r\n\t\t\t\t\t} else if(time <= 60 && time % 10 == 0 && time > 10) {\r\n\t\t\t\t\t\tgame.sendMessage(MessageHandler.getMessage(\"game-deathmatch-cooldown\").replace(\"%0%\", Util.getFormatedTime(time)));\r\n\t\t\t\t\t} else if(time <= 10 && time > 0) {\r\n\t\t\t\t\t\tgame.sendMessage(MessageHandler.getMessage(\"game-deathmatch-cooldown\").replace(\"%0%\", Util.getFormatedTime(time)));\r\n\t\t\t\t\t} else if(time == 0) {\r\n\t\t\t\t\t\tcancelTask();\r\n\t\t\t\t\t\tcancelLightningTask();\r\n\t\t\t\t\t\tgame.startDeathmatch();\r\n\t\t\t\t\t\treturn;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tgame.updateScoreboard();\r\n\t\t\t\ttime--;\r\n\t\t\t}\r\n\t\t}, 0L, 20L);\r\n\t}\r\n\t\r\n\tpublic void killUser(User user, User killer, boolean leave, boolean spectate) {\r\n\t\tint remain = game.getUsers().size() - 1;\r\n\t\t\r\n\t\t// STATISTIC\r\n\t\tuser.getStatistics().addPlayed();\r\n\t\tuser.getStatistics().addDeath();\r\n\t\t\r\n\t\tif(leave) {\r\n\t\t\tgame.sendMessage(MessageHandler.getMessage(\"game-player-left\").replace(\"%0%\", user.getName()));\r\n\t\t} else {\r\n\t\t\tif(killer == null) {\r\n\t\t\t\tgame.sendMessage(MessageHandler.getMessage(\"game-player-die-damage\").replace(\"%0%\", user.getName()));\r\n\t\t\t} else {\r\n\t\t\t\t// STATISTIC\r\n\t\t\t\tkiller.getStatistics().addKill();\r\n\t\t\t\tgame.sendMessage(MessageHandler.getMessage(\"game-player-die-killer\").replace(\"%0%\", user.getName()).replace(\"%1%\", killer.getName()));\r\n\t\t\t\tdouble killMoney = game.getCurrentArena().getMoneyOnKill();\r\n\t\t\t\tif(killMoney > 0 && SurvivalGames.econ != null) {\r\n\t\t\t\t\tSurvivalGames.econ.depositPlayer(killer.getName(), killMoney);\r\n\t\t\t\t\tkiller.sendMessage(MessageHandler.getMessage(\"arena-money-kill\").replace(\"%0%\", Double.valueOf(killMoney).toString()).replace(\"%1%\", user.getName()));\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t// KILL STATISTIC\r\n\t\t\t\tDatabaseThread.addTask(new DatabaseTask(\"INSERT INTO `\" + DatabaseManager.tablePrefix + \"kills` \" +\r\n\t\t\t\t\t\t\"(`player`, `victim`, `health`, `time`) \" +\r\n\t\t\t\t\t\t\"VALUES ('\" + killer.getPlayer().getUniqueId().toString() + \"',\" +\r\n\t\t\t\t\t\t\"'\" + user.getPlayer().getUniqueId().toString() + \"',\" +\r\n\t\t\t\t\t\t\"'\" + (int)((Damageable)killer.getPlayer()).getHealth() + \"',\" +\r\n\t\t\t\t\t\t\"'\" + new Date(System.currentTimeMillis()) + \"')\"));\r\n\t\t\t\t// KILL STATISTIC END\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tgame.sendMessage(MessageHandler.getMessage(\"game-remainplayers\").replace(\"%0%\", Integer.valueOf(remain).toString()));\r\n\t\tif(lightningOD)\r\n\t\t\tuser.getPlayer().getWorld().strikeLightningEffect(user.getPlayer().getLocation());\r\n\t\t\r\n\t\tfor(ItemStack is : user.getPlayer().getInventory().getContents()) {\r\n\t\t\tif(is == null || is.getType() == Material.AIR)\r\n\t\t\t\tcontinue;\r\n\t\t\tuser.getPlayer().getWorld().dropItemNaturally(user.getPlayer().getLocation(), is);\r\n\t\t}\r\n\t\t\r\n\t\tfor(ItemStack is : user.getPlayer().getInventory().getArmorContents()) {\r\n\t\t\tif(is == null || is.getType() == Material.AIR)\r\n\t\t\t\tcontinue;\r\n\t\t\tuser.getPlayer().getWorld().dropItemNaturally(user.getPlayer().getLocation(), is);\r\n\t\t}\r\n\t\tfinal Player p = user.getPlayer();\r\n\t\t\r\n\t\tum.leaveGame(p);\r\n\t\tgame.setDeathAmount(game.getDeathAmount() + 1);\r\n\t\tgame.updateScoreboard();\r\n\t\t\r\n\t\tif(remain == 1) {\r\n\t\t\tUser winner = game.getUsers().get(0);\r\n\t\t\t// STATISTIC\r\n\t\t\twinner.getStatistics().addWin();\r\n\t\t\twinner.getStatistics().addPlayed();\r\n\t\t\t\r\n\t\t\tif(braodcastWin) {\r\n\t\t\t\tBukkit.broadcastMessage(MessageHandler.getMessage(\"game-win\").replace(\"%0%\", winner.getName()).replace(\"%1%\", game.getCurrentArena().getName()).replace(\"%2%\", game.getName()));\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\twinner.sendMessage(MessageHandler.getMessage(\"game-win-winner-message\").replace(\"%0%\", game.getCurrentArena().getName()));\r\n\t\t\tdouble winMoney = game.getCurrentArena().getMoneyOnWin();\r\n\t\t\tif(winMoney > 0 && SurvivalGames.econ != null) {\r\n\t\t\t\tSurvivalGames.econ.depositPlayer(winner.getName(), winMoney);\r\n\t\t\t\twinner.sendMessage(MessageHandler.getMessage(\"arena-money-win\").replace(\"%0%\", Double.valueOf(winMoney).toString()));\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t// GAME STATISTIC\r\n\t\t\tDatabaseThread.addTask(new DatabaseTask(\"INSERT INTO `\" + DatabaseManager.tablePrefix + \"games` \" +\r\n\t\t\t\t\t\"(`arena`, `duration`, `end`, `players`, `winner`) \" +\r\n\t\t\t\t\t\"VALUES ('\" + game.getCurrentArena().getName() + \"',\" +\r\n\t\t\t\t\t\"'\" + (System.currentTimeMillis() - start) / 1000 + \"',\" +\r\n\t\t\t\t\t\"'\" + new Date(System.currentTimeMillis()) + \"',\" +\r\n\t\t\t\t\t\"'\" + players + \"',\" +\r\n\t\t\t\t\t\"'\" + winner.getPlayer().getUniqueId().toString() + \"')\"));\r\n\t\t\t// GAME STATISTIC END\r\n\t\t\t\r\n\t\t\tgame.startFinish();\r\n\t\t} else {\r\n\t\t\tif(spectate) {\r\n\t\t\t\tif(PermissionHandler.hasPermission(p, Permission.SPECTATE)) {\r\n\t\t\t\t\tBukkit.getScheduler().scheduleSyncDelayedTask(SurvivalGames.instance, new Runnable() {\r\n\t\t\t\t\t\tpublic void run() {\r\n\t\t\t\t\t\t\tum.joinGameAsSpectator(p, game.getName());\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}, 2L);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif(remain == game.getCurrentArena().getPlayerDeathmatchAmount() && game.getCurrentArena().isDeathmatchEnabled())\r\n\t\t\t\tstartDeathmatchTask();\r\n\t\t}\r\n\r\n\t}\r\n\t\r\n\tpublic void startDeathmatchTask() {\r\n\t\tif(game.getDeathmatch() != null)\r\n\t\t\treturn;\r\n\t\t\r\n\t\tcancelTask();\r\n\t\t\r\n\t\tdeathmatch = Bukkit.getScheduler().runTaskTimer(SurvivalGames.instance, new Runnable() {\r\n\t\t\tint time = 60;\r\n\t\t\tpublic void run() {\r\n\t\t\t\t\r\n\t\t\t\tif(time % 10 == 0 && time > 10) {\r\n\t\t\t\t\tgame.sendMessage(MessageHandler.getMessage(\"game-deathmatch-cooldown\").replace(\"%0%\", Util.getFormatedTime(time)));\r\n\t\t\t\t} else if(time <= 10 && time > 0) {\r\n\t\t\t\t\tgame.sendMessage(MessageHandler.getMessage(\"game-deathmatch-cooldown\").replace(\"%0%\", Util.getFormatedTime(time)));\r\n\t\t\t\t} else if(time == 0) {\r\n\t\t\t\t\tcancelDeathmatchTask();\r\n\t\t\t\t\tcancelLightningTask();\r\n\t\t\t\t\tgame.startDeathmatch();\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\ttime--;\r\n\t\t\t}\r\n\t\t}, 0L, 20L);\r\n\t}\r\n\t\r\n\tpublic int getTime() {\r\n\t\treturn time;\r\n\t}\r\n\t\r\n\tpublic void startLightningTask() {\r\n\t\tlTask = Bukkit.getScheduler().runTaskTimer(SurvivalGames.instance, new Runnable() {\r\n\t\t\tpublic void run() {\r\n\t\t\t\tif(game.getPlayingUsers() <= lightningFPc && !game.getCurrentArena().isDeathmatchEnabled()) {\r\n\t\t\t\t\tfor(User user : game.getUsers()) {\r\n\t\t\t\t\t\tuser.getPlayer().getWorld().strikeLightningEffect(user.getPlayer().getLocation());\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}, lightningFPt * 20L, lightningFPt * 20L);\r\n\t}\r\n\t\r\n\tpublic void cancelLightningTask() {\r\n\t\tif(lTask != null)\r\n\t\t\tlTask.cancel();\r\n\t}\r\n\t\r\n\tpublic void cancelTask() {\r\n\t\tif(task != null)\r\n\t\t\ttask.cancel();\r\n\t\tif(chestrefill != null)\r\n\t\t\tchestrefill.cancel();\r\n\t\tif(gracetask != null)\r\n\t\t\tgracetask.cancel();\r\n\t}\r\n\t\r\n\tpublic void cancelDeathmatchTask() {\r\n\t\tif(deathmatch != null)\r\n\t\t\tdeathmatch.cancel();\r\n\t}\r\n\t\r\n\tpublic boolean isRunning() {\r\n\t\treturn running;\r\n\t}\r\n}\r", "public class VotingPhase {\r\n\t\r\n\t// STATIC VARIABLES\r\n\tprivate static ItemStack voteItem, arenaItem;\r\n\tprivate static String title;\r\n\t\r\n\tpublic static ItemStack getVotingOpenItemStack() {\r\n\t\treturn voteItem;\r\n\t}\r\n\t\r\n\tpublic static String getVotingInventoryTitle() {\r\n\t\treturn title;\r\n\t}\r\n\t\r\n\tpublic static void reinitializeDatabase() {\r\n\t\tvoteItem = Util.parseItemStack(SurvivalGames.instance.getConfig().getString(\"Voting.Item\"));\r\n\t\tarenaItem = Util.parseItemStack(SurvivalGames.instance.getConfig().getString(\"Voting.ArenaItem\"));\r\n\t\ttitle = SurvivalGames.instance.getConfig().getString(\"Voting.InventoryTitle\");\r\n\t\tif(title.length() > 32) {\r\n\t\t\ttitle = title.substring(0, 32);\r\n\t\t}\r\n\t\ttitle = ChatColor.translateAlternateColorCodes('&', title);\r\n\t}\r\n\t\r\n\tprivate Game game;\r\n\tprivate BukkitTask task;\r\n\tprivate boolean running = false;\r\n\tprivate int time;\r\n\t\r\n\tpublic ArrayList<Arena> voteArenas = new ArrayList<Arena>();\r\n\tprivate Inventory voteInventory;\r\n\t\r\n\t\r\n\tpublic VotingPhase(Game game) {\r\n\t\treinitializeDatabase();\r\n\t\tthis.game = game;\r\n\r\n\t}\r\n\t\r\n\tpublic void load() {\r\n\t\tgame.setState(GameState.VOTING);\r\n\t\tchooseRandomArenas();\r\n\t\tgame.setScoreboardPhase(SurvivalGames.getScoreboardManager().getNewScoreboardPhase(GameState.VOTING));\r\n\t\ttime = game.getLobbyTime();\r\n\t\tstart();\r\n\t}\r\n\t\r\n\tpublic void start() {\r\n\t\trunning = true;\r\n\t\t\r\n\t\tif(game.isVotingEnabled()) {\r\n\t\t\tif(voteItem != null) {\r\n\t\t\t\tgenerateInventory();\r\n\t\t\t\tfor(User user : game.getUsers()) {\r\n\t\t\t\t\tequipPlayer(user);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\ttask = Bukkit.getScheduler().runTaskTimer(SurvivalGames.instance, new Runnable() {\r\n\t\t\tpublic void run() {\r\n\t\t\t\t\r\n\t\t\t\tfor(User user : game.getUsers()) {\r\n\t\t\t\t\tuser.getPlayer().setLevel(time);\r\n\t\t\t\t\tuser.getPlayer().setExp(Util.getExpPercent((float)time, (float)game.getLobbyTime()));\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif(time % 10 == 0 && time > 10) {\r\n\t\t\t\t\tgame.sendMessage(MessageHandler.getMessage(\"game-voting-cooldown\").replace(\"%0%\", Util.getFormatedTime(time)));\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif(time % 15 == 0 && time != 0) {\r\n\t\t\t\t\tsendVoteMessage();\r\n\t\t\t\t} else if(time <= 10 && time > 0){\r\n\t\t\t\t\tgame.sendMessage(MessageHandler.getMessage(\"game-voting-cooldown\").replace(\"%0%\", Util.getFormatedTime(time)));\r\n\t\t\t\t} else if(time == 0) {\r\n\t\t\t\t\tfor(User user : game.getUsers()) {\r\n\t\t\t\t\t\tuser.getPlayer().getInventory().setItem(1, null);\r\n\t\t\t\t\t\tuser.getPlayer().updateInventory();\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\ttask.cancel();\r\n\t\t\t\t\trunning = false;\r\n\t\t\t\t\ttime = game.getLobbyTime();\r\n\t\t\t\t\tgame.sendMessage(MessageHandler.getMessage(\"game-voting-end\"));\r\n\t\t\t\t\tArena winner = getMostVotedArena();\r\n\t\t\t\t\twinner.getSpawns().get(0).getWorld().setTime(0);\r\n\t\t\t\t\t\r\n\t\t\t\t\tgame.startCooldown(winner);\r\n\t\t\t\t\tfor(Arena arena : voteArenas) {\r\n\t\t\t\t\t\tarena.setVotes(0);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tvoteArenas.clear();\r\n\t\t\t\t\tgame.getVotedUsers().clear();\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tgame.updateScoreboard();\r\n\t\t\t\ttime--;\r\n\r\n\t\t\t}\r\n\t\t}, 0L, 20L);\r\n\t}\r\n\t\r\n\tpublic Inventory getVotingInventory() {\r\n\t\treturn voteInventory;\r\n\t}\r\n\t\r\n\tpublic void equipPlayer(User user) {\r\n\t\tuser.getPlayer().getInventory().setItem(1, voteItem);\r\n\t\tuser.getPlayer().updateInventory();\r\n\t}\r\n\t\r\n\tpublic List<Arena> getArenas() {\r\n\t\treturn voteArenas;\r\n\t}\r\n\t\r\n\tpublic void generateInventory() {\r\n\t\tint arenas = voteArenas.size();\r\n\t\tint size = 9;\r\n\t\t\r\n\t\tif(arenas >= 9) {\r\n\t\t\tsize = 9;\r\n\t\t} else if(arenas >= 18) {\r\n\t\t\tsize = 18;\r\n\t\t} else if(arenas >= 27) {\r\n\t\t\tsize = 27;\r\n\t\t} else if(arenas >= 36) {\r\n\t\t\tsize = 36;\r\n\t\t} else if(arenas >= 45) {\r\n\t\t\tsize = 45;\r\n\t\t} else if(arenas >= 54) {\r\n\t\t\tsize = 54;\r\n\t\t}\r\n\t\t\r\n\t\tvoteInventory = Bukkit.createInventory(null, size, title);\r\n\t\t\r\n\t\tint place = size / arenas; \r\n\t\tint c = 0;\r\n\t\t\r\n\t\tfor(int i = 0; i < size; i++) {\r\n\t\t\tArena a;\r\n\t\t\ttry {\r\n\t\t\t\ta = voteArenas.get(i);\r\n\t\t\t} catch(IndexOutOfBoundsException e) {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif(a == null)\r\n\t\t\t\tbreak;\r\n\t\t\t\r\n\t\t\tItemStack is = arenaItem.clone();\r\n\t\t\tItemMeta im = is.getItemMeta();\r\n\t\t\tim.setDisplayName((i + 1) + \". §e§l\" + a.getName());\r\n\t\t\tis.setItemMeta(im);\r\n\t\t\t\r\n\t\t\tvoteInventory.setItem(c, is);\r\n\t\t\tc += place;\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic int getTime() {\r\n\t\treturn time;\r\n\t}\r\n\t\r\n\tpublic void setTime(int time) {\r\n\t\tthis.time = time;\r\n\t}\r\n\t\r\n\tpublic Arena getMostVotedArena() {\r\n\t\tArena mostVoted = null;\r\n\r\n\t\tint votes = 0;\r\n\t\tfor (Arena arena : voteArenas) {\r\n\t\t\tif (arena.getVotes() > votes) {\r\n\t\t\t\tvotes = arena.getVotes();\r\n\t\t\t\tmostVoted = arena;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tif(mostVoted == null)\r\n\t\t\tmostVoted = voteArenas.get(0);\r\n\t\treturn mostVoted;\r\n\t}\r\n\t\r\n\tpublic boolean canVote(String player) {\r\n\t\treturn !game.getVotedUsers().contains(player);\r\n\t}\r\n\r\n\r\n\tpublic Arena vote(Player p, int id) {\r\n\t\ttry {\r\n\t\t\tArena a = voteArenas.get(id - 1);\r\n\t\t\tif(a != null) {\r\n\t\t\t\tint amount = PermissionHandler.getVotePower(p);\r\n\t\t\t\ta.setVotes(a.getVotes() + amount);\r\n\t\t\t\tgame.getVotedUsers().add(p.getName());\r\n\t\t\t\tp.sendMessage(MessageHandler.getMessage(\"game-success-vote\").replace(\"%0%\", a.getName()));\r\n\t\t\t\tif(amount > 1) {\r\n\t\t\t\t\tp.sendMessage(MessageHandler.getMessage(\"game-extra-vote\").replace(\"%0%\", Integer.valueOf(amount).toString()));\r\n\t\t\t\t}\r\n\t\t\t\tgame.updateScoreboard();\r\n\t\t\t}\r\n\t\t\t\t\r\n\t\t\treturn a;\r\n\t\t} catch(IndexOutOfBoundsException e) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate void sendVoteMessage() {\r\n\t\tif(game.isVotingEnabled()) {\r\n\t\t\tif(voteItem == null) {\r\n\t\t\t\tgame.sendMessage(MessageHandler.getMessage(\"game-vote\"));\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tint i = 1;\r\n\t\t\tfor(Arena arena : voteArenas) {\r\n\t\t\t\tgame.sendMessage(new ComponentBuilder(\"§3\" + i + \"§7. §6\" + arena.getName() + \" §7(§e\" + arena.getVotes() + \"§7)\")\r\n\t\t\t\t.event(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(\"Click to vote for arena \" + arena.getName()).create()))\r\n\t\t\t\t.event(new ClickEvent(Action.RUN_COMMAND, \"/sg vote \" + i)).create());\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tprivate void chooseRandomArenas() {\r\n\t\tList<Arena> arenas = game.getArenas();\r\n\r\n\t\tvoteArenas.clear();\r\n\t\tCollections.shuffle(arenas);\r\n\r\n\t\tint i = 0;\r\n\t\tfor(Arena a : arenas) {\r\n\t\t\tif(i == game.getMaxVotingArenas())\r\n\t\t\t\tbreak;\r\n\t\t\tvoteArenas.add(a);\r\n\t\t\ti++;\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic boolean isRunning() {\r\n\t\treturn running;\r\n\t}\r\n\t\r\n\tpublic void cancelTask() {\r\n\t\tif(task != null)\r\n\t\t\ttask.cancel();\r\n\t\trunning = false;\r\n\t\tvoteArenas.clear();\r\n\t\ttime = game.getLobbyTime();\r\n\t\treturn;\r\n\t}\r\n\r\n}\r", "@SuppressWarnings(\"deprecation\")\r\npublic class Reset extends Thread {\r\n\t\r\n\tprivate static List<String> resets = new ArrayList<>();\r\n\t\r\n\t/*\r\n\t * This class contains parts of source code from worldedit!\r\n\t * \r\n\t * https://github.com/sk89q/worldedit/\r\n\t * \r\n\t * \r\n\t * GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007\r\n\t * \r\n\t * Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\r\n\t * Everyone is permitted to copy and distribute verbatim copies of this\r\n\t * license document, but changing it is not allowed.\r\n\t * \r\n\t * Preamble\r\n\t * \r\n\t * The GNU General Public License is a free, copyleft license for software\r\n\t * and other kinds of works.\r\n\t * \r\n\t * The licenses for most software and other practical works are designed to\r\n\t * take away your freedom to share and change the works. By contrast, the\r\n\t * GNU General Public License is intended to guarantee your freedom to share\r\n\t * and change all versions of a program--to make sure it remains free\r\n\t * software for all its users. We, the Free Software Foundation, use the GNU\r\n\t * General Public License for most of our software; it applies also to any\r\n\t * other work released this way by its authors. You can apply it to your\r\n\t * programs, too.\r\n\t * \r\n\t * When we speak of free software, we are referring to freedom, not price.\r\n\t * Our General Public Licenses are designed to make sure that you have the\r\n\t * freedom to distribute copies of free software (and charge for them if you\r\n\t * wish), that you receive source code or can get it if you want it, that\r\n\t * you can change the software or use pieces of it in new free programs, and\r\n\t * that you know you can do these things.\r\n\t * \r\n\t * To protect your rights, we need to prevent others from denying you these\r\n\t * rights or asking you to surrender the rights. Therefore, you have certain\r\n\t * responsibilities if you distribute copies of the software, or if you\r\n\t * modify it: responsibilities to respect the freedom of others.\r\n\t * \r\n\t * For example, if you distribute copies of such a program, whether gratis\r\n\t * or for a fee, you must pass on to the recipients the same freedoms that\r\n\t * you received. You must make sure that they, too, receive or can get the\r\n\t * source code. And you must show them these terms so they know their\r\n\t * rights.\r\n\t * \r\n\t * Developers that use the GNU GPL protect your rights with two steps: (1)\r\n\t * assert copyright on the software, and (2) offer you this License giving\r\n\t * you legal permission to copy, distribute and/or modify it.\r\n\t * \r\n\t * For the developers' and authors' protection, the GPL clearly explains\r\n\t * that there is no warranty for this free software. For both users' and\r\n\t * authors' sake, the GPL requires that modified versions be marked as\r\n\t * changed, so that their problems will not be attributed erroneously to\r\n\t * authors of previous versions.\r\n\t * \r\n\t * Some devices are designed to deny users access to install or run modified\r\n\t * versions of the software inside them, although the manufacturer can do\r\n\t * so. This is fundamentally incompatible with the aim of protecting users'\r\n\t * freedom to change the software. The systematic pattern of such abuse\r\n\t * occurs in the area of products for individuals to use, which is precisely\r\n\t * where it is most unacceptable. Therefore, we have designed this version\r\n\t * of the GPL to prohibit the practice for those products. If such problems\r\n\t * arise substantially in other domains, we stand ready to extend this\r\n\t * provision to those domains in future versions of the GPL, as needed to\r\n\t * protect the freedom of users.\r\n\t * \r\n\t * Finally, every program is threatened constantly by software patents.\r\n\t * States should not allow patents to restrict development and use of\r\n\t * software on general-purpose computers, but in those that do, we wish to\r\n\t * avoid the special danger that patents applied to a free program could\r\n\t * make it effectively proprietary. To prevent this, the GPL assures that\r\n\t * patents cannot be used to render the program non-free.\r\n\t * \r\n\t * The precise terms and conditions for copying, distribution and\r\n\t * modification follow.\r\n\t * \r\n\t * TERMS AND CONDITIONS\r\n\t * \r\n\t * 0. Definitions.\r\n\t * \r\n\t * \"This License\" refers to version 3 of the GNU General Public License.\r\n\t * \r\n\t * \"Copyright\" also means copyright-like laws that apply to other kinds of\r\n\t * works, such as semiconductor masks.\r\n\t * \r\n\t * \"The Program\" refers to any copyrightable work licensed under this\r\n\t * License. Each licensee is addressed as \"you\". \"Licensees\" and\r\n\t * \"recipients\" may be individuals or organizations.\r\n\t * \r\n\t * To \"modify\" a work means to copy from or adapt all or part of the work in\r\n\t * a fashion requiring copyright permission, other than the making of an\r\n\t * exact copy. The resulting work is called a \"modified version\" of the\r\n\t * earlier work or a work \"based on\" the earlier work.\r\n\t * \r\n\t * A \"covered work\" means either the unmodified Program or a work based on\r\n\t * the Program.\r\n\t * \r\n\t * To \"propagate\" a work means to do anything with it that, without\r\n\t * permission, would make you directly or secondarily liable for\r\n\t * infringement under applicable copyright law, except executing it on a\r\n\t * computer or modifying a private copy. Propagation includes copying,\r\n\t * distribution (with or without modification), making available to the\r\n\t * public, and in some countries other activities as well.\r\n\t * \r\n\t * To \"convey\" a work means any kind of propagation that enables other\r\n\t * parties to make or receive copies. Mere interaction with a user through a\r\n\t * computer network, with no transfer of a copy, is not conveying.\r\n\t * \r\n\t * An interactive user interface displays \"Appropriate Legal Notices\" to the\r\n\t * extent that it includes a convenient and prominently visible feature that\r\n\t * (1) displays an appropriate copyright notice, and (2) tells the user that\r\n\t * there is no warranty for the work (except to the extent that warranties\r\n\t * are provided), that licensees may convey the work under this License, and\r\n\t * how to view a copy of this License. If the interface presents a list of\r\n\t * user commands or options, such as a menu, a prominent item in the list\r\n\t * meets this criterion.\r\n\t * \r\n\t * 1. Source Code.\r\n\t * \r\n\t * The \"source code\" for a work means the preferred form of the work for\r\n\t * making modifications to it. \"Object code\" means any non-source form of a\r\n\t * work.\r\n\t * \r\n\t * A \"Standard Interface\" means an interface that either is an official\r\n\t * standard defined by a recognized standards body, or, in the case of\r\n\t * interfaces specified for a particular programming language, one that is\r\n\t * widely used among developers working in that language.\r\n\t * \r\n\t * The \"System Libraries\" of an executable work include anything, other than\r\n\t * the work as a whole, that (a) is included in the normal form of packaging\r\n\t * a Major Component, but which is not part of that Major Component, and (b)\r\n\t * serves only to enable use of the work with that Major Component, or to\r\n\t * implement a Standard Interface for which an implementation is available\r\n\t * to the public in source code form. A \"Major Component\", in this context,\r\n\t * means a major essential component (kernel, window system, and so on) of\r\n\t * the specific operating system (if any) on which the executable work runs,\r\n\t * or a compiler used to produce the work, or an object code interpreter\r\n\t * used to run it.\r\n\t * \r\n\t * The \"Corresponding Source\" for a work in object code form means all the\r\n\t * source code needed to generate, install, and (for an executable work) run\r\n\t * the object code and to modify the work, including scripts to control\r\n\t * those activities. However, it does not include the work's System\r\n\t * Libraries, or general-purpose tools or generally available free programs\r\n\t * which are used unmodified in performing those activities but which are\r\n\t * not part of the work. For example, Corresponding Source includes\r\n\t * interface definition files associated with source files for the work, and\r\n\t * the source code for shared libraries and dynamically linked subprograms\r\n\t * that the work is specifically designed to require, such as by intimate\r\n\t * data communication or control flow between those subprograms and other\r\n\t * parts of the work.\r\n\t * \r\n\t * The Corresponding Source need not include anything that users can\r\n\t * regenerate automatically from other parts of the Corresponding Source.\r\n\t * \r\n\t * The Corresponding Source for a work in source code form is that same\r\n\t * work.\r\n\t * \r\n\t * 2. Basic Permissions.\r\n\t * \r\n\t * All rights granted under this License are granted for the term of\r\n\t * copyright on the Program, and are irrevocable provided the stated\r\n\t * conditions are met. This License explicitly affirms your unlimited\r\n\t * permission to run the unmodified Program. The output from running a\r\n\t * covered work is covered by this License only if the output, given its\r\n\t * content, constitutes a covered work. This License acknowledges your\r\n\t * rights of fair use or other equivalent, as provided by copyright law.\r\n\t * \r\n\t * You may make, run and propagate covered works that you do not convey,\r\n\t * without conditions so long as your license otherwise remains in force.\r\n\t * You may convey covered works to others for the sole purpose of having\r\n\t * them make modifications exclusively for you, or provide you with\r\n\t * facilities for running those works, provided that you comply with the\r\n\t * terms of this License in conveying all material for which you do not\r\n\t * control copyright. Those thus making or running the covered works for you\r\n\t * must do so exclusively on your behalf, under your direction and control,\r\n\t * on terms that prohibit them from making any copies of your copyrighted\r\n\t * material outside their relationship with you.\r\n\t * \r\n\t * Conveying under any other circumstances is permitted solely under the\r\n\t * conditions stated below. Sublicensing is not allowed; section 10 makes it\r\n\t * unnecessary.\r\n\t * \r\n\t * 3. Protecting Users' Legal Rights From Anti-Circumvention Law.\r\n\t * \r\n\t * No covered work shall be deemed part of an effective technological\r\n\t * measure under any applicable law fulfilling obligations under article 11\r\n\t * of the WIPO copyright treaty adopted on 20 December 1996, or similar laws\r\n\t * prohibiting or restricting circumvention of such measures.\r\n\t * \r\n\t * When you convey a covered work, you waive any legal power to forbid\r\n\t * circumvention of technological measures to the extent such circumvention\r\n\t * is effected by exercising rights under this License with respect to the\r\n\t * covered work, and you disclaim any intention to limit operation or\r\n\t * modification of the work as a means of enforcing, against the work's\r\n\t * users, your or third parties' legal rights to forbid circumvention of\r\n\t * technological measures.\r\n\t * \r\n\t * 4. Conveying Verbatim Copies.\r\n\t * \r\n\t * You may convey verbatim copies of the Program's source code as you\r\n\t * receive it, in any medium, provided that you conspicuously and\r\n\t * appropriately publish on each copy an appropriate copyright notice; keep\r\n\t * intact all notices stating that this License and any non-permissive terms\r\n\t * added in accord with section 7 apply to the code; keep intact all notices\r\n\t * of the absence of any warranty; and give all recipients a copy of this\r\n\t * License along with the Program.\r\n\t * \r\n\t * You may charge any price or no price for each copy that you convey, and\r\n\t * you may offer support or warranty protection for a fee.\r\n\t * \r\n\t * 5. Conveying Modified Source Versions.\r\n\t * \r\n\t * You may convey a work based on the Program, or the modifications to\r\n\t * produce it from the Program, in the form of source code under the terms\r\n\t * of section 4, provided that you also meet all of these conditions:\r\n\t * \r\n\t * a) The work must carry prominent notices stating that you modified it,\r\n\t * and giving a relevant date.\r\n\t * \r\n\t * b) The work must carry prominent notices stating that it is released\r\n\t * under this License and any conditions added under section 7. This\r\n\t * requirement modifies the requirement in section 4 to\r\n\t * \"keep intact all notices\".\r\n\t * \r\n\t * c) You must license the entire work, as a whole, under this License to\r\n\t * anyone who comes into possession of a copy. This License will therefore\r\n\t * apply, along with any applicable section 7 additional terms, to the whole\r\n\t * of the work, and all its parts, regardless of how they are packaged. This\r\n\t * License gives no permission to license the work in any other way, but it\r\n\t * does not invalidate such permission if you have separately received it.\r\n\t * \r\n\t * d) If the work has interactive user interfaces, each must display\r\n\t * Appropriate Legal Notices; however, if the Program has interactive\r\n\t * interfaces that do not display Appropriate Legal Notices, your work need\r\n\t * not make them do so.\r\n\t * \r\n\t * A compilation of a covered work with other separate and independent\r\n\t * works, which are not by their nature extensions of the covered work, and\r\n\t * which are not combined with it such as to form a larger program, in or on\r\n\t * a volume of a storage or distribution medium, is called an \"aggregate\" if\r\n\t * the compilation and its resulting copyright are not used to limit the\r\n\t * access or legal rights of the compilation's users beyond what the\r\n\t * individual works permit. Inclusion of a covered work in an aggregate does\r\n\t * not cause this License to apply to the other parts of the aggregate.\r\n\t * \r\n\t * 6. Conveying Non-Source Forms.\r\n\t * \r\n\t * You may convey a covered work in object code form under the terms of\r\n\t * sections 4 and 5, provided that you also convey the machine-readable\r\n\t * Corresponding Source under the terms of this License, in one of these\r\n\t * ways:\r\n\t * \r\n\t * a) Convey the object code in, or embodied in, a physical product\r\n\t * (including a physical distribution medium), accompanied by the\r\n\t * Corresponding Source fixed on a durable physical medium customarily used\r\n\t * for software interchange.\r\n\t * \r\n\t * b) Convey the object code in, or embodied in, a physical product\r\n\t * (including a physical distribution medium), accompanied by a written\r\n\t * offer, valid for at least three years and valid for as long as you offer\r\n\t * spare parts or customer support for that product model, to give anyone\r\n\t * who possesses the object code either (1) a copy of the Corresponding\r\n\t * Source for all the software in the product that is covered by this\r\n\t * License, on a durable physical medium customarily used for software\r\n\t * interchange, for a price no more than your reasonable cost of physically\r\n\t * performing this conveying of source, or (2) access to copy the\r\n\t * Corresponding Source from a network server at no charge.\r\n\t * \r\n\t * c) Convey individual copies of the object code with a copy of the written\r\n\t * offer to provide the Corresponding Source. This alternative is allowed\r\n\t * only occasionally and noncommercially, and only if you received the\r\n\t * object code with such an offer, in accord with subsection 6b.\r\n\t * \r\n\t * d) Convey the object code by offering access from a designated place\r\n\t * (gratis or for a charge), and offer equivalent access to the\r\n\t * Corresponding Source in the same way through the same place at no further\r\n\t * charge. You need not require recipients to copy the Corresponding Source\r\n\t * along with the object code. If the place to copy the object code is a\r\n\t * network server, the Corresponding Source may be on a different server\r\n\t * (operated by you or a third party) that supports equivalent copying\r\n\t * facilities, provided you maintain clear directions next to the object\r\n\t * code saying where to find the Corresponding Source. Regardless of what\r\n\t * server hosts the Corresponding Source, you remain obligated to ensure\r\n\t * that it is available for as long as needed to satisfy these requirements.\r\n\t * \r\n\t * e) Convey the object code using peer-to-peer transmission, provided you\r\n\t * inform other peers where the object code and Corresponding Source of the\r\n\t * work are being offered to the general public at no charge under\r\n\t * subsection 6d.\r\n\t * \r\n\t * A separable portion of the object code, whose source code is excluded\r\n\t * from the Corresponding Source as a System Library, need not be included\r\n\t * in conveying the object code work.\r\n\t * \r\n\t * A \"User Product\" is either (1) a \"consumer product\", which means any\r\n\t * tangible personal property which is normally used for personal, family,\r\n\t * or household purposes, or (2) anything designed or sold for incorporation\r\n\t * into a dwelling. In determining whether a product is a consumer product,\r\n\t * doubtful cases shall be resolved in favor of coverage. For a particular\r\n\t * product received by a particular user, \"normally used\" refers to a\r\n\t * typical or common use of that class of product, regardless of the status\r\n\t * of the particular user or of the way in which the particular user\r\n\t * actually uses, or expects or is expected to use, the product. A product\r\n\t * is a consumer product regardless of whether the product has substantial\r\n\t * commercial, industrial or non-consumer uses, unless such uses represent\r\n\t * the only significant mode of use of the product.\r\n\t * \r\n\t * \"Installation Information\" for a User Product means any methods,\r\n\t * procedures, authorization keys, or other information required to install\r\n\t * and execute modified versions of a covered work in that User Product from\r\n\t * a modified version of its Corresponding Source. The information must\r\n\t * suffice to ensure that the continued functioning of the modified object\r\n\t * code is in no case prevented or interfered with solely because\r\n\t * modification has been made.\r\n\t * \r\n\t * If you convey an object code work under this section in, or with, or\r\n\t * specifically for use in, a User Product, and the conveying occurs as part\r\n\t * of a transaction in which the right of possession and use of the User\r\n\t * Product is transferred to the recipient in perpetuity or for a fixed term\r\n\t * (regardless of how the transaction is characterized), the Corresponding\r\n\t * Source conveyed under this section must be accompanied by the\r\n\t * Installation Information. But this requirement does not apply if neither\r\n\t * you nor any third party retains the ability to install modified object\r\n\t * code on the User Product (for example, the work has been installed in\r\n\t * ROM).\r\n\t * \r\n\t * The requirement to provide Installation Information does not include a\r\n\t * requirement to continue to provide support service, warranty, or updates\r\n\t * for a work that has been modified or installed by the recipient, or for\r\n\t * the User Product in which it has been modified or installed. Access to a\r\n\t * network may be denied when the modification itself materially and\r\n\t * adversely affects the operation of the network or violates the rules and\r\n\t * protocols for communication across the network.\r\n\t * \r\n\t * Corresponding Source conveyed, and Installation Information provided, in\r\n\t * accord with this section must be in a format that is publicly documented\r\n\t * (and with an implementation available to the public in source code form),\r\n\t * and must require no special password or key for unpacking, reading or\r\n\t * copying.\r\n\t * \r\n\t * 7. Additional Terms.\r\n\t * \r\n\t * \"Additional permissions\" are terms that supplement the terms of this\r\n\t * License by making exceptions from one or more of its conditions.\r\n\t * Additional permissions that are applicable to the entire Program shall be\r\n\t * treated as though they were included in this License, to the extent that\r\n\t * they are valid under applicable law. If additional permissions apply only\r\n\t * to part of the Program, that part may be used separately under those\r\n\t * permissions, but the entire Program remains governed by this License\r\n\t * without regard to the additional permissions.\r\n\t * \r\n\t * When you convey a copy of a covered work, you may at your option remove\r\n\t * any additional permissions from that copy, or from any part of it.\r\n\t * (Additional permissions may be written to require their own removal in\r\n\t * certain cases when you modify the work.) You may place additional\r\n\t * permissions on material, added by you to a covered work, for which you\r\n\t * have or can give appropriate copyright permission.\r\n\t * \r\n\t * Notwithstanding any other provision of this License, for material you add\r\n\t * to a covered work, you may (if authorized by the copyright holders of\r\n\t * that material) supplement the terms of this License with terms:\r\n\t * \r\n\t * a) Disclaiming warranty or limiting liability differently from the terms\r\n\t * of sections 15 and 16 of this License; or\r\n\t * \r\n\t * b) Requiring preservation of specified reasonable legal notices or author\r\n\t * attributions in that material or in the Appropriate Legal Notices\r\n\t * displayed by works containing it; or\r\n\t * \r\n\t * c) Prohibiting misrepresentation of the origin of that material, or\r\n\t * requiring that modified versions of such material be marked in reasonable\r\n\t * ways as different from the original version; or\r\n\t * \r\n\t * d) Limiting the use for publicity purposes of names of licensors or\r\n\t * authors of the material; or\r\n\t * \r\n\t * e) Declining to grant rights under trademark law for use of some trade\r\n\t * names, trademarks, or service marks; or\r\n\t * \r\n\t * f) Requiring indemnification of licensors and authors of that material by\r\n\t * anyone who conveys the material (or modified versions of it) with\r\n\t * contractual assumptions of liability to the recipient, for any liability\r\n\t * that these contractual assumptions directly impose on those licensors and\r\n\t * authors.\r\n\t * \r\n\t * All other non-permissive additional terms are considered \"further\r\n\t * restrictions\" within the meaning of section 10. If the Program as you\r\n\t * received it, or any part of it, contains a notice stating that it is\r\n\t * governed by this License along with a term that is a further restriction,\r\n\t * you may remove that term. If a license document contains a further\r\n\t * restriction but permits relicensing or conveying under this License, you\r\n\t * may add to a covered work material governed by the terms of that license\r\n\t * document, provided that the further restriction does not survive such\r\n\t * relicensing or conveying.\r\n\t * \r\n\t * If you add terms to a covered work in accord with this section, you must\r\n\t * place, in the relevant source files, a statement of the additional terms\r\n\t * that apply to those files, or a notice indicating where to find the\r\n\t * applicable terms.\r\n\t * \r\n\t * Additional terms, permissive or non-permissive, may be stated in the form\r\n\t * of a separately written license, or stated as exceptions; the above\r\n\t * requirements apply either way.\r\n\t * \r\n\t * 8. Termination.\r\n\t * \r\n\t * You may not propagate or modify a covered work except as expressly\r\n\t * provided under this License. Any attempt otherwise to propagate or modify\r\n\t * it is void, and will automatically terminate your rights under this\r\n\t * License (including any patent licenses granted under the third paragraph\r\n\t * of section 11).\r\n\t * \r\n\t * However, if you cease all violation of this License, then your license\r\n\t * from a particular copyright holder is reinstated (a) provisionally,\r\n\t * unless and until the copyright holder explicitly and finally terminates\r\n\t * your license, and (b) permanently, if the copyright holder fails to\r\n\t * notify you of the violation by some reasonable means prior to 60 days\r\n\t * after the cessation.\r\n\t * \r\n\t * Moreover, your license from a particular copyright holder is reinstated\r\n\t * permanently if the copyright holder notifies you of the violation by some\r\n\t * reasonable means, this is the first time you have received notice of\r\n\t * violation of this License (for any work) from that copyright holder, and\r\n\t * you cure the violation prior to 30 days after your receipt of the notice.\r\n\t * \r\n\t * Termination of your rights under this section does not terminate the\r\n\t * licenses of parties who have received copies or rights from you under\r\n\t * this License. If your rights have been terminated and not permanently\r\n\t * reinstated, you do not qualify to receive new licenses for the same\r\n\t * material under section 10.\r\n\t * \r\n\t * 9. Acceptance Not Required for Having Copies.\r\n\t * \r\n\t * You are not required to accept this License in order to receive or run a\r\n\t * copy of the Program. Ancillary propagation of a covered work occurring\r\n\t * solely as a consequence of using peer-to-peer transmission to receive a\r\n\t * copy likewise does not require acceptance. However, nothing other than\r\n\t * this License grants you permission to propagate or modify any covered\r\n\t * work. These actions infringe copyright if you do not accept this License.\r\n\t * Therefore, by modifying or propagating a covered work, you indicate your\r\n\t * acceptance of this License to do so.\r\n\t * \r\n\t * 10. Automatic Licensing of Downstream Recipients.\r\n\t * \r\n\t * Each time you convey a covered work, the recipient automatically receives\r\n\t * a license from the original licensors, to run, modify and propagate that\r\n\t * work, subject to this License. You are not responsible for enforcing\r\n\t * compliance by third parties with this License.\r\n\t * \r\n\t * An \"entity transaction\" is a transaction transferring control of an\r\n\t * organization, or substantially all assets of one, or subdividing an\r\n\t * organization, or merging organizations. If propagation of a covered work\r\n\t * results from an entity transaction, each party to that transaction who\r\n\t * receives a copy of the work also receives whatever licenses to the work\r\n\t * the party's predecessor in interest had or could give under the previous\r\n\t * paragraph, plus a right to possession of the Corresponding Source of the\r\n\t * work from the predecessor in interest, if the predecessor has it or can\r\n\t * get it with reasonable efforts.\r\n\t * \r\n\t * You may not impose any further restrictions on the exercise of the rights\r\n\t * granted or affirmed under this License. For example, you may not impose a\r\n\t * license fee, royalty, or other charge for exercise of rights granted\r\n\t * under this License, and you may not initiate litigation (including a\r\n\t * cross-claim or counterclaim in a lawsuit) alleging that any patent claim\r\n\t * is infringed by making, using, selling, offering for sale, or importing\r\n\t * the Program or any portion of it.\r\n\t * \r\n\t * 11. Patents.\r\n\t * \r\n\t * A \"contributor\" is a copyright holder who authorizes use under this\r\n\t * License of the Program or a work on which the Program is based. The work\r\n\t * thus licensed is called the contributor's \"contributor version\".\r\n\t * \r\n\t * A contributor's \"essential patent claims\" are all patent claims owned or\r\n\t * controlled by the contributor, whether already acquired or hereafter\r\n\t * acquired, that would be infringed by some manner, permitted by this\r\n\t * License, of making, using, or selling its contributor version, but do not\r\n\t * include claims that would be infringed only as a consequence of further\r\n\t * modification of the contributor version. For purposes of this definition,\r\n\t * \"control\" includes the right to grant patent sublicenses in a manner\r\n\t * consistent with the requirements of this License.\r\n\t * \r\n\t * Each contributor grants you a non-exclusive, worldwide, royalty-free\r\n\t * patent license under the contributor's essential patent claims, to make,\r\n\t * use, sell, offer for sale, import and otherwise run, modify and propagate\r\n\t * the contents of its contributor version.\r\n\t * \r\n\t * In the following three paragraphs, a \"patent license\" is any express\r\n\t * agreement or commitment, however denominated, not to enforce a patent\r\n\t * (such as an express permission to practice a patent or covenant not to\r\n\t * sue for patent infringement). To \"grant\" such a patent license to a party\r\n\t * means to make such an agreement or commitment not to enforce a patent\r\n\t * against the party.\r\n\t * \r\n\t * If you convey a covered work, knowingly relying on a patent license, and\r\n\t * the Corresponding Source of the work is not available for anyone to copy,\r\n\t * free of charge and under the terms of this License, through a publicly\r\n\t * available network server or other readily accessible means, then you must\r\n\t * either (1) cause the Corresponding Source to be so available, or (2)\r\n\t * arrange to deprive yourself of the benefit of the patent license for this\r\n\t * particular work, or (3) arrange, in a manner consistent with the\r\n\t * requirements of this License, to extend the patent license to downstream\r\n\t * recipients. \"Knowingly relying\" means you have actual knowledge that, but\r\n\t * for the patent license, your conveying the covered work in a country, or\r\n\t * your recipient's use of the covered work in a country, would infringe one\r\n\t * or more identifiable patents in that country that you have reason to\r\n\t * believe are valid.\r\n\t * \r\n\t * If, pursuant to or in connection with a single transaction or\r\n\t * arrangement, you convey, or propagate by procuring conveyance of, a\r\n\t * covered work, and grant a patent license to some of the parties receiving\r\n\t * the covered work authorizing them to use, propagate, modify or convey a\r\n\t * specific copy of the covered work, then the patent license you grant is\r\n\t * automatically extended to all recipients of the covered work and works\r\n\t * based on it.\r\n\t * \r\n\t * A patent license is \"discriminatory\" if it does not include within the\r\n\t * scope of its coverage, prohibits the exercise of, or is conditioned on\r\n\t * the non-exercise of one or more of the rights that are specifically\r\n\t * granted under this License. You may not convey a covered work if you are\r\n\t * a party to an arrangement with a third party that is in the business of\r\n\t * distributing software, under which you make payment to the third party\r\n\t * based on the extent of your activity of conveying the work, and under\r\n\t * which the third party grants, to any of the parties who would receive the\r\n\t * covered work from you, a discriminatory patent license (a) in connection\r\n\t * with copies of the covered work conveyed by you (or copies made from\r\n\t * those copies), or (b) primarily for and in connection with specific\r\n\t * products or compilations that contain the covered work, unless you\r\n\t * entered into that arrangement, or that patent license was granted, prior\r\n\t * to 28 March 2007.\r\n\t * \r\n\t * Nothing in this License shall be construed as excluding or limiting any\r\n\t * implied license or other defenses to infringement that may otherwise be\r\n\t * available to you under applicable patent law.\r\n\t * \r\n\t * 12. No Surrender of Others' Freedom.\r\n\t * \r\n\t * If conditions are imposed on you (whether by court order, agreement or\r\n\t * otherwise) that contradict the conditions of this License, they do not\r\n\t * excuse you from the conditions of this License. If you cannot convey a\r\n\t * covered work so as to satisfy simultaneously your obligations under this\r\n\t * License and any other pertinent obligations, then as a consequence you\r\n\t * may not convey it at all. For example, if you agree to terms that\r\n\t * obligate you to collect a royalty for further conveying from those to\r\n\t * whom you convey the Program, the only way you could satisfy both those\r\n\t * terms and this License would be to refrain entirely from conveying the\r\n\t * Program.\r\n\t * \r\n\t * 13. Use with the GNU Affero General Public License.\r\n\t * \r\n\t * Notwithstanding any other provision of this License, you have permission\r\n\t * to link or combine any covered work with a work licensed under version 3\r\n\t * of the GNU Affero General Public License into a single combined work, and\r\n\t * to convey the resulting work. The terms of this License will continue to\r\n\t * apply to the part which is the covered work, but the special requirements\r\n\t * of the GNU Affero General Public License, section 13, concerning\r\n\t * interaction through a network will apply to the combination as such.\r\n\t * \r\n\t * 14. Revised Versions of this License.\r\n\t * \r\n\t * The Free Software Foundation may publish revised and/or new versions of\r\n\t * the GNU General Public License from time to time. Such new versions will\r\n\t * be similar in spirit to the present version, but may differ in detail to\r\n\t * address new problems or concerns.\r\n\t * \r\n\t * Each version is given a distinguishing version number. If the Program\r\n\t * specifies that a certain numbered version of the GNU General Public\r\n\t * License \"or any later version\" applies to it, you have the option of\r\n\t * following the terms and conditions either of that numbered version or of\r\n\t * any later version published by the Free Software Foundation. If the\r\n\t * Program does not specify a version number of the GNU General Public\r\n\t * License, you may choose any version ever published by the Free Software\r\n\t * Foundation.\r\n\t * \r\n\t * If the Program specifies that a proxy can decide which future versions of\r\n\t * the GNU General Public License can be used, that proxy's public statement\r\n\t * of acceptance of a version permanently authorizes you to choose that\r\n\t * version for the Program.\r\n\t * \r\n\t * Later license versions may give you additional or different permissions.\r\n\t * However, no additional obligations are imposed on any author or copyright\r\n\t * holder as a result of your choosing to follow a later version.\r\n\t * \r\n\t * 15. Disclaimer of Warranty.\r\n\t * \r\n\t * THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\r\n\t * APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\r\n\t * HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\r\n\t * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\r\n\t * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\r\n\t * PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\r\n\t * IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\r\n\t * ALL NECESSARY SERVICING, REPAIR OR CORRECTION.\r\n\t * \r\n\t * 16. Limitation of Liability.\r\n\t * \r\n\t * IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\r\n\t * WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\r\n\t * THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING\r\n\t * ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF\r\n\t * THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO\r\n\t * LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU\r\n\t * OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\r\n\t * PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\r\n\t * POSSIBILITY OF SUCH DAMAGES.\r\n\t * \r\n\t * 17. Interpretation of Sections 15 and 16.\r\n\t * \r\n\t * If the disclaimer of warranty and limitation of liability provided above\r\n\t * cannot be given local legal effect according to their terms, reviewing\r\n\t * courts shall apply local law that most closely approximates an absolute\r\n\t * waiver of all civil liability in connection with the Program, unless a\r\n\t * warranty or assumption of liability accompanies a copy of the Program in\r\n\t * return for a fee.\r\n\t * \r\n\t * END OF TERMS AND CONDITIONS\r\n\t * \r\n\t * How to Apply These Terms to Your New Programs\r\n\t * \r\n\t * If you develop a new program, and you want it to be of the greatest\r\n\t * possible use to the public, the best way to achieve this is to make it\r\n\t * free software which everyone can redistribute and change under these\r\n\t * terms.\r\n\t * \r\n\t * To do so, attach the following notices to the program. It is safest to\r\n\t * attach them to the start of each source file to most effectively state\r\n\t * the exclusion of warranty; and each file should have at least the\r\n\t * \"copyright\" line and a pointer to where the full notice is found.\r\n\t * \r\n\t * {one line to give the program's name and a brief idea of what it does.}\r\n\t * Copyright (C) {year} {name of author}\r\n\t * \r\n\t * This program is free software: you can redistribute it and/or modify it\r\n\t * under the terms of the GNU General Public License as published by the\r\n\t * Free Software Foundation, either version 3 of the License, or (at your\r\n\t * option) any later version.\r\n\t * \r\n\t * This program is distributed in the hope that it will be useful, but\r\n\t * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n\t * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\r\n\t * Public License for more details.\r\n\t * \r\n\t * You should have received a copy of the GNU General Public License along\r\n\t * with this program. If not, see <http://www.gnu.org/licenses/>.\r\n\t * \r\n\t * Also add information on how to contact you by electronic and paper mail.\r\n\t * \r\n\t * If the program does terminal interaction, make it output a short notice\r\n\t * like this when it starts in an interactive mode:\r\n\t * \r\n\t * {project} Copyright (C) {year} {fullname} This program comes with\r\n\t * ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software,\r\n\t * and you are welcome to redistribute it under certain conditions; type\r\n\t * `show c' for details.\r\n\t * \r\n\t * The hypothetical commands `show w' and `show c' should show the\r\n\t * appropriate parts of the General Public License. Of course, your\r\n\t * program's commands might be different; for a GUI interface, you would use\r\n\t * an \"about box\".\r\n\t * \r\n\t * You should also get your employer (if you work as a programmer) or\r\n\t * school, if any, to sign a \"copyright disclaimer\" for the program, if\r\n\t * necessary. For more information on this, and how to apply and follow the\r\n\t * GNU GPL, see <http://www.gnu.org/licenses/>.\r\n\t * \r\n\t * The GNU General Public License does not permit incorporating your program\r\n\t * into proprietary programs. If your program is a subroutine library, you\r\n\t * may consider it more useful to permit linking proprietary applications\r\n\t * with the library. If this is what you want to do, use the GNU Lesser\r\n\t * General Public License instead of this License. But first, please read\r\n\t * <http://www.gnu.org/philosophy/why-not-lgpl.html>.\r\n\t */\r\n\t\r\n\tpublic static boolean isResetting(String lobby, String arena) {\r\n\t\treturn resets.contains(lobby + arena);\r\n\t}\r\n\t\r\n\tpublic static boolean isResseting(String lobby) {\r\n\t\tfor(String key : resets) {\r\n\t\t\tif(key.startsWith(lobby))\r\n\t\t\t\treturn true;\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\tprivate String lobby, arena;\r\n\tprivate World world;\r\n\tprivate long start;\r\n\tprivate List<String> chunks = new ArrayList<>();\r\n\t\r\n\tprivate HashMap<Vector, BaseBlock> cReset = new HashMap<>();\r\n\tprivate boolean build = false;\r\n\t\r\n\tpublic Reset(World w, String lobby, String arena, List<String> chunks) {\r\n\t\tthis.world = w;\r\n\t\tthis.lobby = lobby;\r\n\t\tthis.arena = arena;\r\n\t\tthis.chunks = chunks;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic void run() {\r\n\t\tif(isResetting(lobby, arena))\r\n\t\t\treturn;\r\n\t\tSystem.out.println(\"[SurvivalGames] Start arena reset... (arena \" + arena + \", lobby \" + lobby + \")\");\r\n\t\tresets.add(lobby + arena);\r\n\t\tstart = System.currentTimeMillis();\r\n\t\t\r\n\t\tFile file = new File(\"plugins/SurvivalGames/reset/\" + lobby + arena + \".map\");\r\n\r\n\t\ttry {\r\n\t\t\tNBTInputStream nbtStream = new NBTInputStream( new GZIPInputStream(new FileInputStream(file)));\r\n\r\n\t Vector origin = new Vector();\r\n\t Vector offset = new Vector();\r\n\r\n\t // Schematic tag\r\n\t CompoundTag schematicTag = (CompoundTag) nbtStream.readNamedTag().getTag();\r\n\t nbtStream.close();\r\n\t Map<String, Tag> schematic = schematicTag.getValue();\r\n\r\n\t // Get information\r\n\t short width = getChildTag(schematic, \"Width\", ShortTag.class).getValue();\r\n\t short length = getChildTag(schematic, \"Length\", ShortTag.class).getValue();\r\n\t short height = getChildTag(schematic, \"Height\", ShortTag.class).getValue();\r\n\r\n\t int originX = getChildTag(schematic, \"WEOriginX\", IntTag.class).getValue();\r\n int originY = getChildTag(schematic, \"WEOriginY\", IntTag.class).getValue();\r\n int originZ = getChildTag(schematic, \"WEOriginZ\", IntTag.class).getValue();\r\n origin = new Vector(originX, originY, originZ);\r\n\r\n int offsetX = getChildTag(schematic, \"WEOffsetX\", IntTag.class).getValue();\r\n int offsetY = getChildTag(schematic, \"WEOffsetY\", IntTag.class).getValue();\r\n int offsetZ = getChildTag(schematic, \"WEOffsetZ\", IntTag.class).getValue();\r\n offset = new Vector(offsetX, offsetY, offsetZ);\r\n\r\n\t // Get blocks\r\n\t byte[] blockId = getChildTag(schematic, \"Blocks\", ByteArrayTag.class).getValue();\r\n\t byte[] blockData = getChildTag(schematic, \"Data\", ByteArrayTag.class).getValue();\r\n\t byte[] addId = new byte[0];\r\n\t short[] blocks = new short[blockId.length]; // Have to later combine IDs\r\n\r\n\t // We support 4096 block IDs using the same method as vanilla Minecraft, where\r\n\t // the highest 4 bits are stored in a separate byte array.\r\n\t if (schematic.containsKey(\"AddBlocks\")) {\r\n\t addId = getChildTag(schematic, \"AddBlocks\", ByteArrayTag.class).getValue();\r\n\t }\r\n\r\n\t // Combine the AddBlocks data with the first 8-bit block ID\r\n\t for (int index = 0; index < blockId.length; index++) {\r\n\t if ((index >> 1) >= addId.length) { // No corresponding AddBlocks index\r\n\t blocks[index] = (short) (blockId[index] & 0xFF);\r\n\t } else {\r\n\t if ((index & 1) == 0) {\r\n\t blocks[index] = (short) (((addId[index >> 1] & 0x0F) << 8) + (blockId[index] & 0xFF));\r\n\t } else {\r\n\t blocks[index] = (short) (((addId[index >> 1] & 0xF0) << 4) + (blockId[index] & 0xFF));\r\n\t }\r\n\t }\r\n\t }\r\n\r\n\t // Need to pull out tile entities\r\n\t List<Tag> tileEntities = getChildTag(schematic, \"TileEntities\", ListTag.class)\r\n\t .getValue();\r\n\t Map<BlockVector, Map<String, Tag>> tileEntitiesMap =\r\n\t new HashMap<BlockVector, Map<String, Tag>>();\r\n\r\n\t for (Tag tag : tileEntities) {\r\n\t if (!(tag instanceof CompoundTag)) continue;\r\n\t CompoundTag t = (CompoundTag) tag;\r\n\r\n\t int x = 0;\r\n\t int y = 0;\r\n\t int z = 0;\r\n\r\n\t Map<String, Tag> values = new HashMap<String, Tag>();\r\n\r\n\t for (Map.Entry<String, Tag> entry : t.getValue().entrySet()) {\r\n\t if (entry.getKey().equals(\"x\")) {\r\n\t if (entry.getValue() instanceof IntTag) {\r\n\t x = ((IntTag) entry.getValue()).getValue();\r\n\t }\r\n\t } else if (entry.getKey().equals(\"y\")) {\r\n\t if (entry.getValue() instanceof IntTag) {\r\n\t y = ((IntTag) entry.getValue()).getValue();\r\n\t }\r\n\t } else if (entry.getKey().equals(\"z\")) {\r\n\t if (entry.getValue() instanceof IntTag) {\r\n\t z = ((IntTag) entry.getValue()).getValue();\r\n\t }\r\n\t }\r\n\r\n\t values.put(entry.getKey(), entry.getValue());\r\n\t }\r\n\r\n\t BlockVector vec = new BlockVector(x, y, z);\r\n\t tileEntitiesMap.put(vec, values);\r\n\t }\r\n\r\n\t Vector size = new Vector(width, height, length);\r\n\t CuboidClipboard clipboard = new CuboidClipboard(size);\r\n\t clipboard.setOrigin(origin);\r\n\t clipboard.setOffset(offset);\r\n\t \r\n\t for(com.sk89q.worldedit.world.World lws : we.getServer().getWorlds()) {\r\n\t\t\t\tif(lws.getName().equals(world.getName())) {\r\n\t\t\t\t\tlw = lws;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tint next = 16 * 16 * world.getMaxHeight();\r\n\t\t\tes = we.getEditSessionFactory().getEditSession(lw, -1);\r\n\t\t\tlong sleep = 100;\r\n\t \r\n\t for (int x = 0; x < width; ++x) {\r\n\t for (int y = 0; y < height; ++y) {\r\n\t for (int z = 0; z < length; ++z) {\r\n\t \tif(cReset.size() >= next) {\r\n\t\t\t\t\t\t\tresetNext();\r\n\t\t\t\t\t\t\twhile(build) {\r\n\t\t\t\t\t\t\t\tsleep(sleep);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t \t\r\n\t BlockVector pt = new BlockVector(x, y, z);\r\n\t Vector pos = pt.add(origin);\r\n\t \r\n\t int cx = (int) Math.floor(pos.getBlockX() / 16.0D);\r\n\t\t\t\t\t\tint cz = (int) Math.floor(pos.getBlockZ() / 16.0D);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tString chunkString = cx + \",\" + cz;\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif(chunks.contains(chunkString)) {\r\n\t\t\t\t\t\t\tif(!chunkString.equals(currentItemChunk)) {\r\n\t\t\t\t\t\t\t\tcurrentItemChunk = chunkString;\r\n\t\t\t\t\t\t\t\tresetEntities(chunkString);\r\n\t\t\t\t\t\t\t\tBukkit.broadcastMessage(currentItemChunk);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tint index = y * width * length + z * width + x;\r\n\t\t\t\t\t\t\tBaseBlock block = new BaseBlock(blocks[index], blockData[index]);\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tif (block instanceof TileEntityBlock && tileEntitiesMap.containsKey(pt)) {\r\n\t\t\t\t\t\t\t\t((TileEntityBlock) block).setNbtData(new CompoundTag(tileEntitiesMap.get(pt)));\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tcReset.put(pos, block);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t }\r\n\t }\r\n\t }\r\n\t resetNext();\r\n\t\t\twhile(build) {\r\n\t\t\t\tsleep(sleep);\r\n\t\t\t}\r\n\t \r\n\t\t} catch (IOException | DataException | InterruptedException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\r\n\r\n\t\tBukkit.getScheduler().callSyncMethod(SurvivalGames.instance, new Callable<Void>() {\r\n\t\t\t@Override\r\n\t\t\tpublic Void call() {\r\n\t\t\t\tresets.remove(lobby + arena);\r\n\t\t\t\t\r\n\t\t\t\tSurvivalGames.reset.set(\"Startup-Reset.\" + lobby + \".\" + arena, null);\r\n\t\t\t\tSurvivalGames.saveReset();\r\n\t\t\t\r\n\t\t\t\tint time = (int) ((System.currentTimeMillis() - start) / 1000);\r\n\t\t\t\tSystem.out.println(\"[SurvivalGames] Finished arena reset! (arena \" + arena + \", lobby \" + lobby + \") Time: \" + time + \" seconds!\");\r\n\t\t\t\tBukkit.getPluginManager().callEvent(new ResetDoneEvent(lobby, arena, time));\r\n\t\t\t\treturn null;\r\n\t\t\t}\r\n\t\t});\r\n\t}\r\n\t\r\n\tWorldEdit we = SurvivalGames.getWorldEdit().getWorldEdit();\r\n\tcom.sk89q.worldedit.world.World lw = null;\r\n\tEditSession es = null;\r\n\tString currentItemChunk = \"\";\r\n\r\n\tpublic void resetNext() {\r\n\t\tbuild = true;\r\n\t\tUtil.debug(\"reset next!\");\r\n\t\tBukkit.getScheduler().callSyncMethod(SurvivalGames.instance, new Callable<Void>() {\r\n\t\t\t@Override\r\n\t\t\tpublic Void call() {\r\n\t\t\t\tfor(Entry<Vector, BaseBlock> map : cReset.entrySet()) {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tes.setBlock(map.getKey(), map.getValue());\r\n\t\t\t\t\t} catch (MaxChangedBlocksException e) {\r\n\t\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tcReset.clear();\r\n\t\t\t\tbuild = false;\r\n\t\t\t\treturn null;\r\n\t\t\t}\r\n\t\t});\r\n\t}\r\n\t\r\n\tpublic void resetEntities(final String chunk) {\r\n\t\tBukkit.getScheduler().callSyncMethod(SurvivalGames.instance, new Callable<Void>() {\r\n\t\t\t@Override\r\n\t\t\tpublic Void call() {\r\n\t\t\t\tString[] split = chunk.split(\",\");\r\n\t\t\t\tChunk c = world.getChunkAt(Integer.parseInt(split[0]), Integer.parseInt(split[1]));\r\n\t\t\t\tboolean l = c.isLoaded();\r\n\t\t\t\tif(!l)\r\n\t\t\t\t\tc.load();\r\n\t\t\t\t\r\n\t\t\t\tfor(Entity e : c.getEntities()) {\r\n\t\t\t\t\tif(e instanceof Item || e instanceof LivingEntity || e instanceof Arrow) {\r\n\t\t\t\t\t\te.remove();\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tif(!l)\r\n\t\t\t\t\tc.unload();\r\n\t\t\t\t\r\n\t\t\t\treturn null;\r\n\t\t\t}\r\n\t\t});\r\n\t}\r\n\t\r\n\tprivate static <T extends Tag> T getChildTag(Map<String, Tag> items, String key, Class<T> expected) throws DataException {\r\n\t\treturn expected.cast(items.get(key));\r\n\t}\r\n\r\n\r\n}\r" ]
import java.util.ArrayList; import java.util.List; import org.bukkit.Location; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import me.maker56.survivalgames.Util; import me.maker56.survivalgames.SurvivalGames; import me.maker56.survivalgames.arena.Arena; import me.maker56.survivalgames.commands.messages.MessageHandler; import me.maker56.survivalgames.game.phases.CooldownPhase; import me.maker56.survivalgames.game.phases.DeathmatchPhase; import me.maker56.survivalgames.game.phases.IngamePhase; import me.maker56.survivalgames.game.phases.VotingPhase; import me.maker56.survivalgames.reset.Reset;
package me.maker56.survivalgames.game; public class GameManager { private List<Game> games = new ArrayList<>(); private static FileConfiguration cfg; public GameManager() { reinitializeDatabase(); loadAll(); } public static void reinitializeDatabase() {
cfg = SurvivalGames.database;
1
crazyhitty/Munch
app/src/main/java/com/crazyhitty/chdev/ks/munch/feeds/FeedsLoaderInteractor.java
[ "public class FeedItem {\n private String itemTitle, itemDesc, itemSourceUrl, itemLink, itemImgUrl, itemCategory, itemSource, itemPubDate, itemWebDesc, itemWebDescSync;\n private int itemCategoryImgId, itemBgId;\n\n public String getItemTitle() {\n if (itemTitle == null) {\n return \"\";\n }\n return itemTitle;\n }\n\n public void setItemTitle(String itemTitle) {\n this.itemTitle = itemTitle;\n }\n\n public String getItemDesc() {\n if (itemDesc == null) {\n return \"\";\n }\n return itemDesc;\n }\n\n public void setItemDesc(String itemDesc) {\n this.itemDesc = itemDesc;\n }\n\n public String getItemSourceUrl() {\n if (itemSourceUrl == null) {\n return \"\";\n }\n return itemSourceUrl;\n }\n\n public void setItemSourceUrl(String itemSourceUrl) {\n this.itemSourceUrl = itemSourceUrl;\n }\n\n public String getItemLink() {\n if (itemLink == null) {\n return \"\";\n }\n return itemLink;\n }\n\n public void setItemLink(String itemLink) {\n this.itemLink = itemLink;\n }\n\n public String getItemImgUrl() {\n if (itemImgUrl == null) {\n return \"\";\n }\n return itemImgUrl;\n }\n\n public void setItemImgUrl(String itemImgUrl) {\n this.itemImgUrl = itemImgUrl;\n }\n\n public String getItemCategory() {\n if (itemCategory == null) {\n return \"\";\n }\n return itemCategory;\n }\n\n public void setItemCategory(String itemCategory) {\n this.itemCategory = itemCategory;\n }\n\n public String getItemSource() {\n if (itemSource == null) {\n return \"\";\n }\n return itemSource;\n }\n\n public void setItemSource(String itemSource) {\n this.itemSource = itemSource;\n }\n\n public String getItemPubDate() {\n if (itemPubDate == null) {\n return \"\";\n }\n return itemPubDate;\n }\n\n public void setItemPubDate(String itemPubDate) {\n this.itemPubDate = itemPubDate;\n }\n\n public int getItemCategoryImgId() {\n return itemCategoryImgId;\n }\n\n public void setItemCategoryImgId(int itemCategoryImgId) {\n this.itemCategoryImgId = itemCategoryImgId;\n }\n\n public int getItemBgId() {\n return itemBgId;\n }\n\n public void setItemBgId(int itemBgId) {\n this.itemBgId = itemBgId;\n }\n\n public String getItemWebDesc() {\n return itemWebDesc;\n }\n\n public void setItemWebDesc(String itemWebDesc) {\n this.itemWebDesc = itemWebDesc;\n }\n\n public String getItemWebDescSync() {\n return itemWebDescSync;\n }\n\n public void setItemWebDescSync(String itemWebDescSync) {\n this.itemWebDescSync = itemWebDescSync;\n }\n}", "public class SourceItem {\n private String sourceName, sourceUrl, sourceCategoryName, sourceDateAdded;\n private int sourceCategoryImgId;\n\n public int getSourceCategoryImgId() {\n return sourceCategoryImgId;\n }\n\n public void setSourceCategoryImgId(int sourceCategoryImgId) {\n this.sourceCategoryImgId = sourceCategoryImgId;\n }\n\n public String getSourceName() {\n return sourceName;\n }\n\n public void setSourceName(String sourceName) {\n this.sourceName = sourceName;\n }\n\n public String getSourceUrl() {\n return sourceUrl;\n }\n\n public void setSourceUrl(String sourceUrl) {\n this.sourceUrl = sourceUrl;\n }\n\n public String getSourceDateAdded() {\n return sourceDateAdded;\n }\n\n public void setSourceDateAdded(String sourceDateAdded) {\n this.sourceDateAdded = sourceDateAdded;\n }\n\n public String getSourceCategoryName() {\n return sourceCategoryName;\n }\n\n public void setSourceCategoryName(String sourceCategoryName) {\n this.sourceCategoryName = sourceCategoryName;\n }\n}", "public class DatabaseUtil {\n private Context mContext;\n\n public DatabaseUtil(Context mContext) {\n this.mContext = mContext;\n }\n\n public void saveSourceInDB(SourceItem sourceItem) {\n String[] columnNames = mContext.getResources().getStringArray(R.array.source_table_columns);\n\n DatabaseOperations databaseOperations = new DatabaseOperations(mContext, \"munch_db.sqlite\");\n\n String[] values = {sourceItem.getSourceName()\n , sourceItem.getSourceUrl()\n , sourceItem.getSourceCategoryName()\n , String.valueOf(sourceItem.getSourceCategoryImgId())};\n\n try {\n databaseOperations.saveDataInDB(\"source_table\", columnNames, values);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n public List<SourceItem> getAllSources() throws Exception {\n List<SourceItem> sourceItems = new ArrayList<>();\n\n String[] columnNames = mContext.getResources().getStringArray(R.array.source_table_columns);\n\n DatabaseOperations databaseOperations = new DatabaseOperations(mContext, \"munch_db.sqlite\");\n Cursor cursor = databaseOperations.retrieveAllFromDB(\"source_table\");\n if (cursor != null && cursor.getCount() != 0) {\n if (cursor.moveToFirst()) {\n do {\n SourceItem sourceItem = new SourceItem();\n sourceItem.setSourceName(cursor.getString(cursor.getColumnIndex(columnNames[0])));\n sourceItem.setSourceUrl(cursor.getString(cursor.getColumnIndex(columnNames[1])));\n sourceItem.setSourceCategoryName(cursor.getString(cursor.getColumnIndex(columnNames[2])));\n sourceItem.setSourceCategoryImgId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(columnNames[3]))));\n sourceItems.add(sourceItem);\n } while (cursor.moveToNext());\n }\n }\n\n return sourceItems;\n }\n\n public SourceItem getSourceItem(String sourceName) throws Exception {\n SourceItem sourceItem = new SourceItem();\n String[] columnNames = mContext.getResources().getStringArray(R.array.source_table_columns);\n DatabaseOperations databaseOperations = new DatabaseOperations(mContext, \"munch_db.sqlite\");\n Cursor cursor = databaseOperations.retrieveFromDBCondition(\"source_table\", columnNames, \"WHERE source_name='\" + sourceName + \"'\");\n if (cursor != null && cursor.getCount() != 0) {\n if (cursor.moveToFirst()) {\n do {\n sourceItem.setSourceName(cursor.getString(cursor.getColumnIndex(columnNames[0])));\n sourceItem.setSourceUrl(cursor.getString(cursor.getColumnIndex(columnNames[1])));\n sourceItem.setSourceCategoryName(cursor.getString(cursor.getColumnIndex(columnNames[2])));\n sourceItem.setSourceCategoryImgId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(columnNames[3]))));\n } while (cursor.moveToNext());\n }\n }\n return sourceItem;\n }\n\n public void saveFeedsInDB(List<FeedItem> feedItems) {\n String[] columnNames = mContext.getResources().getStringArray(R.array.feed_table_columns);\n\n DatabaseOperations databaseOperations = new DatabaseOperations(mContext, \"munch_db.sqlite\");\n\n //let the user decide this\n /*try {\n //clear the old feeds\n databaseOperations.deleteAllFromDB(\"feed_table\");\n }catch (Exception e){\n e.printStackTrace();\n }*/\n\n for (FeedItem feedItem : feedItems) {\n String[] values = {feedItem.getItemTitle()\n , feedItem.getItemDesc()\n , feedItem.getItemLink()\n , feedItem.getItemImgUrl()\n , feedItem.getItemCategory()\n , feedItem.getItemSource()\n , feedItem.getItemSourceUrl()\n , feedItem.getItemPubDate()\n , String.valueOf(feedItem.getItemCategoryImgId())\n , \"\"};\n try {\n databaseOperations.saveDataInDB(\"feed_table\", columnNames, values);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n }\n\n public List<FeedItem> getAllFeeds() throws Exception {\n List<FeedItem> feedItems = new ArrayList<>();\n\n String[] columnNames = mContext.getResources().getStringArray(R.array.feed_table_columns);\n\n DatabaseOperations databaseOperations = new DatabaseOperations(mContext, \"munch_db.sqlite\");\n\n Cursor cursor = databaseOperations.retrieveAllFromDB(\"feed_table\");\n\n /*switch (condition){\n case \"no_order\":\n cursor = databaseOperations.retrieveAllFromDB(\"feed_table\");\n break;\n case \"alphabetical_feeds\":\n cursor = databaseOperations.retrieveAllFromDBCondition(\"feed_table\", \"ORDER BY item_name\");\n break;\n case \"alphabetical_sources\":\n cursor = databaseOperations.retrieveAllFromDBCondition(\"feed_table\", \"ORDER BY item_source\");\n break;\n case \"pub_date\":\n cursor = databaseOperations.retrieveAllFromDBCondition(\"feed_table\", \"ORDER BY item_pub_date\");\n break;\n }*/\n\n if (cursor != null && cursor.getCount() != 0) {\n if (cursor.moveToFirst()) {\n do {\n FeedItem feedItem = new FeedItem();\n feedItem.setItemTitle(cursor.getString(cursor.getColumnIndex(columnNames[0])));\n feedItem.setItemDesc(cursor.getString(cursor.getColumnIndex(columnNames[1])));\n feedItem.setItemLink(cursor.getString(cursor.getColumnIndex(columnNames[2])));\n feedItem.setItemImgUrl(cursor.getString(cursor.getColumnIndex(columnNames[3])));\n feedItem.setItemCategory(cursor.getString(cursor.getColumnIndex(columnNames[4])));\n feedItem.setItemSource(cursor.getString(cursor.getColumnIndex(columnNames[5])));\n feedItem.setItemSourceUrl(cursor.getString(cursor.getColumnIndex(columnNames[6])));\n feedItem.setItemPubDate(cursor.getString(cursor.getColumnIndex(columnNames[7])));\n feedItem.setItemCategoryImgId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(columnNames[8]))));\n feedItem.setItemWebDesc(cursor.getString(cursor.getColumnIndex(columnNames[9])));\n feedItems.add(feedItem);\n } while (cursor.moveToNext());\n }\n }\n\n return feedItems;\n }\n\n public List<FeedItem> getFeedsBySource(String source) throws Exception {\n List<FeedItem> feedItems = new ArrayList<>();\n\n String[] columnNames = mContext.getResources().getStringArray(R.array.feed_table_columns);\n\n DatabaseOperations databaseOperations = new DatabaseOperations(mContext, \"munch_db.sqlite\");\n\n String condition = \"WHERE item_source='\" + source + \"'\";\n\n Cursor cursor = databaseOperations.retrieveFromDBCondition(\"feed_table\", columnNames, condition);\n if (cursor != null && cursor.getCount() != 0) {\n if (cursor.moveToFirst()) {\n do {\n FeedItem feedItem = new FeedItem();\n feedItem.setItemTitle(cursor.getString(cursor.getColumnIndex(columnNames[0])));\n feedItem.setItemDesc(cursor.getString(cursor.getColumnIndex(columnNames[1])));\n feedItem.setItemLink(cursor.getString(cursor.getColumnIndex(columnNames[2])));\n feedItem.setItemImgUrl(cursor.getString(cursor.getColumnIndex(columnNames[3])));\n feedItem.setItemCategory(cursor.getString(cursor.getColumnIndex(columnNames[4])));\n feedItem.setItemSource(cursor.getString(cursor.getColumnIndex(columnNames[5])));\n feedItem.setItemSourceUrl(cursor.getString(cursor.getColumnIndex(columnNames[6])));\n feedItem.setItemPubDate(cursor.getString(cursor.getColumnIndex(columnNames[7])));\n feedItem.setItemCategoryImgId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(columnNames[8]))));\n feedItem.setItemWebDesc(cursor.getString(cursor.getColumnIndex(columnNames[9])));\n feedItems.add(feedItem);\n } while (cursor.moveToNext());\n }\n }\n\n return feedItems;\n }\n\n public FeedItem getFeedByLink(String link) throws Exception {\n FeedItem feedItem = new FeedItem();\n\n String[] columnNames = mContext.getResources().getStringArray(R.array.feed_table_columns);\n\n DatabaseOperations databaseOperations = new DatabaseOperations(mContext, \"munch_db.sqlite\");\n\n String condition = \"WHERE item_link='\" + link + \"'\";\n\n Cursor cursor = databaseOperations.retrieveFromDBCondition(\"feed_table\", columnNames, condition);\n if (cursor != null && cursor.getCount() != 0) {\n if (cursor.moveToFirst()) {\n do {\n feedItem.setItemTitle(cursor.getString(cursor.getColumnIndex(columnNames[0])));\n feedItem.setItemDesc(cursor.getString(cursor.getColumnIndex(columnNames[1])));\n feedItem.setItemLink(cursor.getString(cursor.getColumnIndex(columnNames[2])));\n feedItem.setItemImgUrl(cursor.getString(cursor.getColumnIndex(columnNames[3])));\n feedItem.setItemCategory(cursor.getString(cursor.getColumnIndex(columnNames[4])));\n feedItem.setItemSource(cursor.getString(cursor.getColumnIndex(columnNames[5])));\n feedItem.setItemSourceUrl(cursor.getString(cursor.getColumnIndex(columnNames[6])));\n feedItem.setItemPubDate(cursor.getString(cursor.getColumnIndex(columnNames[7])));\n feedItem.setItemCategoryImgId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(columnNames[8]))));\n feedItem.setItemWebDesc(cursor.getString(cursor.getColumnIndex(columnNames[9])));\n break;\n } while (cursor.moveToNext());\n }\n }\n\n return feedItem;\n }\n\n public void deleteAllFeeds() throws Exception {\n new DatabaseOperations(mContext, \"munch_db.sqlite\").deleteAllFromDB(\"feed_table\");\n }\n\n public void saveArticle(FeedItem feedItem, String article) throws Exception {\n String[] columnNames = mContext.getResources().getStringArray(R.array.article_table_columns);\n\n DatabaseOperations databaseOperations = new DatabaseOperations(mContext, \"munch_db.sqlite\");\n\n String[] values = {feedItem.getItemTitle()\n , feedItem.getItemDesc()\n , feedItem.getItemLink()\n , feedItem.getItemImgUrl()\n , feedItem.getItemCategory()\n , feedItem.getItemSource()\n , feedItem.getItemSourceUrl()\n , feedItem.getItemPubDate()\n , String.valueOf(feedItem.getItemCategoryImgId())\n , article};\n\n try {\n databaseOperations.saveDataInDB(\"article_table\", columnNames, values);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n public List<FeedItem> getSavedArticles() throws Exception {\n List<FeedItem> feedItems = new ArrayList<>();\n\n String[] columnNames = mContext.getResources().getStringArray(R.array.article_table_columns);\n\n DatabaseOperations databaseOperations = new DatabaseOperations(mContext, \"munch_db.sqlite\");\n\n Cursor cursor = databaseOperations.retrieveFromDB(\"article_table\", columnNames);\n if (cursor != null && cursor.getCount() != 0) {\n if (cursor.moveToFirst()) {\n do {\n FeedItem feedItem = new FeedItem();\n feedItem.setItemTitle(cursor.getString(cursor.getColumnIndex(columnNames[0])));\n feedItem.setItemDesc(cursor.getString(cursor.getColumnIndex(columnNames[1])));\n feedItem.setItemLink(cursor.getString(cursor.getColumnIndex(columnNames[2])));\n feedItem.setItemImgUrl(cursor.getString(cursor.getColumnIndex(columnNames[3])));\n feedItem.setItemCategory(cursor.getString(cursor.getColumnIndex(columnNames[4])));\n feedItem.setItemSource(cursor.getString(cursor.getColumnIndex(columnNames[5])));\n feedItem.setItemSourceUrl(cursor.getString(cursor.getColumnIndex(columnNames[6])));\n feedItem.setItemPubDate(cursor.getString(cursor.getColumnIndex(columnNames[7])));\n feedItem.setItemCategoryImgId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(columnNames[8]))));\n feedItem.setItemWebDesc(cursor.getString(cursor.getColumnIndex(columnNames[9])));\n feedItems.add(feedItem);\n } while (cursor.moveToNext());\n }\n }\n\n return feedItems;\n }\n\n public List<SourceItem> getAllSourceItems() throws Exception {\n List<SourceItem> sourceItems = new ArrayList<>();\n String[] columnNames = mContext.getResources().getStringArray(R.array.source_table_columns);\n DatabaseOperations databaseOperations = new DatabaseOperations(mContext, \"munch_db.sqlite\");\n Cursor cursor = databaseOperations.retrieveFromDB(\"source_table\", columnNames);\n if (cursor != null && cursor.getCount() != 0) {\n if (cursor.moveToFirst()) {\n do {\n SourceItem sourceItem = new SourceItem();\n sourceItem.setSourceName(cursor.getString(cursor.getColumnIndex(columnNames[0])));\n sourceItem.setSourceUrl(cursor.getString(cursor.getColumnIndex(columnNames[1])));\n sourceItem.setSourceCategoryName(cursor.getString(cursor.getColumnIndex(columnNames[2])));\n sourceItem.setSourceCategoryImgId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(columnNames[3]))));\n sourceItems.add(sourceItem);\n } while (cursor.moveToNext());\n }\n }\n return sourceItems;\n }\n\n public void modifySource(SourceItem sourceItem, String sourceNameOld) throws Exception {\n String[] columnNames = mContext.getResources().getStringArray(R.array.source_table_columns);\n String[] values = {sourceItem.getSourceName(), sourceItem.getSourceUrl(), sourceItem.getSourceCategoryName(), String.valueOf(sourceItem.getSourceCategoryImgId())};\n DatabaseOperations databaseOperations = new DatabaseOperations(mContext, \"munch_db.sqlite\");\n databaseOperations.editDataInDB(\"source_table\", columnNames, values, \"WHERE source_name='\" + sourceNameOld + \"'\");\n }\n\n public void deleteSourceItem(SourceItem sourceItem) throws Exception {\n DatabaseOperations databaseOperations = new DatabaseOperations(mContext, \"munch_db.sqlite\");\n databaseOperations.deleteFromDB(\"source_table\", \"source_name\", sourceItem.getSourceName());\n }\n\n public void deleteArticle(FeedItem feedItem) throws Exception {\n DatabaseOperations databaseOperations = new DatabaseOperations(mContext, \"munch_db.sqlite\");\n databaseOperations.deleteFromDB(\"article_table\", \"article_name\", feedItem.getItemTitle());\n }\n\n public void deleteFeeds(SourceItem sourceItem) throws Exception {\n DatabaseOperations databaseOperations = new DatabaseOperations(mContext, \"munch_db.sqlite\");\n databaseOperations.deleteFromDB(\"feed_table\", \"item_source\", sourceItem.getSourceName());\n }\n\n public void deleteAll() throws Exception {\n DatabaseOperations databaseOperations = new DatabaseOperations(mContext, \"munch_db.sqlite\");\n databaseOperations.deleteAllFromDB(\"source_table\");\n databaseOperations.deleteAllFromDB(\"article_table\");\n databaseOperations.deleteAllFromDB(\"feed_table\");\n }\n\n public void deleteSelectedFeeds(FeedItem feedItem) throws Exception {\n DatabaseOperations databaseOperations = new DatabaseOperations(mContext, \"munch_db.sqlite\");\n databaseOperations.deleteFromDB(\"feed_table\", \"item_name\", feedItem.getItemTitle());\n }\n\n public void saveFeedArticleDesc(FeedItem feedItem) throws Exception {\n /*String[] columnNames = mContext.getResources().getStringArray(R.array.feed_table_columns);\n String[] values = {feedItem.getItemTitle()\n , feedItem.getItemDesc()\n , feedItem.getItemLink()\n , feedItem.getItemImgUrl()\n , feedItem.getItemCategory()\n , feedItem.getItemSource()\n , feedItem.getItemSourceUrl()\n , feedItem.getItemPubDate()\n , String.valueOf(feedItem.getItemCategoryImgId())\n , null};*/\n String[] columnNames = new String[]{\"item_desc_web\"};\n String[] values = new String[]{feedItem.getItemWebDescSync()};\n DatabaseOperations databaseOperations = new DatabaseOperations(mContext, \"munch_db.sqlite\");\n databaseOperations.editDataInDB(\"feed_table\", columnNames, values, \"WHERE item_link='\" + feedItem.getItemLink() + \"'\");\n }\n\n public String[] getFeedLinks() throws Exception {\n DatabaseOperations databaseOperations = new DatabaseOperations(mContext, \"munch_db.sqlite\");\n List<String> itemLinks = databaseOperations.retrieveFromDB(\"feed_table\", \"item_link\");\n String[] links = new String[itemLinks.size()];\n for (int i = 0; i < itemLinks.size(); i++) {\n links[i] = itemLinks.get(i);\n }\n return links;\n }\n\n public void removeDescFromFeed(FeedItem feedItem) throws Exception {\n String[] columnNames = new String[]{\"item_desc_web\"};\n String[] values = new String[]{\"\"};\n DatabaseOperations databaseOperations = new DatabaseOperations(mContext, \"munch_db.sqlite\");\n databaseOperations.editDataInDB(\"feed_table\", columnNames, values, \"WHERE item_link='\" + feedItem.getItemLink() + \"'\");\n }\n}", "public class DateUtil {\n String formatRfc2822 = \"EEE, dd MMM yyyy HH:mm:ss Z\";\n String formatLocal = \"EEE, d MMM yyyy\";\n private String date;\n\n public String getCurrDate() {\n date = new SimpleDateFormat(\"dd/MM/yyyy hh:mm:ss\").format(new Date());\n return date;\n }\n\n //converts rss publish date into a readable format\n public String getDate(String pubDate) throws ParseException {\n Date date = getDateObj(pubDate);\n return new SimpleDateFormat(formatLocal).format(date);\n }\n\n //get Date object from pub date\n public Date getDateObj(String pubDate) throws ParseException {\n SimpleDateFormat pubDateFormat = new SimpleDateFormat(formatRfc2822, Locale.ENGLISH); //rss spec\n Date date = null;\n try {\n date = pubDateFormat.parse(pubDate);\n } catch (ParseException e) {\n pubDateFormat = new SimpleDateFormat(formatLocal); //fallback\n date = pubDateFormat.parse(pubDate);\n }\n return date;\n }\n}", "public interface OnRssLoadListener {\n void onSuccess(List<RssItem> rssItems);\n\n void onFailure(String message);\n}", "public class RssItem {\n String title;\n String description;\n String link;\n String sourceName;\n String sourceUrl;\n String imageUrl;\n String category;\n String pubDate;\n int categoryImgId;\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public String getLink() {\n return link;\n }\n\n public void setLink(String link) {\n this.link = link;\n }\n\n public String getSourceName() {\n return sourceName;\n }\n\n public void setSourceName(String sourceName) {\n this.sourceName = sourceName;\n }\n\n public String getSourceUrl() {\n return sourceUrl;\n }\n\n public void setSourceUrl(String sourceUrl) {\n this.sourceUrl = sourceUrl;\n }\n\n public String getImageUrl() {\n return imageUrl;\n }\n\n public void setImageUrl(String imageUrl) {\n this.imageUrl = imageUrl;\n }\n\n public String getCategory() {\n return category;\n }\n\n public void setCategory(String category) {\n this.category = category;\n }\n\n public String getPubDate() {\n return pubDate;\n }\n\n public void setPubDate(String pubDate) {\n this.pubDate = pubDate;\n }\n\n public int getCategoryImgId() {\n return categoryImgId;\n }\n\n public void setCategoryImgId(int categoryImgId) {\n this.categoryImgId = categoryImgId;\n }\n}", "public class RssReader implements OnFeedLoadListener {\n private String[] mUrlList, mSourceList, mCategories;\n private int[] mCategoryImgIds;\n private Context mContext;\n private List<RssItem> mRssItems = new ArrayList<>();\n private RssParser mRssParser;\n private int mPosition = 0;\n private MaterialDialog mMaterialDialog;\n private OnRssLoadListener mOnRssLoadListener;\n\n public RssReader(Context context, String[] urlList, String[] sourceList, String[] categories, int[] categoryImgIds, OnRssLoadListener onRssLoadListener) {\n this.mContext = context;\n this.mUrlList = urlList;\n this.mSourceList = sourceList;\n this.mCategories = categories;\n this.mCategoryImgIds = categoryImgIds;\n this.mOnRssLoadListener = onRssLoadListener;\n }\n\n public void readRssFeeds() {\n mMaterialDialog = new MaterialDialog.Builder(mContext)\n .title(R.string.loading_feeds)\n .progress(true, 0)\n .progressIndeterminateStyle(true)\n .cancelable(false)\n .negativeText(R.string.cancel)\n .onNegative(new MaterialDialog.SingleButtonCallback() {\n @Override\n public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {\n if (mRssParser != null) {\n mRssParser.cancel(true);\n }\n mOnRssLoadListener.onFailure(\"User performed dismiss action\");\n }\n })\n .build();\n mMaterialDialog.show();\n\n mMaterialDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {\n @Override\n public void onCancel(DialogInterface dialogInterface) {\n if (mRssParser != null) {\n mRssParser.cancel(true);\n }\n mOnRssLoadListener.onFailure(\"User performed dismiss action\");\n }\n });\n\n if (mRssItems != null) {\n mRssItems.clear();\n }\n parseRss(0);\n }\n\n private void parseRss(int position) {\n if (position != mUrlList.length) {\n mRssParser = new RssParser(mUrlList[position], this);\n mRssParser.execute();\n String source = getWebsiteName(mUrlList[position]);\n mMaterialDialog.setContent(source);\n } else {\n mMaterialDialog.dismiss();\n mOnRssLoadListener.onSuccess(mRssItems);\n }\n }\n\n private String getWebsiteName(String url) {\n URI uri;\n try {\n uri = new URI(url);\n return uri.getHost();\n } catch (URISyntaxException e) {\n e.printStackTrace();\n }\n return url;\n }\n\n @Override\n public void onSuccess(Elements items) {\n for (Element item : items) {\n mRssItems.add(getRssItem(item));\n }\n mPosition++;\n parseRss(mPosition);\n }\n\n @Override\n public void onFailure(String message) {\n mOnRssLoadListener.onFailure(message);\n }\n\n private RssItem getRssItem(Element element) {\n String title = element.select(\"title\").first().text();\n String description = element.select(\"description\").first().text();\n String link = element.select(\"link\").first().text();\n String sourceName = mSourceList[mPosition];\n String sourceUrl = getWebsiteName(mUrlList[mPosition]);\n\n String imageUrl;\n if (!element.select(\"media|thumbnail\").isEmpty()) {\n imageUrl = element.select(\"media|thumbnail\").attr(\"url\");\n } else if (!element.select(\"media|content\").isEmpty()) {\n imageUrl = element.select(\"media|content\").attr(\"url\");\n } else if (!element.select(\"image\").isEmpty()) {\n imageUrl = element.select(\"image\").attr(\"url\");\n } else {\n imageUrl = null;\n }\n\n String category = null;\n if (mCategories == null) {\n if (!element.select(\"category\").isEmpty()) {\n category = element.select(\"category\").first().text();\n }\n } else {\n category = mCategories[mPosition];\n }\n\n String pubDate = \"\";\n if (!element.select(\"pubDate\").isEmpty()) {\n pubDate = element.select(\"pubDate\").first().text();\n }\n\n int categoryImgId = mCategoryImgIds[mPosition];\n\n RssItem rssItem = new RssItem();\n\n rssItem.setTitle(title);\n rssItem.setDescription(description);\n rssItem.setLink(link);\n rssItem.setSourceName(sourceName);\n rssItem.setSourceUrl(sourceUrl);\n rssItem.setImageUrl(imageUrl);\n rssItem.setCategory(category);\n rssItem.setPubDate(pubDate);\n rssItem.setCategoryImgId(categoryImgId);\n\n return rssItem;\n }\n}" ]
import android.content.Context; import android.util.Log; import com.crazyhitty.chdev.ks.munch.models.FeedItem; import com.crazyhitty.chdev.ks.munch.models.SourceItem; import com.crazyhitty.chdev.ks.munch.utils.DatabaseUtil; import com.crazyhitty.chdev.ks.munch.utils.DateUtil; import com.crazyhitty.chdev.ks.rssmanager.OnRssLoadListener; import com.crazyhitty.chdev.ks.rssmanager.RssItem; import com.crazyhitty.chdev.ks.rssmanager.RssReader; import java.text.ParseException; import java.util.ArrayList; import java.util.List;
package com.crazyhitty.chdev.ks.munch.feeds; /** * Created by Kartik_ch on 11/5/2015. */ public class FeedsLoaderInteractor implements IFeedsLoaderInteractor, OnRssLoadListener { private Context mContext; private OnFeedsLoadedListener onFeedsLoadedListener; public FeedsLoaderInteractor(Context context) { mContext = context; } public void loadFeedsFromDb(final OnFeedsLoadedListener onFeedsLoadedListener) { try { DatabaseUtil databaseUtil = new DatabaseUtil(mContext); onFeedsLoadedListener.onSuccess(databaseUtil.getAllFeeds(), false); } catch (Exception e) { onFeedsLoadedListener.onFailure("Failed to load all feeds from database"); } } public void loadFeedsFromDbBySource(final OnFeedsLoadedListener onFeedsLoadedListener, String source) { try { DatabaseUtil databaseUtil = new DatabaseUtil(mContext); onFeedsLoadedListener.onSuccess(databaseUtil.getFeedsBySource(source), false); } catch (Exception e) { onFeedsLoadedListener.onFailure("Failed to load selected feeds from database"); } } public void loadFeedsAsync(final OnFeedsLoadedListener onFeedsLoadedListener, List<SourceItem> sourceItems) { this.onFeedsLoadedListener = onFeedsLoadedListener; String[] urlList = new String[sourceItems.size()]; String[] sourceList = new String[sourceItems.size()]; String[] categories = new String[sourceItems.size()]; int[] categoryImgIds = new int[sourceItems.size()]; for (int i = 0; i < urlList.length; i++) { urlList[i] = sourceItems.get(i).getSourceUrl(); sourceList[i] = sourceItems.get(i).getSourceName(); categories[i] = sourceItems.get(i).getSourceCategoryName(); categoryImgIds[i] = sourceItems.get(i).getSourceCategoryImgId(); } Log.e("url", urlList[0]); RssReader rssReader = new RssReader(mContext, urlList, sourceList, categories, categoryImgIds, this); rssReader.readRssFeeds(); } private FeedItem getFeedItem(String title, String description, String link, String imgUrl, String sourceName, String sourceUrlShort, String category, String pubDate, int categoryImgId) { FeedItem feedItem = new FeedItem(); feedItem.setItemTitle(title); feedItem.setItemDesc(description); feedItem.setItemLink(link); feedItem.setItemImgUrl(imgUrl); feedItem.setItemSource(sourceName); feedItem.setItemSourceUrl(sourceUrlShort); feedItem.setItemCategory(category); feedItem.setItemPubDate(pubDate); feedItem.setItemCategoryImgId(categoryImgId); return feedItem; } @Override
public void onSuccess(List<RssItem> rssItems) {
5
InfinityRaider/NinjaGear
src/main/java/com/infinityraider/ninjagear/item/ItemRopeCoil.java
[ "public class EntityRopeCoil extends EntityThrowableBase {\n //For client side spawning\n private EntityRopeCoil(EntityType<? extends EntityRopeCoil> type, World world) {\n super(type, world);\n }\n\n public EntityRopeCoil(World world, PlayerEntity thrower) {\n super(EntityRegistry.getInstance().entityRopeCoil, thrower, world);\n Vector3d vec = thrower.getLookVec();\n this.shoot(vec.getX(), vec.getY(), vec.getZ(), 2F, 0.2F);\n }\n\n @Override\n public PlayerEntity getShooter() { //func_234616_v_ ----> getThrower\n return (PlayerEntity) super.getShooter();\n }\n\n @Override\n protected float getGravityVelocity() {\n return 0.1F;\n }\n\n @Override\n protected void onImpact(RayTraceResult impact) {\n Vector3d hitVec = impact.getHitVec();\n if(impact instanceof EntityRayTraceResult) {\n this.dropAsItem(hitVec.getX(), hitVec.getY(), hitVec.getZ());\n }\n if(impact instanceof BlockRayTraceResult) {\n World world = this.getEntityWorld();\n if (!world.isRemote) {\n BlockPos pos = this.getBlockPosFromImpact((BlockRayTraceResult) impact);\n BlockState state = this.getEntityWorld().getBlockState(pos);\n BlockState rope = BlockRegistry.getInstance().blockRope.getDefaultState();\n if (state.getBlock() instanceof BlockRope) {\n BlockRope ropeBlock = (BlockRope) state.getBlock();\n this.addRemainingToInventory(ropeBlock.extendRope(world, pos, NinjaGear.instance.getConfig().getRopeCoilLength()));\n } else if (rope.isValidPosition(world, pos)) {\n this.addRemainingToInventory(this.placeRope(world, pos, NinjaGear.instance.getConfig().getRopeCoilLength()));\n } else {\n this.dropAsItem(hitVec.getX(), hitVec.getY(), hitVec.getZ());\n }\n }\n }\n }\n\n public void dropAsItem(double x, double y, double z) {\n ItemEntity item = new ItemEntity(getEntityWorld(), x, y, z,\n new ItemStack(ItemRegistry.getInstance().itemRopeCoil));\n getEntityWorld().addEntity(item);\n this.setDead();\n }\n\n private BlockPos getBlockPosFromImpact(BlockRayTraceResult impact) {\n BlockState state = this.getEntityWorld().getBlockState(impact.getPos());\n if (state.getBlock() instanceof BlockRope) {\n return impact.getPos();\n }\n return impact.getPos().offset(impact.getFace());\n }\n\n private int placeRope(World world, BlockPos pos, int ropeCount) {\n BlockRope ropeBlock = (BlockRope) BlockRegistry.getInstance().blockRope;\n BlockState rope = ropeBlock.getStateForPlacement(world, pos);\n world.setBlockState(pos, rope, 3);\n return ropeBlock.extendRope(world, pos, ropeCount - 1);\n }\n\n private void addRemainingToInventory(int remaining) {\n if(remaining > 0) {\n ItemStack stack = new ItemStack(ItemRegistry.getInstance().itemRope, remaining);\n if(getShooter() != null && !getShooter().inventory.addItemStackToInventory(stack)) {\n ItemEntity item = new ItemEntity(this.getEntityWorld(), this.getPosX(), this.getPosY(), this.getPosZ(), stack);\n this.getEntityWorld().addEntity(item);\n }\n }\n this.setDead();\n }\n\n @Override\n protected void registerData() {\n\n }\n\n @Override\n public void writeCustomEntityData(CompoundNBT tag) {\n\n }\n\n @Override\n public void readCustomEntityData(CompoundNBT tag) {\n\n }\n\n public static class SpawnFactory implements EntityType.IFactory<EntityRopeCoil> {\n private static final EntityRopeCoil.SpawnFactory INSTANCE = new EntityRopeCoil.SpawnFactory();\n\n public static EntityRopeCoil.SpawnFactory getInstance() {\n return INSTANCE;\n }\n\n private SpawnFactory() {}\n\n @Override\n public EntityRopeCoil create(EntityType<EntityRopeCoil> type, World world) {\n return new EntityRopeCoil(type, world);\n }\n }\n\n public static class RenderFactory implements IRenderFactory<EntityRopeCoil> {\n private static final RenderFactory INSTANCE = new RenderFactory();\n\n public static RenderFactory getInstance() {\n return INSTANCE;\n }\n\n private RenderFactory() {}\n\n @Override\n @OnlyIn(Dist.CLIENT)\n public EntityRenderer<? super EntityRopeCoil> createRenderFor(EntityRendererManager manager) {\n return new RenderEntityRopeCoil(manager);\n }\n }\n}", "public class Names {\n private Names() {}\n\n public static final class Items extends Names {\n public static final String SHURIKEN = \"shuriken\";\n public static final String KATANA = \"katana\";\n public static final String SMOKE_BOMB = \"smoke_bomb\";\n public static final String ROPE = \"rope\";\n public static final String ROPE_COIL = \"rope_coil\";\n }\n\n public static final class Effects extends Names {\n public static final String NINJA_HIDDEN = \"ninja_hidden\";\n public static final String NINJA_REVEALED = \"ninja_revealed\";\n public static final String NINJA_SMOKED = \"ninja_smoked\";\n }\n\n public static final class NBT extends Names {\n public static final String CRIT = \"NG_crit\";\n public static final String NINJA_GEAR = \"NG_ninja\";\n public static final String X = \"NG_X\";\n public static final String Y = \"NG_Y\";\n public static final String Z = \"NG_Z\";\n }\n}", "public interface Reference {\n\t\n\tString MOD_NAME = /*^${mod.name}^*/ \"NinjaGear\";\n\tString MOD_ID = /*^${mod.id}^*/ \"ninja_gear\";\n\tString AUTHOR = /*^${mod.author}^*/ \"InfinityRaider\";\n\n\tString VER_MAJOR = /*^${mod.version_major}^*/ \"2\";\n\tString VER_MINOR = /*^${mod.version_minor}^*/ \"0\";\n\tString VER_PATCH = /*^${mod.version_patch}^*/ \"1\";\n\tString MOD_VERSION = /*^${mod.version}^*/ \"2.0.1\";\n\tString VERSION = /*^${mod.version_minecraft}-${mod.version}^*/ \"1.16.5-\" + MOD_VERSION;\n\t\n\tString UPDATE_URL = /*^${mod.update_url}^*/ \"https://www.youtube.com/watch?v=dQw4w9WgXcQ\";\n\t\n}", "public interface IHiddenItem {\n /**\n * Checks whether or not equipping this item will reveal a hidden entity\n * @param entity entity equipping the item\n * @param stack stack holding the item\n * @return true to reveal the player\n */\n boolean shouldRevealPlayerWhenEquipped(PlayerEntity entity, ItemStack stack);\n}", "public class ItemRegistry {\n public static final ItemGroup CREATIVE_TAB = new ItemGroup(Reference.MOD_ID.toLowerCase() + \".creative_tab\") {\n @Override\n public ItemStack createIcon() {\n return new ItemStack(ItemRegistry.getInstance().itemShuriken);\n }\n };\n\n private static final ItemRegistry INSTANCE = new ItemRegistry();\n\n public static ItemRegistry getInstance() {\n return INSTANCE;\n }\n\n private ItemRegistry() {\n itemNinjaArmorHead = new ItemNinjaArmor(\"ninja_gear_head\", EquipmentSlotType.HEAD);\n itemNinjaArmorChest = new ItemNinjaArmor(\"ninja_gear_chest\", EquipmentSlotType.CHEST);\n itemNinjaArmorLegs = new ItemNinjaArmor(\"ninja_gear_legs\", EquipmentSlotType.LEGS);\n itemNinjaArmorFeet = new ItemNinjaArmor(\"ninja_gear_feet\", EquipmentSlotType.FEET);\n itemKatana = new ItemKatana();\n itemSai = new ItemSai();\n itemShuriken = new ItemShuriken();\n itemSmokeBomb = new ItemSmokeBomb();\n itemRopeCoil = new ItemRopeCoil();\n itemRope = new ItemRope((IInfinityBlock) BlockRegistry.getInstance().blockRope);\n }\n\n public Item itemNinjaArmorHead;\n public Item itemNinjaArmorChest;\n public Item itemNinjaArmorLegs;\n public Item itemNinjaArmorFeet;\n public Item itemKatana;\n public Item itemSai;\n public Item itemShuriken;\n public Item itemSmokeBomb;\n public Item itemRopeCoil;\n public Item itemRope;\n}" ]
import com.infinityraider.ninjagear.entity.EntityRopeCoil; import com.infinityraider.ninjagear.reference.Names; import com.infinityraider.ninjagear.reference.Reference; import com.infinityraider.infinitylib.item.ItemBase; import com.infinityraider.ninjagear.api.v1.IHiddenItem; import com.infinityraider.ninjagear.registry.ItemRegistry; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.util.ActionResult; import net.minecraft.util.ActionResultType; import net.minecraft.util.Hand; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.world.World; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import javax.annotation.Nullable; import javax.annotation.ParametersAreNonnullByDefault; import java.util.List;
package com.infinityraider.ninjagear.item; public class ItemRopeCoil extends ItemBase implements IHiddenItem { public ItemRopeCoil() {
super(Names.Items.ROPE_COIL, new Properties().group(ItemRegistry.CREATIVE_TAB));
1
ajitsing/Sherlock
sherlock/src/androidTest/java/com/singhajit/sherlock/crashes/CrashActivityTest.java
[ "public class Sherlock {\n private static final String TAG = Sherlock.class.getSimpleName();\n private static Sherlock instance;\n private final SherlockDatabaseHelper database;\n private final CrashReporter crashReporter;\n private AppInfoProvider appInfoProvider;\n\n private Sherlock(Context context) {\n database = new SherlockDatabaseHelper(context);\n crashReporter = new CrashReporter(context);\n appInfoProvider = new DefaultAppInfoProvider(context);\n }\n\n public static void init(final Context context) {\n Log.d(TAG, \"Initializing Sherlock...\");\n instance = new Sherlock(context);\n\n final Thread.UncaughtExceptionHandler handler = Thread.getDefaultUncaughtExceptionHandler();\n\n Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {\n @Override\n public void uncaughtException(Thread thread, Throwable throwable) {\n analyzeAndReportCrash(throwable);\n handler.uncaughtException(thread, throwable);\n }\n });\n }\n\n public static boolean isInitialized() {\n return instance != null;\n }\n\n public static Sherlock getInstance() {\n if (!isInitialized()) {\n throw new SherlockNotInitializedException();\n }\n Log.d(TAG, \"Returning existing instance...\");\n return instance;\n }\n\n public List<Crash> getAllCrashes() {\n return getInstance().database.getCrashes();\n }\n\n private static void analyzeAndReportCrash(Throwable throwable) {\n Log.d(TAG, \"Analyzing Crash...\");\n CrashAnalyzer crashAnalyzer = new CrashAnalyzer(throwable);\n Crash crash = crashAnalyzer.getAnalysis();\n int crashId = instance.database.insertCrash(CrashRecord.createFrom(crash));\n crash.setId(crashId);\n instance.crashReporter.report(new CrashViewModel(crash));\n Log.d(TAG, \"Crash analysis completed!\");\n }\n\n public static void setAppInfoProvider(AppInfoProvider appInfoProvider) {\n getInstance().appInfoProvider = appInfoProvider;\n }\n\n public AppInfoProvider getAppInfoProvider() {\n return getInstance().appInfoProvider;\n }\n}", "public class CrashRecord {\n private String place;\n private String reason;\n private String date;\n private String stackTrace;\n\n public CrashRecord(String place, String reason, String date, String stackTrace) {\n this.place = place;\n this.reason = reason;\n this.date = date;\n this.stackTrace = stackTrace;\n }\n\n public String getPlace() {\n return place;\n }\n\n public String getReason() {\n return reason;\n }\n\n public String getDate() {\n return date;\n }\n\n public String getStackTrace() {\n return stackTrace;\n }\n\n public static CrashRecord createFrom(Crash crash) {\n SimpleDateFormat dateFormat = new SimpleDateFormat(Crash.DATE_FORMAT);\n return new CrashRecord(crash.getPlace(), crash.getReason(), dateFormat.format(crash.getDate()), crash.getStackTrace());\n }\n}", "public class DatabaseResetRule implements TestRule {\n @Override\n public Statement apply(final Statement base, Description description) {\n return new Statement() {\n @Override\n public void evaluate() throws Throwable {\n resetDB();\n initializeSherlock();\n base.evaluate();\n }\n };\n }\n\n private void initializeSherlock() {\n Context targetContext = InstrumentationRegistry.getTargetContext();\n Sherlock.init(targetContext);\n }\n\n private void resetDB() {\n Context targetContext = InstrumentationRegistry.getTargetContext();\n SherlockDatabaseHelper database = new SherlockDatabaseHelper(targetContext);\n SQLiteDatabase writableDatabase = database.getWritableDatabase();\n writableDatabase.execSQL(CrashTable.TRUNCATE_QUERY);\n writableDatabase.close();\n }\n}", "public class SherlockDatabaseHelper extends SQLiteOpenHelper {\n private static final int VERSION = 2;\n private static final String DB_NAME = \"Sherlock\";\n\n public SherlockDatabaseHelper(Context context) {\n super(context, DB_NAME, null, VERSION);\n }\n\n @Override\n public void onCreate(SQLiteDatabase database) {\n database.execSQL(CrashTable.CREATE_QUERY);\n }\n\n @Override\n public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {\n sqLiteDatabase.execSQL(CrashTable.DROP_QUERY);\n sqLiteDatabase.execSQL(CrashTable.CREATE_QUERY);\n }\n\n public int insertCrash(CrashRecord crashRecord) {\n ContentValues values = new ContentValues();\n values.put(CrashTable.PLACE, crashRecord.getPlace());\n values.put(CrashTable.REASON, crashRecord.getReason());\n values.put(CrashTable.STACKTRACE, crashRecord.getStackTrace());\n values.put(CrashTable.DATE, crashRecord.getDate());\n\n SQLiteDatabase database = getWritableDatabase();\n long id = database.insert(CrashTable.TABLE_NAME, null, values);\n database.close();\n\n return Long.valueOf(id).intValue();\n }\n\n public List<Crash> getCrashes() {\n SQLiteDatabase readableDatabase = getReadableDatabase();\n ArrayList<Crash> crashes = new ArrayList<>();\n Cursor cursor = readableDatabase.rawQuery(CrashTable.SELECT_ALL, null);\n if (isCursorPopulated(cursor)) {\n do {\n crashes.add(toCrash(cursor));\n } while (cursor.moveToNext());\n }\n\n cursor.close();\n readableDatabase.close();\n\n return crashes;\n }\n\n public Crash getCrashById(int id) {\n SQLiteDatabase readableDatabase = getReadableDatabase();\n Cursor cursor = readableDatabase.rawQuery(CrashTable.selectById(id), null);\n Crash crash = null;\n\n if (isCursorPopulated(cursor)) {\n crash = toCrash(cursor);\n cursor.close();\n readableDatabase.close();\n }\n\n return crash;\n }\n\n @NonNull\n private Crash toCrash(Cursor cursor) {\n int id = cursor.getInt(cursor.getColumnIndex(CrashTable._ID));\n String placeOfCrash = cursor.getString(cursor.getColumnIndex(CrashTable.PLACE));\n String reasonOfCrash = cursor.getString(cursor.getColumnIndex(CrashTable.REASON));\n String stacktrace = cursor.getString(cursor.getColumnIndex(CrashTable.STACKTRACE));\n String date = cursor.getString(cursor.getColumnIndex(CrashTable.DATE));\n return new Crash(id, placeOfCrash, reasonOfCrash, stacktrace, date);\n }\n\n private boolean isCursorPopulated(Cursor cursor) {\n return cursor != null && cursor.moveToFirst();\n }\n}", "public class AppInfo {\n private List<Pair> appDetails = new ArrayList<>();\n\n private AppInfo(List<Pair> appDetails) {\n this.appDetails = appDetails;\n }\n\n public Map<String, String> getAppDetails() {\n TreeMap<String, String> details = new TreeMap<>();\n for (Pair pair : appDetails) {\n details.put(pair.getKey(), pair.getVal());\n }\n return details.descendingMap();\n }\n\n public static class Builder {\n List<Pair> appDetails = new ArrayList<>();\n\n public Builder with(String key, String value) {\n appDetails.add(new Pair(key, value));\n return this;\n }\n\n public AppInfo build() {\n return new AppInfo(appDetails);\n }\n }\n}", "public interface AppInfoProvider {\n AppInfo getAppInfo();\n}", "public class Crash {\n public static final String DATE_FORMAT = \"EEE MMM dd kk:mm:ss z yyyy\";\n\n public Crash(String place, String reason, String stackTrace) {\n }\n\n public Crash(int id, String placeOfCrash, String reasonOfCrash, String stacktrace, String date) {\n }\n\n public DeviceInfo getDeviceInfo() {\n return new DeviceInfo.Builder().build();\n }\n\n public AppInfo getAppInfo() {\n return new AppInfo();\n }\n\n public void setId(int id) {\n }\n\n public Class<Crash> getType() {\n return Crash.class;\n }\n\n public String getReason() {\n return \"\";\n }\n\n public String getStackTrace() {\n return \"\";\n }\n\n public String getPlace() {\n return \"\";\n }\n\n public int getId() {\n return 0;\n }\n\n public Date getDate() {\n return new Date();\n }\n}", "public class CrashActivity extends BaseActivity implements CrashActions {\n public static final String CRASH_ID = \"com.singhajit.sherlock.CRASH_ID\";\n private CrashViewModel viewModel = new CrashViewModel();\n private CrashPresenter presenter;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n Intent intent = getIntent();\n int crashId = intent.getIntExtra(CRASH_ID, -1);\n setContentView(R.layout.crash_activity);\n\n enableHomeButton((Toolbar) findViewById(R.id.toolbar));\n setTitle(R.string.crash_report);\n\n presenter = new CrashPresenter(new SherlockDatabaseHelper(this), this);\n presenter.render(crashId);\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n getMenuInflater().inflate(R.menu.crash_menu, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n if (item.getItemId() == R.id.share) {\n presenter.shareCrashDetails(viewModel);\n return true;\n }\n return super.onOptionsItemSelected(item);\n }\n\n @Override\n public void render(CrashViewModel viewModel) {\n this.viewModel = viewModel;\n TextView crashLocation = (TextView) findViewById(R.id.crash_location);\n TextView crashReason = (TextView) findViewById(R.id.crash_reason);\n TextView stackTrace = (TextView) findViewById(R.id.stacktrace);\n\n crashLocation.setText(viewModel.getExactLocationOfCrash());\n crashReason.setText(viewModel.getReasonOfCrash());\n stackTrace.setText(viewModel.getStackTrace());\n\n renderDeviceInfo(viewModel);\n }\n\n @Override\n public void openSendApplicationChooser(String crashDetails) {\n Intent share = new Intent(Intent.ACTION_SEND);\n share.setType(\"text/plain\");\n share.putExtra(Intent.EXTRA_TEXT, crashDetails);\n\n startActivity(Intent.createChooser(share, getString(R.string.share_dialog_message)));\n }\n\n @Override\n public void renderAppInfo(AppInfoViewModel viewModel) {\n RecyclerView appInfoDetails = (RecyclerView) findViewById(R.id.app_info_details);\n appInfoDetails.setAdapter(new AppInfoAdapter(viewModel));\n appInfoDetails.setLayoutManager(new LinearLayoutManager(this));\n }\n\n private void renderDeviceInfo(CrashViewModel viewModel) {\n TextView deviceName = (TextView) findViewById(R.id.device_name);\n TextView deviceBrand = (TextView) findViewById(R.id.device_brand);\n TextView deviceAndroidVersion = (TextView) findViewById(R.id.device_android_version);\n\n deviceName.setText(viewModel.getDeviceName());\n deviceBrand.setText(viewModel.getDeviceBrand());\n deviceAndroidVersion.setText(viewModel.getDeviceAndroidApiVersion());\n }\n}", "public static Matcher<View> withRecyclerView(final int recyclerViewId, final int position) {\n return new CustomTypeSafeMatcher<View>(\"\") {\n @Override\n protected boolean matchesSafely(View item) {\n RecyclerView view = (RecyclerView) item.getRootView().findViewById(recyclerViewId);\n return view.getChildAt(position) == item;\n }\n };\n}" ]
import android.content.Context; import android.content.Intent; import android.support.test.InstrumentationRegistry; import android.support.test.rule.ActivityTestRule; import com.singhajit.sherlock.R; import com.singhajit.sherlock.core.Sherlock; import com.singhajit.sherlock.core.database.CrashRecord; import com.singhajit.sherlock.core.database.DatabaseResetRule; import com.singhajit.sherlock.core.database.SherlockDatabaseHelper; import com.singhajit.sherlock.core.investigation.AppInfo; import com.singhajit.sherlock.core.investigation.AppInfoProvider; import com.singhajit.sherlock.core.investigation.Crash; import com.singhajit.sherlock.crashes.activity.CrashActivity; import org.junit.Rule; import org.junit.Test; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.scrollTo; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.hasDescendant; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static com.singhajit.sherlock.CustomEspressoMatchers.withRecyclerView; import static org.hamcrest.Matchers.allOf;
package com.singhajit.sherlock.crashes; public class CrashActivityTest { @Rule public DatabaseResetRule databaseResetRule = new DatabaseResetRule(); @Rule public ActivityTestRule<CrashActivity> rule = new ActivityTestRule<>(CrashActivity.class, true, false); @Test public void shouldRenderCrashDetails() throws Exception { Context targetContext = InstrumentationRegistry.getTargetContext(); Sherlock.init(targetContext); Sherlock.setAppInfoProvider(new AppInfoProvider() { @Override
public AppInfo getAppInfo() {
4
matburt/mobileorg-android
MobileOrg/src/main/java/com/matburt/mobileorg/gui/outline/OutlineAdapter.java
[ "public class AgendaFragment extends Fragment {\n\n class AgendaItem {\n public OrgNodeTimeDate.TYPE type;\n public OrgNode node;\n public String text;\n long time;\n public AgendaItem(OrgNode node, OrgNodeTimeDate.TYPE type, long time){\n this.node = node;\n this.type = type;\n this.time = time;\n\n OrgNodeTimeDate date = new OrgNodeTimeDate(time);\n\n if(time < 0 || (node.getRangeInSec() > 86400 && date.isBetween(node.getScheduled(), node.getDeadline()))){\n text = getActivity().getResources().getString(R.string.all_day);\n } else {\n text = date.toString(false);\n }\n\n }\n }\n\n RecyclerViewAdapter adapter;\n RecyclerView recyclerView;\n ArrayList<AgendaItem> nodesList;\n ArrayList<OrgNodeTimeDate> daysList;\n ArrayList<PositionHelper> items;\n private ContentResolver resolver;\n\n /**\n * Mandatory empty constructor for the fragment manager to instantiate the\n * fragment (e.g. upon screen orientation changes).\n */\n public AgendaFragment() {\n }\n\n static void setItemModifiersVisibility(View view, int visibility) {\n LinearLayout itemModifiers = (LinearLayout) view.findViewById(R.id.item_modifiers);\n if (itemModifiers != null) itemModifiers.setVisibility(visibility);\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n this.resolver = getActivity().getContentResolver();\n\n\n Cursor cursor = resolver.query(Timestamps.CONTENT_URI,\n new String[]{Timestamps.NODE_ID, Timestamps.TIMESTAMP, Timestamps.TYPE},\n null, null, Timestamps.TIMESTAMP);\n\n nodesList = new ArrayList<>();\n items = new ArrayList<>();\n daysList = new ArrayList<>();\n\n // Nodes with only a deadline or a scheduled but not both\n HashSet<Long> orphanTimestampsNodes = new HashSet<>();\n\n // Nodes with a deadline AND a scheduled date\n HashSet<Long> rangedTimestampsNodes = new HashSet<>();\n\n if (cursor != null) {\n\n while (cursor.moveToNext()) {\n long nodeId = cursor.getLong(cursor.getColumnIndexOrThrow(Timestamps.NODE_ID));\n\n if (orphanTimestampsNodes.contains(nodeId)) {\n orphanTimestampsNodes.remove(nodeId);\n rangedTimestampsNodes.add(nodeId);\n } else {\n orphanTimestampsNodes.add(nodeId);\n }\n }\n cursor.close();\n }\n\n\n TreeMap<Long, ArrayList<AgendaItem>> nodeIdsForEachDay = new TreeMap<>();\n\n for (Long nodeId : orphanTimestampsNodes) {\n try {\n OrgNode node = new OrgNode(nodeId, resolver);\n Long day, time;\n OrgNodeTimeDate.TYPE type;\n if (node.getScheduled().getEpochTime() < 0) {\n type = OrgNodeTimeDate.TYPE.Deadline;\n time = node.getDeadline().getEpochTime();\n } else {\n time = node.getScheduled().getEpochTime();\n type = OrgNodeTimeDate.TYPE.Scheduled;\n }\n\n day = time / (24*3600);\n\n if (!nodeIdsForEachDay.containsKey(day))\n nodeIdsForEachDay.put(day, new ArrayList<AgendaItem>());\n nodeIdsForEachDay.get(day).add(new AgendaItem(node, type, time));\n } catch (OrgNodeNotFoundException e) {\n // If we are here, it means an OrgNode has been deleted but not the corresponding\n // timestamps from the Timestamp database. So we do the cleanup.\n OrgNodeTimeDate.deleteTimestamp(getActivity(), nodeId, null);\n e.printStackTrace();\n }\n }\n\n for (Long nodeId : rangedTimestampsNodes) {\n try {\n OrgNode node = new OrgNode(nodeId, resolver);\n boolean scheduledBeforeDeadline = node.getScheduled().getEpochTime() < node.getDeadline().getEpochTime();\n\n long firstTime = scheduledBeforeDeadline ? node.getScheduled().getEpochTime() : node.getDeadline().getEpochTime();\n long lastTime = scheduledBeforeDeadline ? node.getDeadline().getEpochTime() : node.getScheduled().getEpochTime();\n long firstDay = firstTime / (24 * 3600);\n long lastDay = lastTime / (24 * 3600);\n OrgNodeTimeDate.TYPE type;\n long time;\n for (long day = firstDay; day <= lastDay; day++) {\n if(firstDay == lastDay){\n if (!nodeIdsForEachDay.containsKey(day))\n nodeIdsForEachDay.put(day, new ArrayList<AgendaItem>());\n nodeIdsForEachDay.get(day).add(new AgendaItem(node, scheduledBeforeDeadline ? OrgNodeTimeDate.TYPE.Scheduled : OrgNodeTimeDate.TYPE.Deadline, firstTime));\n nodeIdsForEachDay.get(day).add(new AgendaItem(node, scheduledBeforeDeadline ? OrgNodeTimeDate.TYPE.Deadline : OrgNodeTimeDate.TYPE.Scheduled, lastTime));\n } else {\n if (day == firstDay) {\n type = scheduledBeforeDeadline ? OrgNodeTimeDate.TYPE.Scheduled : OrgNodeTimeDate.TYPE.Deadline;\n time = firstTime;\n } else if (day == lastDay) {\n type = scheduledBeforeDeadline ? OrgNodeTimeDate.TYPE.Deadline : OrgNodeTimeDate.TYPE.Scheduled;\n time = lastTime;\n } else {\n type = OrgNodeTimeDate.TYPE.Timestamp;\n time = -1;\n }\n if (!nodeIdsForEachDay.containsKey(day))\n nodeIdsForEachDay.put(day, new ArrayList<AgendaItem>());\n nodeIdsForEachDay.get(day).add(new AgendaItem(node, type, time));\n }\n }\n } catch (OrgNodeNotFoundException e) {\n e.printStackTrace();\n }\n }\n\n int dayCursor = 0, nodeCursor = 0;\n for (long day : nodeIdsForEachDay.keySet()) {\n daysList.add(new OrgNodeTimeDate(day * 3600 * 24));\n items.add(new PositionHelper(dayCursor++, Type.kDate));\n Collections.sort(nodeIdsForEachDay.get(day), new TimeComparator());\n for (AgendaItem item: nodeIdsForEachDay.get(day)) {\n nodesList.add(item);\n items.add(new PositionHelper(nodeCursor++, Type.kNode));\n }\n }\n\n adapter = new RecyclerViewAdapter();\n }\n\n class TimeComparator implements Comparator<AgendaItem> {\n @Override\n public int compare(AgendaItem a, AgendaItem b) {\n return a.time < b.time ? -1 : a.time == b.time ? 0 : 1;\n }\n }\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n View rootView = inflater.inflate(R.layout.node_summary_recycler_fragment, container, false);\n\n recyclerView = (RecyclerView) rootView.findViewById(R.id.node_recycler_view);\n assert recyclerView != null;\n recyclerView.addItemDecoration(new DividerItemDecoration(getContext()));\n\n recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));\n recyclerView.setAdapter(adapter);\n\n return rootView;\n }\n\n @Override\n public void onResume(){\n super.onResume();\n }\n\n enum Type {\n kNode,\n kDate\n }\n\n class PositionHelper {\n int position;\n Type type;\n\n PositionHelper(int position, Type type) {\n this.position = position;\n this.type = type;\n }\n }\n\n\n\n public class RecyclerViewAdapter\n extends RecyclerView.Adapter<ItemViewHolder> {\n\n public RecyclerViewAdapter() {\n\n }\n\n @Override\n public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n View view;\n if(viewType == Type.kDate.ordinal()){\n view = LayoutInflater.from(parent.getContext())\n .inflate(R.layout.days_view_holder, parent, false);\n return new DateViewHolder(view);\n } else {\n view = LayoutInflater.from(parent.getContext())\n .inflate(R.layout.agenda_recycler_item, parent, false);\n return new OrgItemViewHolder(view);\n }\n }\n\n @Override\n public void onBindViewHolder(final ItemViewHolder holder, final int position) {\n int type = getItemViewType(position);\n\n if(type == Type.kDate.ordinal()) onBindDateHolder((DateViewHolder)holder, position);\n else onBindOrgItemHolder((OrgItemViewHolder)holder, position);\n }\n\n private void onBindOrgItemHolder(final OrgItemViewHolder holder, int position){\n final AgendaItem item = nodesList.get(items.get(position).position);\n final OrgNode node = item.node;\n\n // The day associated with this item\n int dayPosition = position;\n while(items.get(dayPosition).type != Type.kDate && dayPosition > 0) dayPosition--;\n\n TextView title = (TextView) holder.itemView.findViewById(R.id.title);\n TextView details = (TextView) holder.itemView.findViewById(R.id.details);\n\n title.setText(node.name);\n\n String textDetails = node.getPayload();\n\n if (textDetails.equals(\"\")) {\n RelativeLayout.LayoutParams layoutParams =\n (RelativeLayout.LayoutParams) title.getLayoutParams();\n layoutParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);\n title.setLayoutParams(layoutParams);\n\n details.setVisibility(View.GONE);\n } else {\n details.setText(textDetails);\n }\n\n TextView content = (TextView) holder.itemView.findViewById(R.id.date);\n\n // If event spans on more than one day (=86499 sec), tag the enclosed days as 'all days'\n content.setText(item.text);\n\n holder.itemView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n EditNodeFragment.createEditNodeFragment((int)node.id, -1, -1, getContext());\n }\n });\n\n holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {\n @Override\n public boolean onLongClick(View v) {\n return true;\n }\n });\n }\n\n private void onBindDateHolder(final DateViewHolder holder, int position){\n final OrgNodeTimeDate date = daysList.get(items.get(position).position);\n\n TextView title = (TextView) holder.itemView.findViewById(R.id.outline_item_title);\n title.setText(date.toString(true));\n\n holder.itemView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n\n }\n });\n\n holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {\n @Override\n public boolean onLongClick(View v) {\n return true;\n }\n });\n }\n\n @Override\n public int getItemCount() {\n return items.size();\n }\n\n @Override\n public int getItemViewType(int position){\n return items.get(position).type.ordinal();\n }\n\n /**\n * The view holder for the date\n */\n private class DateViewHolder extends ItemViewHolder {\n public DateViewHolder(View view) {\n super(view);\n }\n }\n\n /**\n * The view holder for the node items\n */\n private class OrgItemViewHolder extends ItemViewHolder {\n public OrgItemViewHolder(View view) {\n super(view);\n }\n }\n\n\n }\n\n public class DividerItemDecoration extends RecyclerView.ItemDecoration {\n\n private final int[] ATTRS = new int[]{android.R.attr.listDivider};\n\n private Drawable mDivider;\n\n /**\n * Default divider will be used\n */\n public DividerItemDecoration(Context context) {\n final TypedArray styledAttributes = context.obtainStyledAttributes(ATTRS);\n mDivider = styledAttributes.getDrawable(0);\n styledAttributes.recycle();\n }\n\n /**\n * Custom divider will be used\n */\n public DividerItemDecoration(Context context, int resId) {\n mDivider = ContextCompat.getDrawable(context, resId);\n }\n\n @Override\n public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {\n int left = parent.getPaddingLeft();\n int right = parent.getWidth() - parent.getPaddingRight();\n\n int childCount = parent.getChildCount();\n for (int i = 0; i < childCount; i++) {\n View child = parent.getChildAt(i);\n\n RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();\n\n int top = child.getBottom() + params.bottomMargin;\n int bottom = top + mDivider.getIntrinsicHeight();\n\n mDivider.setBounds(left, top, right, bottom);\n mDivider.draw(c);\n }\n }\n }\n}", "public class DefaultTheme {\n\t\n\tpublic int gray = Color.GRAY;\n\t\n\tpublic int c0Black = Color.rgb(0x00, 0x00, 0x00);\n\tpublic int c1Red = Color.rgb(0xd0, 0x00, 0x00);\n\tpublic int c2Green = Color.rgb(0x00, 0xa0, 0x00);\n\tpublic int c3Yellow = Color.rgb(0xc0, 0x80, 0x00);\n\tpublic int c4Blue = Color.rgb(0x22, 0x22, 0xf0);\n\tpublic int c5Purple = Color.rgb(0xa0, 0x00, 0xa0);\n\tpublic int c6Cyan = Color.rgb(0x00, 0x80, 0x80);\n\tpublic int c7White = Color.rgb(0xc0, 0xc0, 0xc0);\n\n\tpublic int c9LRed = Color.rgb(0xff, 0x77, 0x77);\n\tpublic int caLGreen = Color.rgb(0x77, 0xff, 0x77);\n\tpublic int cbLYellow = Color.rgb(0xff, 0xff, 0x00);\n\tpublic int ccLBlue = Color.rgb(0x88, 0x88, 0xff);\n\tpublic int cdLPurple = Color.rgb(0xff, 0x00, 0xff);\n\tpublic int ceLCyan = Color.rgb(0x00, 0xff, 0xff);\n\tpublic int cfLWhite = Color.rgb(0xff, 0xff, 0xff);\n\n\tpublic int defaultForeground = Color.rgb(0xc0, 0xc0, 0xc0);\n\tpublic int defaultBackground = Color.rgb(0x00, 0x00, 0x00);\n\t\n\tpublic int[] levelColors;\n\t\n\tpublic String defaultFontColor = \"white\";\n\t\n\tpublic DefaultTheme() {\n\t\tlevelColors = new int[] { ccLBlue, c3Yellow, ceLCyan, c2Green,\n\t\t\t\tc5Purple, ccLBlue, c2Green, ccLBlue, c3Yellow, ceLCyan };\n\t}\n\t\n\t\n\tpublic static DefaultTheme getTheme(Context context) {\n\t\tfinal String themeName = PreferenceUtils.getThemeName();\n\t\tif(themeName.equals(\"Light\"))\n\t\t\t\treturn new WhiteTheme();\n\t\telse if(themeName.equals(\"Monochrome\"))\n\t\t\treturn new MonoTheme();\n\t\telse\n\t\t\treturn new DefaultTheme();\n\t}\n}", "public class OrgContract {\n\tpublic static final String CONTENT_AUTHORITY = \"com.matburt.mobileorg.orgdata.OrgProvider\";\n\tprivate static final Uri BASE_CONTENT_URI = Uri.parse(\"content://\" + CONTENT_AUTHORITY);\n\tprivate static final String PATH_ORGDATA = OrgDatabase.Tables.ORGDATA;\n\tprivate static final String PATH_TIMESTAMPS = OrgDatabase.Tables.TIMESTAMPS;\n\tprivate static final String PATH_TODOS = OrgDatabase.Tables.TODOS;\n\tprivate static final String PATH_TAGS = OrgDatabase.Tables.TAGS;\n\tprivate static final String PATH_PRIORITIES = OrgDatabase.Tables.PRIORITIES;\n\tprivate static final String PATH_FILES = OrgDatabase.Tables.FILES;\n\tprivate static final String PATH_SEARCH = \"search\";\n\tstatic public long TODO_ID = -2;\n\tstatic public long AGENDA_ID = -3;\n\tpublic static String NODE_ID = \"node_id\";\n\tpublic static String PARENT_ID = \"parent_id\";\n\tpublic static String POSITION = \"position\";\n\n\t/**\n\t * @param tableName\n\t * @param columns\n\t * @return the list of column prefixed by the table name and separated by a \",\"\n\t */\n\tpublic static String formatColumns(String tableName, String[] columns) {\n\t\tString result = \"\";\n\t\tfor (String column : columns)\n\t\t\tresult += tableName + \".\" + column + \", \";\n\t\tresult = result.substring(0, result.length() - 2); // removing the last \", \"\n\t\treturn result;\n\t}\n\tinterface TimestampsColumns {\n\t\tString NODE_ID = \"node_id\";\n\t\tString FILE_ID = \"file_id\";\n\t\tString TYPE = \"type\";\n\t\tString TIMESTAMP = \"timestamp\";\n\t\tString ALL_DAY = \"all_day\";\n\t}\n\n\tinterface OrgDataColumns {\n\t\tString ID = \"_id\";\n\t\tString NAME = \"name\";\n\t\tString TODO = \"todo\";\n\t\tString PARENT_ID = \"parent_id\";\n\t\tString FILE_ID = \"file_id\";\n\t\tString LEVEL = \"level\";\n\t\tString POSITION = \"position\";\n\t\tString PRIORITY = \"priority\";\n\t\tString TAGS = \"tags\";\n\t\tString TAGS_INHERITED = \"tags_inherited\";\n\t\tString PAYLOAD = \"payload\";\n\t\tString DEADLINE = \"deadline\";\n\t\tString SCHEDULED = \"scheduled\";\n\t\tString DEADLINE_DATE_ONLY = \"deadline_date_only\";\n\t\tString SCHEDULED_DATE_ONLY = \"scheduled_date_only\";\n\t}\n\tinterface FilesColumns {\n\t\tString ID = \"_id\";\n\t\tString NAME = \"name\";\n\t\tString FILENAME = \"filename\";\n\t\tString COMMENT = \"comment\";\n\t\tString NODE_ID = \"node_id\";\n\t}\n\tinterface TodosColumns {\n\t\tString ID = \"_id\";\n\t\tString NAME = \"name\";\n\t\tString GROUP = \"todogroup\";\n\t\tString ISDONE = \"isdone\";\n\t}\n\tinterface TagsColumns {\n\t\tString ID = \"_id\";\n\t\tString NAME = \"name\";\n\t\tString GROUP = \"taggroup\";\n\t}\n\n\tinterface PrioritiesColumns {\n\t\tString ID = \"_id\";\n\t\tString NAME = \"name\";\n\t}\n\t\n\tpublic static class OrgData implements OrgDataColumns {\n\t\tpublic static final Uri CONTENT_URI =\n\t\t\t\tBASE_CONTENT_URI.buildUpon().appendPath(PATH_ORGDATA).build();\n\n\t\tpublic static final Uri CONTENT_URI_TODOS =\n\t\t\t\tBASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build();\n\t\tpublic static final String DEFAULT_SORT = ID + \" ASC\";\n\t\tpublic static final String NAME_SORT = NAME + \" ASC\";\n\t\tpublic static final String POSITION_SORT = POSITION + \" ASC\";\n\t\tpublic static final String[] DEFAULT_COLUMNS = {ID, NAME, TODO, TAGS, TAGS_INHERITED,\n\t\t\t\tPARENT_ID, PAYLOAD, LEVEL, PRIORITY, FILE_ID, POSITION, SCHEDULED, SCHEDULED_DATE_ONLY, DEADLINE, DEADLINE_DATE_ONLY};\n\n\t\tpublic static String getId(Uri uri) {\n\t\t\treturn uri.getPathSegments().get(1);\n\t\t}\n\n\t\tpublic static Uri buildIdUri(String id) {\n\t\t\treturn CONTENT_URI.buildUpon().appendPath(id).build();\n\t\t}\n\n\t\tpublic static Uri buildIdUri(Long id) {\n\t\t\treturn buildIdUri(id.toString());\n\t\t}\n\n\t\tpublic static Uri buildChildrenUri(String parentId) {\n\t\t\treturn CONTENT_URI.buildUpon().appendPath(parentId).appendPath(\"children\").build();\n\t\t}\n\n\t\tpublic static Uri buildChildrenUri(long node_id) {\n\t\t\treturn buildChildrenUri(Long.toString(node_id));\n\t\t}\n\t}\n\t\n\tpublic static class Timestamps implements TimestampsColumns {\n\t\tpublic static final Uri CONTENT_URI =\n\t\t\t\tBASE_CONTENT_URI.buildUpon().appendPath(PATH_TIMESTAMPS).build();\n\t\tpublic static final String[] DEFAULT_COLUMNS = {NODE_ID, FILE_ID, TYPE, TIMESTAMP, ALL_DAY};\n\n\t\tpublic static Uri buildIdUri(Long id) {\n\t\t\treturn CONTENT_URI.buildUpon().appendPath(id.toString()).build();\n\t\t}\n\n\t\tpublic static String getId(Uri uri) {\n\t\t\treturn uri.getLastPathSegment();\n\t\t}\n\t}\n\t\n\tpublic static class Files implements FilesColumns {\n\t\tpublic static final Uri CONTENT_URI =\n\t\t\t\tBASE_CONTENT_URI.buildUpon().appendPath(PATH_FILES).build();\n\n\t\tpublic static final String[] DEFAULT_COLUMNS = { ID, NAME, FILENAME,\n\t\t\t\tCOMMENT, NODE_ID };\n\t\tpublic static final String DEFAULT_SORT = NAME + \" ASC\";\n\n\t\tpublic static String getId(Uri uri) {\n\t\t\treturn uri.getLastPathSegment();\n\t\t}\n\n\t\tpublic static String getFilename(Uri uri) {\n\t\t\treturn uri.getPathSegments().get(1);\n\t\t}\n\n\t\tpublic static Uri buildFilenameUri(String filename) {\n\t\t\treturn CONTENT_URI.buildUpon().appendPath(filename)\n\t\t\t\t\t.appendPath(\"filename\").build();\n\t\t}\n\n\t\tpublic static Uri buildIdUri(Long fileId) {\n\t\t\treturn CONTENT_URI.buildUpon().appendPath(fileId.toString()).build();\n\t\t}\n\t}\n\t\n\tpublic static class Todos implements TodosColumns {\n\t\tpublic static final Uri CONTENT_URI =\n\t\t\t\tBASE_CONTENT_URI.buildUpon().appendPath(PATH_TODOS).build();\n\n\t\tpublic static final String[] DEFAULT_COLUMNS = {NAME, ID, GROUP, ISDONE};\n\t}\n\t\n\tpublic static class Tags implements TagsColumns {\n\t\tpublic static final Uri CONTENT_URI =\n\t\t\t\tBASE_CONTENT_URI.buildUpon().appendPath(PATH_TAGS).build();\n\t}\n\t\n\tpublic static class Priorities implements PrioritiesColumns {\n\t\tpublic static final Uri CONTENT_URI =\n\t\t\t\tBASE_CONTENT_URI.buildUpon().appendPath(PATH_PRIORITIES).build();\n\t}\n\n\tpublic static class Search implements OrgDataColumns {\n\t\tpublic static final Uri CONTENT_URI =\n\t\t\t\tBASE_CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).build();\n\n\t\tpublic static String getSearchTerm(Uri uri) {\n\t\t\treturn uri.getLastPathSegment();\n\t\t}\n\t}\n}", "public class OrgFile {\n\tpublic static final String CAPTURE_FILE = \"mobileorg.org\";\n\tpublic static final String CAPTURE_FILE_ALIAS = \"Captures\";\n\tpublic static final String AGENDA_FILE = \"agendas.org\";\n\tpublic static final String AGENDA_FILE_ALIAS = \"Agenda Views\";\n\n\tpublic String filename = \"\";\n\tpublic String name = \"\";\n\tpublic String comment = \"\";\n\n\tpublic long id = -1;\n\tpublic long nodeId = -1;\n\n\tpublic OrgFile() {\n\t}\n\n\tpublic OrgFile(String filename, String name) {\n\t\tthis.filename = filename;\n\n if (name == null || name.equals(\"null\"))\n this.name = filename;\n else\n this.name = name;\n }\n\n\tpublic OrgFile(Cursor cursor) throws OrgFileNotFoundException {\n\t\tset(cursor);\n\t}\n\n\tpublic OrgFile(long id, ContentResolver resolver) throws OrgFileNotFoundException {\n\t\tCursor cursor = resolver.query(Files.buildIdUri(id),\n\t\t\t\tFiles.DEFAULT_COLUMNS, null, null, null);\n if (cursor == null || cursor.getCount() < 1) {\n if (cursor != null) cursor.close();\n throw new OrgFileNotFoundException(\"File with id \\\"\" + id + \"\\\" not found\");\n\t\t}\n\n\t\tset(cursor);\n\t\tcursor.close();\n\t}\n\n\tpublic OrgFile(String filename, ContentResolver resolver) throws OrgFileNotFoundException {\n\t\tCursor cursor = resolver.query(Files.CONTENT_URI,\n Files.DEFAULT_COLUMNS, Files.FILENAME + \"=?\", new String[]{filename}, null);\n if (cursor == null || cursor.getCount() <= 0) {\n if (cursor != null) cursor.close();\n throw new OrgFileNotFoundException(\"File \\\"\" + filename + \"\\\" not found\");\n\t\t}\n\n\t\tset(cursor);\n\t\tcursor.close();\n\t}\n\n\t/**\n\t * Edit the org file on disk to incorporate new modifications\n\t * @param node: Any node from the file\n\t * @param context: context\n\t */\n\tstatic public void updateFile(OrgNode node, Context context) {\n\t\tContentResolver resolver = context.getContentResolver();\n\t\ttry {\n\t\t\tOrgFile file = new OrgFile(node.fileId, resolver);\n\t\t\tfile.updateFile(file.toString(resolver), context);\n\t\t} catch (OrgFileNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tpublic void set(Cursor cursor) throws OrgFileNotFoundException {\n\t\tif (cursor != null && cursor.getCount() > 0) {\n if (cursor.isBeforeFirst() || cursor.isAfterLast())\n cursor.moveToFirst();\n\t\t\tthis.name = OrgProviderUtils.getNonNullString(cursor,\n\t\t\t\t\tcursor.getColumnIndexOrThrow(Files.NAME));\n\t\t\tthis.filename = OrgProviderUtils.getNonNullString(cursor,\n\t\t\t\t\tcursor.getColumnIndexOrThrow(Files.FILENAME));\n\t\t\tthis.id = cursor.getLong(cursor.getColumnIndexOrThrow(Files.ID));\n\t\t\tthis.nodeId = cursor.getLong(cursor.getColumnIndexOrThrow(Files.NODE_ID));\n\t\t\tthis.comment = OrgProviderUtils.getNonNullString(cursor,\n\t\t\t\t\tcursor.getColumnIndexOrThrow(Files.COMMENT));\n\t\t} else {\n\t\t\tthrow new OrgFileNotFoundException(\n\t\t\t\t\t\"Failed to create OrgFile from cursor\");\n }\n }\n\n\tpublic boolean doesFileExist(ContentResolver resolver) {\n\t\tCursor cursor = resolver.query(Files.buildFilenameUri(filename),\n\t\t\t\tFiles.DEFAULT_COLUMNS, null, null, null);\n\t\tint count = cursor.getCount();\n\t\tcursor.close();\n\n\t\treturn count > 0;\n\t}\n\n\tpublic OrgNode getOrgNode(ContentResolver resolver) {\n\t\ttry {\n\t\t\treturn new OrgNode(this.nodeId, resolver);\n\t\t} catch (OrgNodeNotFoundException e) {\n\t\t\tthrow new IllegalStateException(\"Org node for file \" + filename\n\t\t\t\t\t+ \" should exist\");\n\t\t}\n\t}\n\n\t/**\n\t * Add the file to the DB, then create file on disk if does not exist\n\t *\n * @param context\n */\n public void addFile(Context context) {\n ContentResolver resolver = context.getContentResolver();\n\t\tthis.nodeId = addFileOrgDataNode(resolver);\n\n\t\tthis.id = addFileNode(nodeId, resolver);\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(OrgData.FILE_ID, id);\n\t\tresolver.update(OrgData.buildIdUri(nodeId), values, null, null);\n\t\tif(!new File(getFilePath(context)).exists()) createFile(context);\n\t}\n\n\t/**\n\t Insert a new file node in the \"Files\" database\n\t **/\n\tprivate long addFileNode(long nodeId, ContentResolver resolver) {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(Files.FILENAME, filename);\n\t\tvalues.put(Files.NAME, name);\n\t\tvalues.put(Files.NODE_ID, nodeId);\n\n\t\tUri uri = resolver.insert(Files.CONTENT_URI, values);\n//\t\tLog.v(\"uri\", \"uri : \" + uri);\n\t\treturn Long.parseLong(Files.getId(uri));\n\t}\n\n\t/**\n\t Insert the root OrgNode of this file in the \"OrgData\" database\n\t **/\n\tprivate long addFileOrgDataNode(ContentResolver resolver) {\n\t\tContentValues orgdata = new ContentValues();\n\t\torgdata.put(OrgData.NAME, name);\n\t\torgdata.put(OrgData.TODO, \"\");\n\t\torgdata.put(OrgData.PRIORITY, \"\");\n\t\torgdata.put(OrgData.LEVEL, 0);\n\t\torgdata.put(OrgData.PARENT_ID, -1);\n\n\t\tUri uri = resolver.insert(OrgData.CONTENT_URI, orgdata);\n\t\tlong nodeId = Long.parseLong(OrgData.getId(uri));\n\t\treturn nodeId;\n }\n\n\t/**\n\t * Create a file on disk\n\t * @param context\n */\n\tpublic void createFile(Context context){\n\t\tupdateFile(\"\", context);\n\t}\n\n /**\n * Replace the old content of the file by 'content'\n *\n * @param content the new content of the file\n * @param context\n */\n public void updateFile(String content, Context context) {\n File file = new File(getFilePath(context));\n FileOutputStream outputStream = null;\n try {\n outputStream = new FileOutputStream(file);\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n return;\n }\n\n try {\n outputStream.write(content.getBytes());\n outputStream.close();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n\n }\n }\n\n\t/**\n\t * 1) Remove all OrgNode(s) associated with this file from the DB\n\t * 2) Remove this OrgFile node from the DB\n\t * 3) Remove file from disk\n *\n\t * @param context\n\t * @param fromDisk: whether or not the file has to be deleted from disk\n\t * @return the number of OrgData nodes removed\n */\n\tpublic long removeFile(Context context, boolean fromDisk) {\n\t\tContentResolver resolver = context.getContentResolver();\n\n\t\tlong entriesRemoved = removeFileOrgDataNodes(resolver);\n\t\tremoveFileNode(resolver);\n\t\tif (fromDisk) new File(getFilePath(context)).delete();\n\n return entriesRemoved;\n\t}\n\n\tprivate long removeFileNode(ContentResolver resolver) {\n\t\tint total = 0;\n\t\ttry {\n\t\t\ttotal += resolver.delete(Files.buildIdUri(id), Files.NAME + \"=? AND \"\n\t\t\t\t\t+ Files.FILENAME + \"=?\", new String[]{name, filename});\n\t\t} catch (IllegalArgumentException e){\n\t\t\t// Uri does not exist, no need to delete\n\t\t}\n\t\treturn total;\n }\n\n\t/**\n\t * Update this file in the DB\n\t * @param resolver\n\t * @param values\n * @return\n */\n\tpublic long updateFileInDB(ContentResolver resolver, ContentValues values) {\n\t\treturn resolver.update(Files.buildIdUri(id), values, Files.NAME + \"=? AND \"\n + Files.FILENAME + \"=?\", new String[]{name, filename});\n }\n\n\tprivate long removeFileOrgDataNodes(ContentResolver resolver) {\n\t\tint total = 0;\n\t\ttry{\n\t\t\tresolver.delete(Timestamps.CONTENT_URI, Timestamps.FILE_ID + \"=?\",\n\t\t\t\t\tnew String[]{Long.toString(id)});\n\n\t\t\ttotal += resolver.delete(OrgData.CONTENT_URI, OrgData.FILE_ID + \"=?\",\n\t\t\t\t\tnew String[]{Long.toString(id)});\n\t\t\ttotal += resolver.delete(OrgData.buildIdUri(nodeId), null, null);\n\t\t} catch (IllegalArgumentException e){\n\t\t\t// DB does not exist. No need to delete.\n\t\t}\n\n//\t\tLog.v(\"sync\",\"remove all nodes : \"+total);\n\t\treturn total;\n\t}\n\n\tpublic boolean isEncrypted() {\n\t\treturn filename.endsWith(\".gpg\") || filename.endsWith(\".pgp\")\n\t\t\t\t|| filename.endsWith(\".enc\") || filename.endsWith(\".asc\");\n\t}\n\n\tpublic boolean equals(OrgFile file) {\n\t\treturn filename.equals(file.filename) && name.equals(file.name);\n }\n\n /**\n * @return the absolute filename\n */\n public String getFilePath(Context context) {\n\t\treturn Synchronizer.getInstance().getAbsoluteFilesDir(context) + \"/\" + filename;\n\t}\n\n\t/**\n\t * Query the state of the file (conflicted or not)\n\t * @return\n */\n\tpublic State getState(){\n\t\treturn comment.equals(\"conflict\") ? State.kConflict : State.kOK;\n\t}\n\n\tpublic String toString(ContentResolver resolver) {\n\t\tString result = \"\";\n\t\tOrgNode root = null;\n\t\ttry {\n\t\t\troot = new OrgNode(nodeId, resolver);\n\t\t\tOrgNodeTree tree = new OrgNodeTree(root, resolver);\n\t\t\tArrayList<OrgNode> res = OrgNodeTree.getFullNodeArray(tree, true);\n\t\t\tfor (OrgNode node : res) {\n//\t\t\t\tLog.v(\"content\", \"content\");\n//\t\t\t\tLog.v(\"content\", node.toString());\n\t\t\t\tresult += FileUtils.stripLastNewLine(node.toString()) + \"\\n\";\n\t\t\t}\n\t\t} catch (OrgNodeNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn result;\n\t}\n\n\n\tpublic enum State {\n\t\tkOK,\n\t\tkConflict\n\t}\n}", "public class OrgNode {\n\n\tpublic long id = -1;\n\tpublic long parentId = -1;\n\tpublic long fileId = -1;\n\n\tpublic long level = 0; // The headline level\n\tpublic String priority = \"\"; // The priority tag\n\tpublic String todo = \"\"; // The TODO state\n\tpublic String tags = \"\";\n\tpublic String tags_inherited = \"\";\n\tpublic String name = \"\";\n // The ordering of the same level siblings\n public int position = 0;\n\tOrgNodeTimeDate deadline, scheduled;\n\t// The payload is a string containing the raw string corresponding to this mode\n private String payload = \"\";\n private OrgNodePayload orgNodePayload = null;\n\n\tpublic OrgNode() {\n\t\tscheduled = new OrgNodeTimeDate(OrgNodeTimeDate.TYPE.Scheduled);\n\t\tdeadline = new OrgNodeTimeDate(OrgNodeTimeDate.TYPE.Deadline);\n\t}\n\t\n\tpublic OrgNode(OrgNode node) {\n\t\tthis.level = node.level;\n\t\tthis.priority = node.priority;\n\t\tthis.todo = node.todo;\n\t\tthis.tags = node.tags;\n\t\tthis.tags_inherited = node.tags_inherited;\n\t\tthis.name = node.name;\n this.position = node.position;\n this.scheduled = node.scheduled;\n this.deadline = node.deadline;\n\t\tsetPayload(node.getPayload());\n\t}\n\t\n\tpublic OrgNode(long id, ContentResolver resolver) throws OrgNodeNotFoundException {\n\t\tCursor cursor = resolver.query(OrgData.buildIdUri(id),\n\t\t\t\tOrgData.DEFAULT_COLUMNS, null, null, null);\n\t\tif(cursor == null)\n throw new OrgNodeNotFoundException(\"Node with id \\\"\" + id + \"\\\" not found\");\n\n if(!cursor.moveToFirst()){\n cursor.close();\n throw new OrgNodeNotFoundException(\"Node with id \\\"\" + id + \"\\\" not found\");\n }\n\t\tset(cursor);\n\n cursor.close();\n\t}\n\n\tpublic OrgNode(Cursor cursor) throws OrgNodeNotFoundException {\n\t\tset(cursor);\n\t}\n\n public static boolean hasChildren(long node_id, ContentResolver resolver) {\n try {\n OrgNode node = new OrgNode(node_id, resolver);\n return node.hasChildren(resolver);\n } catch (OrgNodeNotFoundException e) {\n }\n\n return false;\n }\n\n\tvoid setTimestamps() {\n\t\tdeadline = new OrgNodeTimeDate(OrgNodeTimeDate.TYPE.Deadline, id);\n\t\tscheduled = new OrgNodeTimeDate(OrgNodeTimeDate.TYPE.Scheduled, id);\n\t}\n\n public void set(Cursor cursor) throws OrgNodeNotFoundException {\n if (cursor != null && cursor.getCount() > 0) {\n\t\t\tif(cursor.isBeforeFirst() || cursor.isAfterLast())\n\t\t\t\tcursor.moveToFirst();\n\t\t\tid = cursor.getLong(cursor.getColumnIndexOrThrow(OrgData.ID));\n\t\t\tparentId = cursor.getLong(cursor\n .getColumnIndexOrThrow(OrgData.PARENT_ID));\n\t\t\tfileId = cursor.getLong(cursor\n .getColumnIndexOrThrow(OrgData.FILE_ID));\n\t\t\tlevel = cursor.getLong(cursor.getColumnIndexOrThrow(OrgData.LEVEL));\n\t\t\tpriority = cursor.getString(cursor\n .getColumnIndexOrThrow(OrgData.PRIORITY));\n\t\t\ttodo = cursor.getString(cursor.getColumnIndexOrThrow(OrgData.TODO));\n\t\t\ttags = cursor.getString(cursor.getColumnIndexOrThrow(OrgData.TAGS));\n\t\t\ttags_inherited = cursor.getString(cursor\n\t\t\t\t\t.getColumnIndexOrThrow(OrgData.TAGS_INHERITED));\n\t\t\tname = cursor.getString(cursor.getColumnIndexOrThrow(OrgData.NAME));\n\t\t\tpayload = cursor.getString(cursor\n\t\t\t\t\t.getColumnIndexOrThrow(OrgData.PAYLOAD));\n position = cursor.getInt(cursor\n .getColumnIndexOrThrow(OrgData.POSITION));\n\n\t\t} else {\n\t\t\tthrow new OrgNodeNotFoundException(\n\t\t\t\t\t\"Failed to create OrgNode from cursor\");\n\t\t}\n\t\tsetTimestamps();\n\t}\n\t\n\tpublic String getFilename(ContentResolver resolver) {\n\t\ttry {\n\t\t\tOrgFile file = new OrgFile(fileId, resolver);\n\t\t\treturn file.filename;\n\t\t} catch (OrgFileNotFoundException e) {\n\t\t\treturn \"\";\n\t\t}\n\t}\n\t\n\tpublic OrgFile getOrgFile(ContentResolver resolver) throws OrgFileNotFoundException {\n\t\treturn new OrgFile(fileId, resolver);\n\t}\n\t\n\tpublic void setFilename(String filename, ContentResolver resolver) throws OrgFileNotFoundException {\n\t\tOrgFile file = new OrgFile(filename, resolver);\n\t\tthis.fileId = file.nodeId;\n\t}\n\t\n\tprivate void preparePayload() {\n\t\tif(this.orgNodePayload == null)\n\t\t\tthis.orgNodePayload = new OrgNodePayload(this.payload);\n\t}\n\n\tpublic void write(Context context) {\n\t\tif(id < 0)\n\t\t\taddNode(context);\n\t\telse\n\t\t\tupdateNode(context);\n\t}\n\n /**\n * Generate the family tree with all descendants nodes and starting at the current one\n * @return the ArrayList<OrgNode> containing all nodes\n */\n public ArrayList<OrgNode> getDescandants(ContentResolver resolver){\n ArrayList<OrgNode> result = new ArrayList<OrgNode>();\n result.add(this);\n for(OrgNode child: getChildren(resolver)) result.addAll(child.getDescandants(resolver));\n return result;\n }\n\n\tprivate int updateNode(Context context) {\n\t\tif(scheduled != null){\n\t\t\tscheduled.update(context, id, fileId);\n\t\t}\n if(deadline != null){\n\t\t\tdeadline.update(context, id, fileId);\n\t\t}\n\t\treturn context.getContentResolver().update(OrgData.buildIdUri(id), getContentValues(), null, null);\n\t}\n\n public boolean isHabit() {\n\t\tpreparePayload();\n\t\treturn orgNodePayload.getProperty(\"STYLE\").equals(\"habit\");\n\t}\n\t\n\tprivate ContentValues getContentValues() {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(OrgData.NAME, name);\n\t\tvalues.put(OrgData.TODO, todo);\n\t\tvalues.put(OrgData.FILE_ID, fileId);\n\t\tvalues.put(OrgData.LEVEL, level);\n\t\tvalues.put(OrgData.PARENT_ID, parentId);\n\t\tvalues.put(OrgData.PAYLOAD, payload);\n\t\tvalues.put(OrgData.PRIORITY, priority);\n\t\tvalues.put(OrgData.TAGS, tags);\n values.put(OrgData.TAGS_INHERITED, tags_inherited);\n values.put(OrgData.POSITION, position);\n\t\treturn values;\n\t}\n\t\n\t/**\n\t * This will split up the tag string that it got from the tag entry in the\n\t * database. The leading and trailing : are stripped out from the tags by\n\t * the parser. A double colon (::) means that the tags before it are\n\t * inherited.\n\t */\n\tpublic ArrayList<String> getTags() {\n\t\tArrayList<String> result = new ArrayList<String>();\n\n\t\tif(tags == null)\n\t\t\treturn result;\n\n String[] split = tags.split(\"\\\\:\");\n\n\t\tfor (String tag : split)\n\t\t\tresult.add(tag);\n\n\t\tif (tags.endsWith(\":\"))\n\t\t\tresult.add(\"\");\n\n\t\treturn result;\n\t}\n\t\n\tpublic ArrayList<OrgNode> getChildren(ContentResolver resolver) {\n\t\treturn OrgProviderUtils.getOrgNodeChildren(id, resolver);\n\t}\n\t\n\tpublic ArrayList<String> getChildrenStringArray(ContentResolver resolver) {\n\t\tArrayList<String> result = new ArrayList<String>();\n\t\tArrayList<OrgNode> children = getChildren(resolver);\n\n\t\tfor (OrgNode node : children)\n\t\t\tresult.add(node.name);\n\n\t\treturn result;\n\t}\n\t\n\tpublic OrgNode getChild(String name, ContentResolver resolver) throws OrgNodeNotFoundException {\n ArrayList<OrgNode> children = getChildren(resolver);\n\n for(OrgNode child: children) {\n\t\t\tif(child.name.equals(name))\n\t\t\t\treturn child;\n\t\t}\n\t\tthrow new OrgNodeNotFoundException(\"Couln't find child of node \"\n\t\t\t\t+ this.name + \" with name \" + name);\n\t}\n\t\n\tpublic boolean hasChildren(ContentResolver resolver) {\n\t\tCursor childCursor = resolver.query(OrgData.buildChildrenUri(id),\n OrgData.DEFAULT_COLUMNS, null, null, null);\n\n int childCount = childCursor.getCount();\n\t\tchildCursor.close();\n\n\t\treturn childCount > 0;\n\t}\n\t\n\tpublic OrgNode getParent(ContentResolver resolver) throws OrgNodeNotFoundException {\n\t\tCursor cursor = resolver.query(OrgData.buildIdUri(this.parentId),\n\t\t\t\tOrgData.DEFAULT_COLUMNS, null, null, null);\n OrgNode parent = new OrgNode(cursor);\n if(cursor!=null) cursor.close();\n\t\treturn parent;\n\t}\n\n\n\tpublic ArrayList<String> getSiblingsStringArray(ContentResolver resolver) {\n\t\ttry {\n\t\t\tOrgNode parent = getParent(resolver);\n\t\t\treturn parent.getChildrenStringArray(resolver);\n\t\t}\n\t\tcatch (OrgNodeNotFoundException e) {\n\t\t\tthrow new IllegalArgumentException(\"Couldn't get parent for node \" + name);\n\t\t}\n\t}\n\n\tpublic ArrayList<OrgNode> getSiblings(ContentResolver resolver) {\n try {\n OrgNode parent = getParent(resolver);\n return parent.getChildren(resolver);\n } catch (OrgNodeNotFoundException e) {\n\t\t\tthrow new IllegalArgumentException(\"Couldn't get parent for node \" + name);\n\t\t}\n\t}\n\n\tpublic void shiftNextSiblingNodes(Context context) {\n\t\tfor (OrgNode sibling : getSiblings(context.getContentResolver())) {\n\t\t\tif(sibling.position >= position && sibling.id != this.id) {\n ++sibling.position;\n\t\t\t\tsibling.updateNode(context);\n//\t\t\t\tLog.v(\"position\", \"new pos : \" + sibling.position);\n }\n }\n }\n\n\tpublic boolean isFilenode(ContentResolver resolver) {\n\t\ttry {\n\t\t\tOrgFile file = new OrgFile(fileId, resolver);\n\t\t\tif(file.nodeId == this.id)\n\t\t\t\treturn true;\n\t\t} catch (OrgFileNotFoundException e) {}\n\t\t\n\t\treturn false;\n\t}\n\t\n\n\n\tpublic String getCleanedName() {\n\t\treturn this.name;\n\t}\n\n\t\n\t/**\n\t * @return The :ID:, :ORIGINAL_ID: or olp link of node.\n\t */\n\tpublic String getNodeId(ContentResolver resolver) {\n\t\tpreparePayload();\n\n\t\tString id = orgNodePayload.getId();\t\t\t\t\n\t\tif(id != null && id.equals(\"\") == false)\n\t\t\treturn id;\n\t\telse\n\t\t\treturn getOlpId(resolver);\n\t}\n\t\n\tpublic String getOlpId(ContentResolver resolver) {\n\t\tStringBuilder result = new StringBuilder();\n\t\t\n\t\tArrayList<OrgNode> nodesFromRoot;\n\t\ttry {\n\t\t\tnodesFromRoot = OrgProviderUtils.getOrgNodePathFromTopLevel(\n\t\t\t\t\tparentId, resolver);\n\t\t} catch (IllegalStateException e) {\n\t\t\treturn \"\";\n\t\t}\n\t\t\n\t\tif (nodesFromRoot.size() == 0) {\n\t\t\ttry {\n\t\t\t\treturn \"olp:\" + getOrgFile(resolver).name;\n\t\t\t} catch (OrgFileNotFoundException e) {\n\t\t\t\treturn \"\";\n\t\t\t}\n\t\t}\n\t\t\t\n\t\tOrgNode topNode = nodesFromRoot.get(0);\n\t\tnodesFromRoot.remove(0);\n\t\tresult.append(\"olp:\" + topNode.getFilename(resolver) + \":\");\n\t\t\n\t\tfor(OrgNode node: nodesFromRoot)\n\t\t\tresult.append(node.getStrippedNameForOlpPathLink() + \"/\");\n\t\t\n\t\tresult.append(getStrippedNameForOlpPathLink());\n\t\treturn result.toString();\n\t}\n\n public OrgNodeTimeDate getDeadline() {\n return deadline;\n }\n\n public OrgNodeTimeDate getScheduled() {\n return scheduled;\n }\n\n\t/**\n\t * if scheduled and deadline are defined returns the number of seconds between them\n\t * else return -1\n\t */\n\tpublic long getRangeInSec(){\n\t\tlong scheduled = this.scheduled.getEpochTime();\n\t\tif(scheduled < 0) return -1;\n\t\tlong deadline = this.deadline.getEpochTime();\n\t\tif(deadline < 0) return -1;\n\t\treturn Math.abs(deadline-scheduled);\n\t}\n\n /**\n\t * Olp paths containing certain symbols can't be applied by org-mode. To\n\t * prevent node names from injecting bad symbols, we strip them out here.\n\t */\n\n\tprivate String getStrippedNameForOlpPathLink() {\n\t\tString result = this.name;\n\t\tresult = result.replaceAll(\"\\\\[[^\\\\]]*\\\\]\", \"\"); // Strip out \"[*]\"\n\t\treturn result;\n\t}\n\t\n\t\n\tpublic String getCleanedPayload() {\n\t\tpreparePayload();\n\t\treturn this.orgNodePayload.getCleanedPayload();\n\t}\n\t\n\tpublic String getPayload() {\n preparePayload();\n\t\treturn this.orgNodePayload.get();\n\t}\n\n public void setPayload(String payload) {\n this.orgNodePayload = null;\n this.payload = payload;\n }\n\n public HashMap getPropertiesPayload() {\n preparePayload();\n return this.orgNodePayload.getPropertiesPayload();\n }\n\n public void addDate(OrgNodeTimeDate date){\n//\t\tLog.v(\"timestamp\", \"adding date : \" + date.getEpochTime() + \" type : \" + date.type);\n\t\tthis.orgNodePayload.insertOrReplaceDate(date);\n switch (date.type){\n case Deadline:\n deadline = date;\n break;\n case Scheduled:\n scheduled = date;\n break;\n }\n return;\n }\n\t\n\tpublic OrgNodePayload getOrgNodePayload() {\n\t\tpreparePayload();\n\t\treturn this.orgNodePayload;\n\t}\n\n\t/**\n\t * Build the the plain text string corresponding to this node\n\t * @return the node in plain text\n */\n\tpublic String toString() {\n\t\tStringBuilder result = new StringBuilder();\n\t\t\n\t\tfor(int i = 0; i < level; i++)\n\t\t\tresult.append(\"*\");\n\t\tresult.append(\" \");\n\n\t\tif (!TextUtils.isEmpty(todo))\n\t\t\tresult.append(todo + \" \");\n\n\t\tif (!TextUtils.isEmpty(priority))\n\t\t\tresult.append(\"[#\" + priority + \"] \");\n\n\t\tresult.append(name);\n\t\t\n\t\tif(tags != null && !TextUtils.isEmpty(tags))\n\t\t\tresult.append(\" \").append(\":\" + tags + \":\");\n\t\t\n\n\t\tif (payload != null && !TextUtils.isEmpty(payload)){\n\t\t\tresult.append(\"\\n\");\n\t\t\tif(level > 0) for(int i = 0;i<level+1; i++) result.append(\" \");\n\t\t\tresult.append(payload.trim());\n\t\t}\n\n\t\treturn result.toString();\n\t}\n\n\n\n\tpublic boolean equals(OrgNode node) {\n\t\treturn name.equals(node.name) && tags.equals(node.tags)\n\t\t\t\t&& priority.equals(node.priority) && todo.equals(node.todo)\n\t\t\t\t&& payload.equals(node.payload);\n\t}\n\n\t/**\n\t * Delete this node and rewrite the file on disk\n\t *\n\t * @param context\n\t */\n\tpublic void deleteNode(Context context) {\n\t\tcontext.getContentResolver().delete(OrgData.buildIdUri(id), null, null);\n\t\tOrgFile.updateFile(this, context);\n\t}\n\n\t/**\n\t * Add this node and rewrite the file on disk\n\t *\n\t * @param context\n\t * @return\n\t */\n\tprivate long addNode(Context context) {\n\n\t\tUri uri = context.getContentResolver().insert(OrgData.CONTENT_URI, getContentValues());\n\t\tthis.id = Long.parseLong(OrgData.getId(uri));\n\t\tif (scheduled != null) {\n\t\t\tscheduled.update(context, id, fileId);\n\t\t}\n\t\tif (deadline != null) {\n\t\t\tdeadline.update(context, id, fileId);\n\t\t}\n\t\tOrgFile.updateFile(this, context);\n\t\treturn id;\n\t}\n\n\tpublic void addAutomaticTimestamp() {\n\t\tContext context = MobileOrgApplication.getContext();\n\t\tboolean addTimestamp = PreferenceManager.getDefaultSharedPreferences(\n\t\t\t\tcontext).getBoolean(\"captureWithTimestamp\", false);\n\t\tif(addTimestamp)\n\t\t\tsetPayload(getPayload() + OrgUtils.getTimestamp());\n\t}\n}", "public class OrgProviderUtils {\n\n\t/**\n\t *\n\t * @param context\n\t * @return the list of nodes corresponding to a file\n\t */\n\tpublic static List<OrgNode> getFileNodes(Context context){\n return OrgProviderUtils.getOrgNodeChildren(-1, context.getContentResolver());\n }\n\n\n\tpublic static ArrayList<String> getFilenames(ContentResolver resolver) {\n\t\tArrayList<String> result = new ArrayList<String>();\n\n\t\tCursor cursor = resolver.query(Files.CONTENT_URI, Files.DEFAULT_COLUMNS,\n\t\t\t\tnull, null, Files.DEFAULT_SORT);\n\t\tcursor.moveToFirst();\n\n\t\twhile (!cursor.isAfterLast()) {\n\t\t\tOrgFile orgFile = new OrgFile();\n\t\t\t\n\t\t\ttry {\n\t\t\t\torgFile.set(cursor);\n\t\t\t\tresult.add(orgFile.filename);\n\t\t\t} catch (OrgFileNotFoundException e) {}\n\t\t\tcursor.moveToNext();\n\t\t}\n\n\t\tcursor.close();\n\t\treturn result;\n\t}\n\n\n\t/**\n\t * Query the DB for the list of files\n\t * @param resolver\n * @return\n */\n\tpublic static ArrayList<OrgFile> getFiles(ContentResolver resolver) {\n\t\tArrayList<OrgFile> result = new ArrayList<>();\n\n\t\tCursor cursor = resolver.query(Files.CONTENT_URI, Files.DEFAULT_COLUMNS,\n\t\t\t\tnull, null, Files.DEFAULT_SORT);\n\t\tif(cursor == null) return result;\n\t\tcursor.moveToFirst();\n\n\t\twhile (!cursor.isAfterLast()) {\n\t\t\tOrgFile orgFile = new OrgFile();\n\n\t\t\ttry {\n\t\t\t\torgFile.set(cursor);\n\t\t\t\tresult.add(orgFile);\n\t\t\t} catch (OrgFileNotFoundException e) {}\n\t\t\tcursor.moveToNext();\n\t\t}\n\n\t\tcursor.close();\n\t\treturn result;\n\t}\n\n\tpublic static String getNonNullString(Cursor cursor, int index){\n\t\tString result = cursor.getString(index);\n\t\treturn result!=null ? result : \"\";\n\t}\n\n\n\tpublic static void addTodos(HashMap<String, Boolean> todos,\n\t\t\t\t\t\t\t\tContentResolver resolver) {\n\t\tif(todos == null) return;\n\t\tfor (String name : todos.keySet()) {\n\t\t\tContentValues values = new ContentValues();\n\t\t\tvalues.put(Todos.NAME, name);\n\t\t\tvalues.put(Todos.GROUP, 0);\n\n\t\t\tif (todos.get(name))\n\t\t\t\tvalues.put(Todos.ISDONE, 1);\n\n\t\t\ttry{\n\t\t\t\tresolver.insert(Todos.CONTENT_URI, values);\n\t\t\t} catch (Exception e){\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t}\n\tpublic static ArrayList<String> getTodos(ContentResolver resolver) {\n\t\tCursor cursor = resolver.query(Todos.CONTENT_URI, new String[] { Todos.NAME }, null, null, Todos.ID);\n\t\tif(cursor==null) return new ArrayList<>();\n\n\t\tArrayList<String> todos = cursorToArrayList(cursor);\n\n\t\treturn todos;\n\t}\n\t\n\tpublic static void setPriorities(ArrayList<String> priorities, ContentResolver resolver) {\n\t\tresolver.delete(Priorities.CONTENT_URI, null, null);\n\n\t\tfor (String priority : priorities) {\n\t\t\tContentValues values = new ContentValues();\n\t\t\tvalues.put(Priorities.NAME, priority);\n\t\t\tresolver.insert(Priorities.CONTENT_URI, values);\n\t\t}\n\t}\n\n\tpublic static ArrayList<String> getPriorities(ContentResolver resolver) {\n\t\tCursor cursor = resolver.query(Priorities.CONTENT_URI, new String[] { Priorities.NAME },\n\t\t\t\tnull, null, Priorities.ID);\n\t\tArrayList<String> priorities = cursorToArrayList(cursor);\n\n\t\tcursor.close();\n\t\treturn priorities;\n\t}\n\t\n\n\tpublic static void setTags(ArrayList<String> priorities, ContentResolver resolver) {\n\t\tresolver.delete(Tags.CONTENT_URI, null, null);\n\n\t\tfor (String priority : priorities) {\n\t\t\tContentValues values = new ContentValues();\n\t\t\tvalues.put(Tags.NAME, priority);\n\t\t\tresolver.insert(Tags.CONTENT_URI, values);\n\t\t}\n\t}\n\tpublic static ArrayList<String> getTags(ContentResolver resolver) {\n\t\tCursor cursor = resolver.query(Tags.CONTENT_URI, new String[] { Tags.NAME },\n\t\t\t\tnull, null, Tags.ID);\n\t\tArrayList<String> tags = cursorToArrayList(cursor);\n\n\t\tcursor.close();\n\t\treturn tags;\n\t}\n\n\tpublic static ArrayList<String> cursorToArrayList(Cursor cursor) {\n\t\tArrayList<String> list = new ArrayList<>();\n\t\tif(cursor == null) return list;\n\t\tcursor.moveToFirst();\n\n\t\twhile (!cursor.isAfterLast()) {\n\t\t\tlist.add(cursor.getString(0));\n\t\t\tcursor.moveToNext();\n\t\t}\n\t\treturn list;\n\t}\n\n\tpublic static ArrayList<OrgNode> getOrgNodePathFromTopLevel(long node_id, ContentResolver resolver) {\n\t\tArrayList<OrgNode> nodes = new ArrayList<OrgNode>();\n\t\t\n\t\tlong currentId = node_id;\n\t\twhile(currentId >= 0) {\n\t\t\ttry {\n\t\t\t\tOrgNode node = new OrgNode(currentId, resolver);\n\t\t\t\tnodes.add(node);\n\t\t\t\tcurrentId = node.parentId;\n\t\t\t} catch (OrgNodeNotFoundException e) {\n\t\t\t\tthrow new IllegalStateException(\"Couldn't build entire path to root from a given node\");\n\t\t\t}\n\t\t}\n\t\t\n\t\tCollections.reverse(nodes);\n\t\treturn nodes;\n\t}\n\n\n\tpublic static void clearDB(ContentResolver resolver) {\n\t\tresolver.delete(OrgData.CONTENT_URI, null, null);\n\t\tresolver.delete(Files.CONTENT_URI, null, null);\n\t\tresolver.delete(Timestamps.CONTENT_URI, null, null);\n\t}\n\t\n\tpublic static boolean isTodoActive(String todo, ContentResolver resolver) {\n\t\tif(TextUtils.isEmpty(todo))\n\t\t\treturn true;\n\n\t\tCursor cursor = resolver.query(Todos.CONTENT_URI, Todos.DEFAULT_COLUMNS, Todos.NAME + \" = ?\",\n\t\t\t\tnew String[] { todo }, null);\t\t\n\t\t\n\t\tif(cursor.getCount() > 0) {\n\t\t\tcursor.moveToFirst();\n\t\t\tint isdone = cursor.getInt(cursor.getColumnIndex(Todos.ISDONE));\n\t\t\tcursor.close();\n\n\t\t\treturn isdone == 0;\n\t\t}\n\n\t\tif(cursor!=null) cursor.close();\n\n\t\treturn false;\n\t}\n\t\n\tpublic static Cursor search(String query, ContentResolver resolver) {\n\t\tCursor cursor = resolver.query(OrgData.CONTENT_URI, OrgData.DEFAULT_COLUMNS,\n\t\t\t\tOrgData.NAME + \" LIKE ?\", new String[] { query },\n\t\t\t\tOrgData.DEFAULT_SORT);\n\t\t\n\t\treturn cursor;\n\t}\n\n\tpublic static ArrayList<OrgNode> getOrgNodeChildren(long nodeId, ContentResolver resolver) {\n\t\t\n\t\tString sort = nodeId == -1 ? OrgData.NAME_SORT : OrgData.POSITION_SORT;\n//\t\tLog.v(\"sort\", \"sort : \" + sort);\n\t\tCursor childCursor = resolver.query(OrgData.buildChildrenUri(nodeId),\n\t\t\t\tOrgData.DEFAULT_COLUMNS, null, null, sort);\n\n\t\tif(childCursor!=null) {\n\t\t\tArrayList<OrgNode> result = orgDataCursorToArrayList(childCursor);\n\t\t\tchildCursor.close();\n\t\t\treturn result;\n\t\t}else{\n\t\t\treturn new ArrayList<OrgNode>();\n\t\t}\n\t}\n\t\n\tpublic static ArrayList<OrgNode> orgDataCursorToArrayList(Cursor cursor) {\n\t\tArrayList<OrgNode> result = new ArrayList<OrgNode>();\n\n\t\tcursor.moveToFirst();\n\t\t\n\t\twhile(cursor.isAfterLast() == false) {\n\t\t\ttry {\n\t\t\t\tresult.add(new OrgNode(cursor));\n\t\t\t} catch (OrgNodeNotFoundException e) {}\n\t\t\tcursor.moveToNext();\n\t\t}\n\t\t\n\t\treturn result;\n\t}\n}", "public class OrgNodeDetailActivity extends AppCompatActivity {\n\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_orgnode_detail);\n Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);\n setSupportActionBar(toolbar);\n\n // Show the Up button in the action bar.\n ActionBar actionBar = getSupportActionBar();\n if (actionBar != null) {\n actionBar.setDisplayHomeAsUpEnabled(true);\n }\n\n // savedInstanceState is non-null when there is fragment state\n // saved from previous configurations of this activity\n // (e.g. when rotating the screen from portrait to landscape).\n // In this case, the fragment will automatically be re-added\n // to its container so we don't need to manually add it.\n // For more information, see the Fragments API guide at:\n //\n // http://developer.android.com/guide/components/fragments.html\n //\n if (savedInstanceState == null) {\n // Create the detail fragment and add it to the activity\n // using a fragment transaction.\n Bundle arguments = new Bundle();\n Long nodeId = getIntent().getLongExtra(OrgContract.NODE_ID, -1);\n\n arguments.putLong(OrgContract.NODE_ID, nodeId);\n arguments.putLong(OrgContract.POSITION, getIntent().getLongExtra(OrgContract.POSITION, -1));\n Fragment fragment;\n\n if(nodeId == OrgContract.AGENDA_ID) fragment = new AgendaFragment();\n else fragment = new OrgNodeDetailFragment();\n\n fragment.setArguments(arguments);\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.orgnode_detail_container, fragment, \"detail_fragment\")\n .commit();\n\n if(actionBar != null) {\n if(nodeId == OrgContract.TODO_ID) actionBar.setTitle(getResources().getString(R.string.menu_todos));\n else if (nodeId == OrgContract.AGENDA_ID){\n actionBar.setTitle(getResources().getString(R.string.menu_agenda));\n } else {\n try {\n OrgNode node = new OrgNode(nodeId, getContentResolver());\n actionBar.setTitle(node.name);\n } catch (OrgNodeNotFoundException e) {\n e.printStackTrace();\n }\n }\n }\n }\n }\n\n @Override\n public void onBackPressed()\n {\n // Writing changes currently done in the fragment EditNodeFragment if any\n EditNodeFragment fragment = (EditNodeFragment) getSupportFragmentManager().findFragmentByTag(\"edit_node_fragment\");\n if(fragment != null){\n fragment.onOKPressed();\n }\n\n // code here to show dialog\n super.onBackPressed(); // optional depending on your needs\n }\n\n//\n// @Override\n// public boolean onCreateOptionsMenu(Menu menu) {\n// MenuInflater inflater = getMenuInflater();\n// inflater.inflate(R.menu.detail_menu, menu);\n//\n// return true;\n// }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case android.R.id.home:\n // This ID represents the Home or Up button. In the case of this\n // activity, the Up button is shown. Use NavUtils to allow users\n // to navigate up one level in the application structure. For\n // more details, see the Navigation pattern on Android Design:\n //\n // http://developer.android.com/design/patterns/navigation.html#up-vs-back\n //\n NavUtils.navigateUpTo(this, new Intent(this, OrgNodeListActivity.class));\n return true;\n\n// case R.id.delete_node_button:\n// OrgNodeDetailFragment fragment = (OrgNodeDetailFragment) getSupportFragmentManager().findFragmentByTag(\"detail_fragment\");\n// if(fragment != null){\n// }\n// return true;\n }\n// return super.onOptionsItemSelected(item);\n return false;\n }\n\n\n\n\n}", "public class OrgNodeDetailFragment extends Fragment {\n\n MainRecyclerViewAdapter adapter;\n Button insertNodeButton;\n RecyclerView recyclerView;\n TextView insertNodeText;\n private ContentResolver resolver;\n private long nodeId;\n private OrgNode selectedNode;\n private View highlightedView = null;\n private ActionMode mActionMode = null;\n private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {\n\n // Called when the action mode is created; startActionMode() was called\n @Override\n public boolean onCreateActionMode(ActionMode mode, Menu menu) {\n // Inflate a menu resource providing context menu items\n MenuInflater inflater = mode.getMenuInflater();\n inflater.inflate(R.menu.agenda_entry, menu);\n return true;\n }\n\n // Called each time the action mode is shown. Always called after onCreateActionMode, but\n // may be called multiple times if the mode is invalidated.\n @Override\n public boolean onPrepareActionMode(ActionMode mode, Menu menu) {\n return false; // Return false if nothing is done\n }\n\n // Called when the user selects a contextual menu item\n @Override\n public boolean onActionItemClicked(ActionMode mode, MenuItem item) {\n switch (item.getItemId()) {\n case R.id.agenda_entry_cancel:\n// shareCurrentItem();\n mode.finish(); // Action picked, so close the CAB\n return true;\n default:\n return false;\n }\n }\n\n // Called when the user exits the action mode\n @Override\n public void onDestroyActionMode(ActionMode mode) {\n mActionMode = null;\n }\n };\n\n /**\n * Mandatory empty constructor for the fragment manager to instantiate the\n * fragment (e.g. upon screen orientation changes).\n */\n public OrgNodeDetailFragment() {\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n this.resolver = getActivity().getContentResolver();\n\n OrgNodeTree tree = null;\n\n if (getArguments().containsKey(OrgContract.NODE_ID)) {\n Bundle arguments = getArguments();\n this.nodeId = arguments.getLong(OrgContract.NODE_ID);\n\n\n }\n\n adapter = new MainRecyclerViewAdapter();\n\n }\n\n private OrgNodeTree getTree(){\n // Handling of the TODO file\n if (nodeId == OrgContract.TODO_ID) {\n// Cursor cursor = resolver.query(OrgContract.OrgData.CONTENT_URI,\n// OrgContract.OrgData.DEFAULT_COLUMNS, OrgContract.Todos.ISDONE + \"=1\",\n// null, OrgContract.OrgData.NAME_SORT);\n\n String todoQuery = \"SELECT \" +\n OrgContract.formatColumns(\n OrgDatabase.Tables.ORGDATA,\n OrgContract.OrgData.DEFAULT_COLUMNS) +\n \" FROM orgdata JOIN todos \" +\n \" ON todos.name = orgdata.todo WHERE todos.isdone=0\";\n\n\n Cursor cursor = OrgDatabase.getInstance().getReadableDatabase().rawQuery(todoQuery, null);\n\n OrgNodeTree tree = new OrgNodeTree(OrgProviderUtils.orgDataCursorToArrayList(cursor));\n if(cursor != null) cursor.close();\n return tree;\n } else {\n try {\n return new OrgNodeTree(new OrgNode(nodeId, resolver), resolver);\n } catch (OrgNodeNotFoundException e) {\n// TODO: implement error\n e.printStackTrace();\n }\n }\n return null;\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n View rootView = inflater.inflate(R.layout.node_summary_recycler_fragment, container, false);\n\n\n recyclerView = (RecyclerView) rootView.findViewById(R.id.node_recycler_view);\n assert recyclerView != null;\n// recyclerView.addItemDecoration(new DividerItemDecoration(getContext()));\n\n recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));\n recyclerView.setAdapter(adapter);\n\n insertNodeButton = (Button) rootView.findViewById(R.id.empty_recycler);\n insertNodeText = (TextView) rootView.findViewById(R.id.empty_recycler_text);\n\n insertNodeButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n EditNodeFragment.createEditNodeFragment(\n -1,\n (int) OrgNodeDetailFragment.this.nodeId,\n 0,\n getContext());\n }\n });\n\n refresh();\n\n int position = findCardViewContaining(getArguments().getLong(OrgContract.POSITION, -1));\n recyclerView.scrollToPosition(position);\n return rootView;\n }\n\n /**\n * Recreate the OrgNodeTree and refresh the Adapter\n */\n public void refresh() {\n adapter.tree = getTree();\n\n int size = adapter.getItemCount();\n\n if (size == 0) {\n recyclerView.setVisibility(View.GONE);\n int textId = (nodeId != OrgContract.TODO_ID) ? R.string.no_node : R.string.no_todo;\n insertNodeButton.setVisibility((nodeId != OrgContract.TODO_ID) ? View.VISIBLE : View.INVISIBLE);\n insertNodeText.setText(textId);\n insertNodeText.setVisibility(View.VISIBLE);\n } else {\n insertNodeButton.setVisibility(View.GONE);\n insertNodeText.setVisibility(View.GONE);\n recyclerView.setVisibility(View.VISIBLE);\n }\n adapter.notifyDataSetChanged();\n }\n\n @Override\n public void onResume() {\n super.onResume();\n refresh();\n }\n\n\n\n /**\n * Find the CardView containing the given node id\n *\n * @param id\n * @return the position of the CardView\n */\n int findCardViewContaining(long id) {\n if (id < 0) return 0;\n OrgNode node = null;\n long cardViewMainNode = -1;\n try {\n do {\n if (node != null) cardViewMainNode = node.id;\n node = new OrgNode(id, getContext().getContentResolver());\n id = node.parentId;\n } while (id > -1);\n for (int i = 0; i < adapter.tree.children.size(); i++) {\n if (adapter.tree.children.get(i).node.id == cardViewMainNode) {\n return i;\n }\n }\n } catch (OrgNodeNotFoundException e) {\n e.printStackTrace();\n }\n return 0;\n }\n\n public class MainRecyclerViewAdapter\n extends RecyclerView.Adapter<MultipleItemsViewHolder> {\n\n private OrgNodeTree tree;\n\n public MainRecyclerViewAdapter() {\n }\n\n @Override\n public MultipleItemsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n View view = LayoutInflater.from(parent.getContext())\n .inflate(R.layout.detail_recycler_item, parent, false);\n return new MultipleItemsViewHolder(view);\n }\n\n @Override\n public void onBindViewHolder(final MultipleItemsViewHolder holder, final int position) {\n OrgNodeTree root = tree.children.get(position);\n\n SecondaryRecyclerViewAdapter secondaryAdapter = new SecondaryRecyclerViewAdapter(root, position);\n\n RecyclerView secondaryRecyclerView = (RecyclerView) holder.view.findViewById(R.id.node_recycler_view);\n secondaryRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));\n secondaryRecyclerView.setAdapter(secondaryAdapter);\n\n SimpleItemTouchHelperCallback callback = new SimpleItemTouchHelperCallback(secondaryAdapter);\n ItemTouchHelper touchHelper = new ItemTouchHelper(callback);\n touchHelper.attachToRecyclerView(secondaryRecyclerView);\n }\n\n @Override\n public int getItemCount() {\n return tree.children.size();\n }\n\n class SimpleItemTouchHelperCallback extends ItemTouchHelper.Callback {\n private final RecyclerView.Adapter mAdapter;\n\n public SimpleItemTouchHelperCallback(RecyclerView.Adapter adapter) {\n mAdapter = adapter;\n }\n\n @Override\n public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {\n int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;\n int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;\n return makeMovementFlags(dragFlags, swipeFlags);\n }\n\n\n @Override\n public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {\n long position = (long) viewHolder.getAdapterPosition();\n// OrgNode node = mAdapter.idTreeMap.get(position).node;\n// int id = (int)node.id;\n// int parentId = (int)node.parentId;\n\n OrgNodeViewHolder item = (OrgNodeViewHolder) viewHolder;\n EditNodeFragment.createEditNodeFragment((int)item.node.id, -1, -1, getContext());\n }\n\n @Override\n public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,\n RecyclerView.ViewHolder target) {\n return false;\n }\n }\n }\n\n public class SecondaryRecyclerViewAdapter\n extends RecyclerView.Adapter<OrgNodeViewHolder> {\n\n NavigableMap<Long, OrgNodeTree> items;\n private OrgNodeTree tree;\n private int parentPosition;\n\n public SecondaryRecyclerViewAdapter(OrgNodeTree root, int parentPosition) {\n tree = root;\n refreshVisibility();\n this.parentPosition = parentPosition;\n }\n\n void refreshVisibility() {\n items = tree.getVisibleNodesArray();\n notifyDataSetChanged();\n }\n\n @Override\n public OrgNodeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n View view = LayoutInflater.from(parent.getContext())\n .inflate(R.layout.subnode_layout, parent, false);\n return new OrgNodeViewHolder(view);\n }\n\n @Override\n public void onBindViewHolder(final OrgNodeViewHolder item, final int position) {\n final OrgNodeTree tree = items.get((long)position);\n\n boolean isSelected = (tree.node == selectedNode);\n item.setup(tree, isSelected, getContext());\n\n item.mView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (selectedNode != null) {\n closeInsertItem();\n } else {\n tree.toggleVisibility();\n }\n refreshVisibility();\n }\n });\n\n item.mView.setOnLongClickListener(new View.OnLongClickListener() {\n @Override\n public boolean onLongClick(View v) {\n// ((AppCompatActivity)getActivity()).startSupportActionMode(mActionModeCallback);\n\n if (highlightedView != null) {\n closeInsertItem();\n }\n\n selectedNode = item.node;\n highlightedView = item.mView;\n// setItemModifiersVisibility(highlightedView, View.VISIBLE);\n// item.mView.setSelected(true);\n\n// notifyItemChanged(position);\n// refreshVisibility();\n// adapter.notifyItemChanged(parentPosition, SecondaryRecyclerViewAdapter.this);\n adapter.notifyDataSetChanged();\n return true;\n }\n });\n\n item.todoButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (selectedNode != null) {\n closeInsertItem();\n refreshVisibility();\n return;\n }\n new TodoDialog(getContext(), tree.node, item.todoButton, true);\n refreshVisibility();\n }\n });\n\n\n item.sameLevel.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n OrgNode currentNode = item.node;\n int parentId = (int) currentNode.parentId;\n\n // Place the node right after this one in the adapter\n int siblingPosition = currentNode.position + 1;\n EditNodeFragment.createEditNodeFragment(-1, parentId, siblingPosition, getContext());\n }\n });\n\n item.childLevel.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n int parentId = (int) item.node.id;\n EditNodeFragment.createEditNodeFragment(-1, parentId, 0, getContext());\n }\n });\n\n item.deleteNodeButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n new AlertDialog.Builder(getActivity())\n .setMessage(R.string.prompt_node_delete)\n .setIcon(android.R.drawable.ic_dialog_alert)\n .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {\n\n public void onClick(DialogInterface dialog, int whichButton) {\n item.node.deleteNode(getContext());\n refresh();\n }\n })\n .setNegativeButton(android.R.string.no, null).show();\n }\n });\n }\n\n\n private void closeInsertItem() {\n selectedNode = null;\n if (highlightedView != null) {\n setItemModifiersVisibility(highlightedView, View.GONE);\n highlightedView = null;\n }\n }\n\n @Override\n public int getItemCount() {\n return items.size();\n }\n\n void setItemModifiersVisibility(View view, int visibility){\n LinearLayout itemModifiers = (LinearLayout) view.findViewById(R.id.item_modifiers);\n if (itemModifiers != null) {\n itemModifiers.setVisibility(visibility);\n }\n }\n }\n\n public class DividerItemDecoration extends RecyclerView.ItemDecoration {\n\n private final int[] ATTRS = new int[]{android.R.attr.listDivider};\n\n private Drawable mDivider;\n\n /**\n * Default divider will be used\n */\n public DividerItemDecoration(Context context) {\n final TypedArray styledAttributes = context.obtainStyledAttributes(ATTRS);\n mDivider = styledAttributes.getDrawable(0);\n styledAttributes.recycle();\n }\n\n /**\n * Custom divider will be used\n */\n public DividerItemDecoration(Context context, int resId) {\n mDivider = ContextCompat.getDrawable(context, resId);\n }\n\n @Override\n public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {\n int left = parent.getPaddingLeft();\n int right = parent.getWidth() - parent.getPaddingRight();\n\n int childCount = parent.getChildCount();\n for (int i = 0; i < childCount; i++) {\n View child = parent.getChildAt(i);\n\n RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();\n\n int top = child.getBottom() + params.bottomMargin;\n int bottom = top + mDivider.getIntrinsicHeight();\n\n mDivider.setBounds(left, top, right, bottom);\n mDivider.draw(c);\n }\n }\n }\n}", "public class OrgNodeListActivity extends AppCompatActivity {\n\n public final static String NODE_ID = \"node_id\";\n public final static String SYNC_FAILED = \"com.matburt.mobileorg.SYNC_FAILED\";\n static boolean passwordPrompt = true;\n /**\n * Whether or not the activity is in two-pane mode, i.e. running on a tablet\n * device.\n */\n\n private Long node_id;\n private SynchServiceReceiver syncReceiver;\n private MenuItem synchronizerMenuItem;\n private RecyclerView recyclerView;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_orgnode_list);\n\n Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);\n setSupportActionBar(toolbar);\n toolbar.setTitle(getTitle());\n\n Intent intent = getIntent();\n node_id = intent.getLongExtra(NODE_ID, -1);\n\n if (this.node_id == -1) displayNewUserDialogs();\n\n recyclerView = (RecyclerView) findViewById(R.id.orgnode_list);\n assert recyclerView != null;\n setupRecyclerView(recyclerView);\n\n if (findViewById(R.id.orgnode_detail_container) != null) {\n // The detail container view will be present only in the\n // large-screen layouts (res/values-w900dp).\n // If this view is present, then the\n // activity should be in two-pane mode.\n ((OutlineAdapter) recyclerView.getAdapter()).setHasTwoPanes(true);\n }\n\n new Style(this);\n\n this.syncReceiver = new SynchServiceReceiver();\n registerReceiver(this.syncReceiver, new IntentFilter(\n Synchronizer.SYNC_UPDATE));\n\n FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);\n if (fab != null) fab.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n AlertDialog.Builder alert = new AlertDialog.Builder(OrgNodeListActivity.this);\n\n alert.setTitle(R.string.new_file);\n alert.setMessage(getResources().getString(R.string.filename) + \":\");\n\n // Set an EditText view to get user input\n final EditText input = new EditText(OrgNodeListActivity.this);\n alert.setView(input);\n\n alert.setPositiveButton(\"Ok\", new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n String filename = input.getText().toString();\n OrgFile newFile = new OrgFile(filename, filename);\n File file = new File(newFile.getFilePath(OrgNodeListActivity.this));\n if(file.exists()){\n Toast.makeText(OrgNodeListActivity.this, R.string.file_exists, Toast.LENGTH_SHORT)\n .show();\n return;\n }\n newFile.addFile(OrgNodeListActivity.this);\n ((OutlineAdapter) recyclerView.getAdapter()).refresh();\n Synchronizer.getInstance().addFile(filename);\n connect();\n }\n });\n\n alert.setNegativeButton(\"Cancel\", new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n // Canceled.\n }\n });\n\n alert.show();\n }\n });\n\n connect();\n }\n\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n MenuInflater inflater = getMenuInflater();\n inflater.inflate(R.menu.outline_menu, menu);\n synchronizerMenuItem = menu.findItem(R.id.menu_sync);\n\n // Get the SearchView and set the searchable configuration\n SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);\n MenuItem searchItem = menu.findItem(R.id.menu_search);\n\n SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);\n\n ComponentName cn = new ComponentName(this, SearchActivity.class);\n searchView.setSearchableInfo(searchManager.getSearchableInfo(cn));\n// searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default\n\n return true;\n }\n\n // TODO: Add onSaveInstanceState and onRestoreInstanceState\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case android.R.id.home:\n return true;\n\n case R.id.menu_sync:\n passwordPrompt = true;\n connect();\n return true;\n\n case R.id.menu_settings:\n runShowSettings(null);\n return true;\n\n case R.id.menu_search:\n onSearchRequested();\n return true;\n\n case R.id.menu_help:\n runHelp(null);\n return true;\n }\n return false;\n }\n\n public void runHelp(View view) {\n Intent intent = new Intent(Intent.ACTION_VIEW,\n Uri.parse(\"https://github.com/matburt/mobileorg-android/wiki\"));\n startActivity(intent);\n }\n\n public void runSynchronize() {\n startService(new Intent(this, SyncService.class));\n }\n\n public void runShowSettings(View view) {\n Intent intent = new Intent(this, SettingsActivity.class);\n startActivity(intent);\n }\n\n public void runShowWizard(View view) {\n startActivity(new Intent(this, WizardActivity.class));\n }\n\n private boolean runSearch() {\n return onSearchRequested();\n }\n\n private void setupRecyclerView(@NonNull RecyclerView recyclerView) {\n recyclerView.setAdapter(new OutlineAdapter(this));\n }\n\n private void showUpgradePopup() {\n AlertDialog.Builder builder = new AlertDialog.Builder(this);\n builder.setMessage(OrgUtils.getStringFromResource(R.raw.upgrade, this));\n builder.setCancelable(false);\n builder.setPositiveButton(R.string.ok,\n new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int id) {\n dialog.dismiss();\n }\n });\n builder.create().show();\n }\n\n\n private void displayNewUserDialogs() {\n if (!PreferenceUtils.isSyncConfigured())\n runShowWizard(null);\n\n if (PreferenceUtils.isUpgradedVersion())\n showUpgradePopup();\n }\n\n @Override\n protected void onDestroy() {\n unregisterReceiver(this.syncReceiver);\n super.onDestroy();\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n runSynchronize();\n }\n\n @Override\n protected void onNewIntent(Intent intent) {\n if (intent.getAction().equals(SYNC_FAILED)) {\n Bundle extrasBundle = intent.getExtras();\n String errorMsg = extrasBundle.getString(\"ERROR_MESSAGE\");\n showSyncFailPopup(errorMsg);\n }\n }\n\n private void showSyncFailPopup(String errorMsg) {\n AlertDialog.Builder builder = new AlertDialog.Builder(this);\n builder.setMessage(errorMsg);\n builder.setCancelable(false);\n builder.setPositiveButton(R.string.ok,\n new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int id) {\n dialog.dismiss();\n }\n });\n builder.create().show();\n }\n\n /**\n * Run the synchronization if credentials are stored or prompt for credentials\n * if it has not yet been prompt\n */\n private void connect() {\n if (Synchronizer.getInstance().isCredentialsRequired() && passwordPrompt) {\n final AlertDialog.Builder alert = new AlertDialog.Builder(OrgNodeListActivity.this);\n final AuthData authData = AuthData.getInstance(OrgNodeListActivity.this);\n alert.setTitle(R.string.prompt_enter_password);\n\n // Set an EditText view to get user input\n final EditText input = new EditText(OrgNodeListActivity.this);\n\n input.setInputType(InputType.TYPE_CLASS_TEXT);\n alert.setView(input);\n input.setText(authData.getPassword());\n\n alert.setPositiveButton(\"Ok\", new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n passwordPrompt = false;\n runSynchronize();\n dialog.dismiss();\n }\n });\n\n alert.setNegativeButton(\"Cancel\", new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int whichButton) {\n passwordPrompt = false;\n dialog.dismiss();\n }\n });\n\n alert.show();\n } else {\n runSynchronize();\n }\n }\n\n private class SynchServiceReceiver extends BroadcastReceiver {\n @Override\n public void onReceive(Context context, Intent intent) {\n boolean syncStart = intent.getBooleanExtra(Synchronizer.SYNC_START, false);\n boolean syncDone = intent.getBooleanExtra(Synchronizer.SYNC_DONE, false);\n int progress = intent.getIntExtra(Synchronizer.SYNC_PROGRESS_UPDATE, -1);\n\n if (syncStart) {\n if (synchronizerMenuItem != null)\n synchronizerMenuItem.setVisible(false);\n } else if (syncDone) {\n ((OutlineAdapter) recyclerView.getAdapter()).refresh();\n if (synchronizerMenuItem != null) synchronizerMenuItem.setVisible(true);\n\n } else if (progress >= 0 && progress <= 100) {\n// int normalizedProgress = (Window.PROGRESS_END - Window.PROGRESS_START) / 100 * progress;\n }\n }\n }\n}" ]
import android.content.ContentResolver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.ActionBar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.view.ActionMode; import android.support.v7.widget.RecyclerView; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.matburt.mobileorg.AgendaFragment; import com.matburt.mobileorg.gui.theme.DefaultTheme; import com.matburt.mobileorg.orgdata.OrgContract; import com.matburt.mobileorg.orgdata.OrgFile; import com.matburt.mobileorg.orgdata.OrgNode; import com.matburt.mobileorg.orgdata.OrgProviderUtils; import com.matburt.mobileorg.OrgNodeDetailActivity; import com.matburt.mobileorg.OrgNodeDetailFragment; import com.matburt.mobileorg.OrgNodeListActivity; import com.matburt.mobileorg.R; import com.matburt.mobileorg.util.OrgNodeNotFoundException; import java.util.ArrayList; import java.util.List;
OutlineAdapter.this.clearSelections(); } @Override public boolean onCreateActionMode(ActionMode actionMode, Menu menu) { MenuInflater inflater = activity.getMenuInflater(); inflater.inflate(R.menu.main_context_action_bar, menu); return true; } @Override public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.item_delete: String message; int numSelectedItems = getSelectedItemCount(); if (numSelectedItems == 1) message = activity.getResources().getString(R.string.prompt_delete_file); else { message = activity.getResources().getString(R.string.prompt_delete_files); message = message.replace("#", String.valueOf(numSelectedItems)); } new AlertDialog.Builder(activity) .setMessage(message) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { deleteSelectedFiles(); } }) .setNegativeButton(android.R.string.no, null).show(); return true; } return false; } }; private DefaultTheme theme; public OutlineAdapter(AppCompatActivity activity) { super(); this.activity = activity; this.resolver = activity.getContentResolver(); this.theme = DefaultTheme.getTheme(activity); selectedItems = new SparseBooleanArray(); refresh(); } public void refresh() { clear(); for (OrgFile file : OrgProviderUtils.getFiles(resolver)){ add(file); } notifyDataSetChanged(); } @Override public int getItemCount() { return items.size() + numExtraItems; } @Override public OutlineItem onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.outline_item, parent, false); return new OutlineItem(v); } @Override public void onBindViewHolder(final OutlineItem holder, final int position) { final int positionInItems = position - numExtraItems; OrgFile file = null; try{ file = items.get(positionInItems); } catch(ArrayIndexOutOfBoundsException ignored){} final boolean conflict = (file != null && file.getState() == OrgFile.State.kConflict); String title; if(position == 0) { title = activity.getResources().getString(R.string.menu_todos); } else if (position == 1){ title = activity.getResources().getString(R.string.menu_agenda); } else { title = items.get(positionInItems).name; } holder.titleView.setText(title); TextView comment = (TextView)holder.mView.findViewById(R.id.comment); if (conflict) { comment.setText(R.string.conflict); comment.setVisibility(View.VISIBLE); } else { comment.setVisibility(View.GONE); } holder.mView.setActivated(selectedItems.get(position, false)); final long itemId = getItemId(position); holder.mView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Context context = v.getContext(); if (getSelectedItemCount() > 0) { if(!isSelectableItem(position)) return; toggleSelection(position); } else { if (mTwoPanes) { Bundle arguments = new Bundle(); Intent intent; // Special activity for conflicted file if(conflict){ intent = new Intent(context, ConflictResolverActivity.class); context.startActivity(intent); return; } if(position == 0){
arguments.putLong(OrgContract.NODE_ID, OrgContract.TODO_ID);
2
JeffreyFalgout/ThrowingStream
throwing-stream/src/main/java/name/falgout/jeffrey/throwing/stream/adapter/CheckedIterator.java
[ "@FunctionalInterface\npublic interface ThrowingConsumer<T, X extends Throwable> {\n public void accept(T t) throws X;\n\n default public Consumer<T> fallbackTo(Consumer<? super T> fallback) {\n return fallbackTo(fallback, null);\n }\n\n default public Consumer<T> fallbackTo(Consumer<? super T> fallback,\n @Nullable Consumer<? super Throwable> thrown) {\n ThrowingConsumer<T, Nothing> t = fallback::accept;\n return orTry(t, thrown)::accept;\n }\n\n default public <Y extends Throwable> ThrowingConsumer<T, Y>\n orTry(ThrowingConsumer<? super T, ? extends Y> f) {\n return orTry(f, null);\n }\n\n default public <Y extends Throwable> ThrowingConsumer<T, Y> orTry(\n ThrowingConsumer<? super T, ? extends Y> f, @Nullable Consumer<? super Throwable> thrown) {\n return t -> {\n ThrowingRunnable<X> s = () -> accept(t);\n s.orTry(() -> f.accept(t), thrown).run();\n };\n }\n\n default public <Y extends Throwable> ThrowingConsumer<T, Y> rethrow(Class<X> x,\n Function<? super X, ? extends Y> mapper) {\n return t -> {\n ThrowingRunnable<X> s = () -> accept(t);\n s.rethrow(x, mapper).run();\n };\n }\n}", "@FunctionalInterface\npublic interface ThrowingDoubleConsumer<X extends Throwable> {\n void accept(double value) throws X;\n\n default public DoubleConsumer fallbackTo(DoubleConsumer fallback) {\n return fallbackTo(fallback, null);\n }\n\n default public DoubleConsumer fallbackTo(DoubleConsumer fallback,\n @Nullable Consumer<? super Throwable> thrown) {\n ThrowingDoubleConsumer<Nothing> t = fallback::accept;\n return orTry(t, thrown)::accept;\n }\n\n default public <Y extends Throwable> ThrowingDoubleConsumer<Y>\n orTry(ThrowingDoubleConsumer<? extends Y> f) {\n return orTry(f, null);\n }\n\n default public <Y extends Throwable> ThrowingDoubleConsumer<Y>\n orTry(ThrowingDoubleConsumer<? extends Y> f, @Nullable Consumer<? super Throwable> thrown) {\n return t -> {\n ThrowingRunnable<X> s = () -> accept(t);\n s.orTry(() -> f.accept(t), thrown).run();\n };\n }\n\n default public <Y extends Throwable> ThrowingDoubleConsumer<Y> rethrow(Class<X> x,\n Function<? super X, ? extends Y> mapper) {\n return t -> {\n ThrowingRunnable<X> s = () -> accept(t);\n s.rethrow(x, mapper).run();\n };\n }\n}", "@FunctionalInterface\npublic interface ThrowingIntConsumer<X extends Throwable> {\n void accept(int value) throws X;\n\n default public IntConsumer fallbackTo(IntConsumer fallback) {\n return fallbackTo(fallback, null);\n }\n\n default public IntConsumer fallbackTo(IntConsumer fallback,\n @Nullable Consumer<? super Throwable> thrown) {\n ThrowingIntConsumer<Nothing> t = fallback::accept;\n return orTry(t, thrown)::accept;\n }\n\n default public <Y extends Throwable> ThrowingIntConsumer<Y>\n orTry(ThrowingIntConsumer<? extends Y> f) {\n return orTry(f, null);\n }\n\n default public <Y extends Throwable> ThrowingIntConsumer<Y>\n orTry(ThrowingIntConsumer<? extends Y> f, @Nullable Consumer<? super Throwable> thrown) {\n return t -> {\n ThrowingRunnable<X> s = () -> accept(t);\n s.orTry(() -> f.accept(t), thrown).run();\n };\n }\n\n default public <Y extends Throwable> ThrowingIntConsumer<Y> rethrow(Class<X> x,\n Function<? super X, ? extends Y> mapper) {\n return t -> {\n ThrowingRunnable<X> s = () -> accept(t);\n s.rethrow(x, mapper).run();\n };\n }\n}", "public interface ThrowingIterator<E, X extends Throwable> {\n public static interface OfPrimitive<E, E_CONS, X extends Throwable>\n extends ThrowingIterator<E, X> {\n public void forEachRemaining(E_CONS action) throws X;\n }\n\n public static interface OfInt<X extends Throwable>\n extends OfPrimitive<Integer, ThrowingIntConsumer<? extends X>, X> {\n public int nextInt() throws X;\n\n @Override\n default public Integer next() throws X {\n return nextInt();\n }\n }\n\n public static interface OfLong<X extends Throwable>\n extends OfPrimitive<Long, ThrowingLongConsumer<? extends X>, X> {\n public long nextLong() throws X;\n\n @Override\n default public Long next() throws X {\n return nextLong();\n }\n }\n\n public static interface OfDouble<X extends Throwable>\n extends OfPrimitive<Double, ThrowingDoubleConsumer<? extends X>, X> {\n public double nextDouble() throws X;\n\n @Override\n default public Double next() throws X {\n return nextDouble();\n }\n }\n\n public E next() throws X;\n\n public boolean hasNext() throws X;\n\n default public void remove() throws X {\n throw new UnsupportedOperationException();\n }\n\n public void forEachRemaining(ThrowingConsumer<? super E, ? extends X> action) throws X;\n}", "@FunctionalInterface\npublic interface ThrowingLongConsumer<X extends Throwable> {\n void accept(long value) throws X;\n\n default public LongConsumer fallbackTo(LongConsumer fallback) {\n return fallbackTo(fallback, null);\n }\n\n default public LongConsumer fallbackTo(LongConsumer fallback,\n @Nullable Consumer<? super Throwable> thrown) {\n ThrowingLongConsumer<Nothing> t = fallback::accept;\n return orTry(t, thrown)::accept;\n }\n\n default public <Y extends Throwable> ThrowingLongConsumer<Y>\n orTry(ThrowingLongConsumer<? extends Y> f) {\n return orTry(f, null);\n }\n\n default public <Y extends Throwable> ThrowingLongConsumer<Y>\n orTry(ThrowingLongConsumer<? extends Y> f, @Nullable Consumer<? super Throwable> thrown) {\n return t -> {\n ThrowingRunnable<X> s = () -> accept(t);\n s.orTry(() -> f.accept(t), thrown).run();\n };\n }\n\n default public <Y extends Throwable> ThrowingLongConsumer<Y> rethrow(Class<X> x,\n Function<? super X, ? extends Y> mapper) {\n return t -> {\n ThrowingRunnable<X> s = () -> accept(t);\n s.rethrow(x, mapper).run();\n };\n }\n}", "public final class ExceptionMasker<X extends Throwable> {\n private static final class MaskedException extends RuntimeException {\n private static final long serialVersionUID = -6116256229712974011L;\n\n private MaskedException(Throwable cause) {\n super(\"Uh oh, someone forgot to unmask!\", cause);\n }\n }\n\n public static Throwable unmask(Throwable throwable) {\n if (throwable instanceof MaskedException) {\n return throwable.getCause();\n }\n\n return throwable;\n }\n\n private final Class<X> exceptionClass;\n private final Function<Throwable, MaskedException> masker;\n private final Function<MaskedException, X> unmasker;\n\n public ExceptionMasker(Class<X> exceptionClass) {\n this.exceptionClass = exceptionClass;\n RethrowChain<Throwable, X> caster = RethrowChain.castTo(exceptionClass);\n masker = caster.rethrow(MaskedException::new).finish();\n RethrowChain<MaskedException, X> unmasker = masked -> caster.apply(masked.getCause());\n this.unmasker = unmasker.finish();\n }\n\n public Class<X> getExceptionClass() {\n return exceptionClass;\n }\n\n public void maskException(ThrowingRunnable<? extends X> runnable) {\n maskException(() -> {\n runnable.run();\n return null;\n });\n }\n\n public <R> R maskException(ThrowingSupplier<? extends R, ? extends X> supplier) {\n try {\n return supplier.get();\n } catch (Throwable t) {\n throw masker.apply(t);\n }\n }\n\n public Runnable mask(ThrowingRunnable<? extends X> runnable) {\n Objects.requireNonNull(runnable);\n return () -> maskException(runnable);\n }\n\n public <R> Supplier<R> mask(ThrowingSupplier<? extends R, ? extends X> supplier) {\n Objects.requireNonNull(supplier);\n return () -> maskException(supplier);\n }\n\n public <T> Predicate<T> mask(ThrowingPredicate<? super T, ? extends X> predicate) {\n Objects.requireNonNull(predicate);\n return t -> maskException(() -> predicate.test(t));\n }\n\n public <T, R> Function<T, R> mask(\n ThrowingFunction<? super T, ? extends R, ? extends X> function) {\n Objects.requireNonNull(function);\n return t -> maskException(() -> function.apply(t));\n }\n\n public <T> Consumer<T> mask(ThrowingConsumer<? super T, ? extends X> consumer) {\n Objects.requireNonNull(consumer);\n return t -> maskException(() -> consumer.accept(t));\n }\n\n public <T, U, R> BiFunction<T, U, R> mask(\n ThrowingBiFunction<? super T, ? super U, ? extends R, ? extends X> function) {\n Objects.requireNonNull(function);\n return (t, u) -> maskException(() -> function.apply(t, u));\n }\n\n public <T> BinaryOperator<T> mask(ThrowingBinaryOperator<T, ? extends X> operator) {\n Objects.requireNonNull(operator);\n return (t1, t2) -> maskException(() -> operator.apply(t1, t2));\n }\n\n public <T> Comparator<T> mask(ThrowingComparator<? super T, ? extends X> comparator) {\n Objects.requireNonNull(comparator);\n return (t1, t2) -> maskException(() -> comparator.compare(t1, t2));\n }\n\n public <T, U> BiConsumer<T, U> mask(\n ThrowingBiConsumer<? super T, ? super U, ? extends X> consumer) {\n Objects.requireNonNull(consumer);\n return (t, u) -> maskException(() -> consumer.accept(t, u));\n }\n\n // int\n\n public IntConsumer mask(ThrowingIntConsumer<? extends X> consumer) {\n Objects.requireNonNull(consumer);\n return i -> maskException(() -> consumer.accept(i));\n }\n\n public IntPredicate mask(ThrowingIntPredicate<? extends X> predicate) {\n Objects.requireNonNull(predicate);\n return i -> maskException(() -> predicate.test(i));\n }\n\n public IntBinaryOperator mask(ThrowingIntBinaryOperator<? extends X> operator) {\n Objects.requireNonNull(operator);\n return (i1, i2) -> maskException(() -> operator.applyAsInt(i1, i2));\n }\n\n public <T> ObjIntConsumer<T> mask(ThrowingObjIntConsumer<T, ? extends X> consumer) {\n Objects.requireNonNull(consumer);\n return (t, i) -> maskException(() -> consumer.accept(t, i));\n }\n\n public IntUnaryOperator mask(ThrowingIntUnaryOperator<? extends X> operator) {\n Objects.requireNonNull(operator);\n return i -> maskException(() -> operator.applyAsInt(i));\n }\n\n public <R> IntFunction<R> mask(ThrowingIntFunction<R, ? extends X> function) {\n Objects.requireNonNull(function);\n return i -> maskException(() -> function.apply(i));\n }\n\n public <T> ToIntFunction<T> mask(ThrowingToIntFunction<T, ? extends X> function) {\n Objects.requireNonNull(function);\n return t -> maskException(() -> function.applyAsInt(t));\n }\n\n public IntToLongFunction mask(ThrowingIntToLongFunction<? extends X> function) {\n Objects.requireNonNull(function);\n return i -> maskException(() -> function.applyAsLong(i));\n }\n\n public IntToDoubleFunction mask(ThrowingIntToDoubleFunction<? extends X> function) {\n Objects.requireNonNull(function);\n return i -> maskException(() -> function.applyAsDouble(i));\n }\n\n // long\n\n public LongConsumer mask(ThrowingLongConsumer<? extends X> consumer) {\n Objects.requireNonNull(consumer);\n return l -> maskException(() -> consumer.accept(l));\n }\n\n public LongPredicate mask(ThrowingLongPredicate<? extends X> predicate) {\n Objects.requireNonNull(predicate);\n return l -> maskException(() -> predicate.test(l));\n }\n\n public LongBinaryOperator mask(ThrowingLongBinaryOperator<? extends X> operator) {\n Objects.requireNonNull(operator);\n return (l1, l2) -> maskException(() -> operator.applyAsLong(l1, l2));\n }\n\n public <T> ObjLongConsumer<T> mask(ThrowingObjLongConsumer<T, ? extends X> consumer) {\n Objects.requireNonNull(consumer);\n return (t, l) -> maskException(() -> consumer.accept(t, l));\n }\n\n public LongUnaryOperator mask(ThrowingLongUnaryOperator<? extends X> operator) {\n Objects.requireNonNull(operator);\n return l -> maskException(() -> operator.applyAsLong(l));\n }\n\n public <R> LongFunction<R> mask(ThrowingLongFunction<R, ? extends X> function) {\n Objects.requireNonNull(function);\n return l -> maskException(() -> function.apply(l));\n }\n\n public <T> ToLongFunction<T> mask(ThrowingToLongFunction<T, ? extends X> function) {\n Objects.requireNonNull(function);\n return t -> maskException(() -> function.applyAsLong(t));\n }\n\n public LongToIntFunction mask(ThrowingLongToIntFunction<? extends X> function) {\n Objects.requireNonNull(function);\n return l -> maskException(() -> function.applyAsInt(l));\n }\n\n public LongToDoubleFunction mask(ThrowingLongToDoubleFunction<? extends X> function) {\n Objects.requireNonNull(function);\n return l -> maskException(() -> function.applyAsDouble(l));\n }\n\n // double\n\n public DoubleConsumer mask(ThrowingDoubleConsumer<? extends X> consumer) {\n Objects.requireNonNull(consumer);\n return d -> maskException(() -> consumer.accept(d));\n }\n\n public DoublePredicate mask(ThrowingDoublePredicate<? extends X> predicate) {\n Objects.requireNonNull(predicate);\n return d -> maskException(() -> predicate.test(d));\n }\n\n public DoubleBinaryOperator mask(ThrowingDoubleBinaryOperator<? extends X> operator) {\n Objects.requireNonNull(operator);\n return (d1, d2) -> maskException(() -> operator.applyAsDouble(d1, d2));\n }\n\n public <T> ObjDoubleConsumer<T> mask(ThrowingObjDoubleConsumer<T, ? extends X> consumer) {\n Objects.requireNonNull(consumer);\n return (t, d) -> maskException(() -> consumer.accept(t, d));\n }\n\n public DoubleUnaryOperator mask(ThrowingDoubleUnaryOperator<? extends X> operator) {\n Objects.requireNonNull(operator);\n return d -> maskException(() -> operator.applyAsDouble(d));\n }\n\n public <R> DoubleFunction<R> mask(ThrowingDoubleFunction<R, ? extends X> function) {\n Objects.requireNonNull(function);\n return d -> maskException(() -> function.apply(d));\n }\n\n public <T> ToDoubleFunction<T> mask(ThrowingToDoubleFunction<T, ? extends X> function) {\n Objects.requireNonNull(function);\n return t -> maskException(() -> function.applyAsDouble(t));\n }\n\n public DoubleToIntFunction mask(ThrowingDoubleToIntFunction<? extends X> function) {\n Objects.requireNonNull(function);\n return d -> maskException(() -> function.applyAsInt(d));\n }\n\n public DoubleToLongFunction mask(ThrowingDoubleToLongFunction<? extends X> function) {\n Objects.requireNonNull(function);\n return d -> maskException(() -> function.applyAsLong(d));\n }\n\n public void unmaskException(Runnable runnable) throws X {\n unmaskException(() -> {\n runnable.run();\n return null;\n });\n }\n\n public <R> R unmaskException(Supplier<? extends R> supplier) throws X {\n try {\n return supplier.get();\n } catch (MaskedException e) {\n throw unmasker.apply(e);\n }\n }\n\n public ThrowingRunnable<X> unmask(Runnable runnable) {\n Objects.requireNonNull(runnable);\n return () -> unmaskException(runnable);\n }\n\n public <R> ThrowingSupplier<R, X> unmask(Supplier<? extends R> supplier) {\n Objects.requireNonNull(supplier);\n return () -> unmaskException(supplier);\n }\n\n public <T> ThrowingPredicate<T, X> unmask(Predicate<? super T> predicate) {\n Objects.requireNonNull(predicate);\n return t -> unmaskException(() -> predicate.test(t));\n }\n\n public <T, R> ThrowingFunction<T, R, X> unmask(Function<? super T, ? extends R> function) {\n Objects.requireNonNull(function);\n return t -> unmaskException(() -> function.apply(t));\n }\n\n public <T> ThrowingConsumer<T, X> unmask(Consumer<? super T> consumer) {\n Objects.requireNonNull(consumer);\n return t -> unmaskException(() -> consumer.accept(t));\n }\n\n public <T, U, R> ThrowingBiFunction<T, U, R, X> unmask(\n BiFunction<? super T, ? super U, ? extends R> function) {\n Objects.requireNonNull(function);\n return (t, u) -> unmaskException(() -> function.apply(t, u));\n }\n\n public <T> ThrowingBinaryOperator<T, X> unmask(BinaryOperator<T> operator) {\n Objects.requireNonNull(operator);\n return (t1, t2) -> unmaskException(() -> operator.apply(t1, t2));\n }\n\n public <T> ThrowingComparator<T, X> unmask(Comparator<? super T> comparator) {\n Objects.requireNonNull(comparator);\n return (t1, t2) -> unmaskException(() -> comparator.compare(t1, t2));\n }\n\n public <T, U> ThrowingBiConsumer<T, U, X> unmask(BiConsumer<? super T, ? super U> consumer) {\n Objects.requireNonNull(consumer);\n return (t, u) -> unmaskException(() -> consumer.accept(t, u));\n }\n\n // int\n\n public ThrowingIntConsumer<X> unmask(IntConsumer consumer) {\n Objects.requireNonNull(consumer);\n return i -> unmaskException(() -> consumer.accept(i));\n }\n\n public ThrowingIntPredicate<X> unmask(IntPredicate predicate) {\n Objects.requireNonNull(predicate);\n return i -> unmaskException(() -> predicate.test(i));\n }\n\n public ThrowingIntBinaryOperator<X> unmask(IntBinaryOperator operator) {\n Objects.requireNonNull(operator);\n return (i1, i2) -> unmaskException(() -> operator.applyAsInt(i1, i2));\n }\n\n public <T> ThrowingObjIntConsumer<T, X> unmask(ObjIntConsumer<T> consumer) {\n Objects.requireNonNull(consumer);\n return (t, i) -> unmaskException(() -> consumer.accept(t, i));\n }\n\n public ThrowingIntUnaryOperator<X> unmask(IntUnaryOperator operator) {\n Objects.requireNonNull(operator);\n return i -> unmaskException(() -> operator.applyAsInt(i));\n }\n\n public <R> ThrowingIntFunction<R, X> unmask(IntFunction<R> function) {\n Objects.requireNonNull(function);\n return i -> unmaskException(() -> function.apply(i));\n }\n\n public <T> ThrowingToIntFunction<T, X> unmask(ToIntFunction<T> function) {\n Objects.requireNonNull(function);\n return t -> unmaskException(() -> function.applyAsInt(t));\n }\n\n public ThrowingIntToLongFunction<X> unmask(IntToLongFunction function) {\n Objects.requireNonNull(function);\n return i -> unmaskException(() -> function.applyAsLong(i));\n }\n\n public ThrowingIntToDoubleFunction<X> unmask(IntToDoubleFunction function) {\n Objects.requireNonNull(function);\n return i -> unmaskException(() -> function.applyAsDouble(i));\n }\n\n // long\n\n public ThrowingLongConsumer<X> unmask(LongConsumer consumer) {\n Objects.requireNonNull(consumer);\n return l -> unmaskException(() -> consumer.accept(l));\n }\n\n public ThrowingLongPredicate<X> unmask(LongPredicate predicate) {\n Objects.requireNonNull(predicate);\n return l -> unmaskException(() -> predicate.test(l));\n }\n\n public ThrowingLongBinaryOperator<X> unmask(LongBinaryOperator operator) {\n Objects.requireNonNull(operator);\n return (l1, l2) -> unmaskException(() -> operator.applyAsLong(l1, l2));\n }\n\n public <T> ThrowingObjLongConsumer<T, X> unmask(ObjLongConsumer<T> consumer) {\n Objects.requireNonNull(consumer);\n return (t, l) -> unmaskException(() -> consumer.accept(t, l));\n }\n\n public ThrowingLongUnaryOperator<X> unmask(LongUnaryOperator operator) {\n Objects.requireNonNull(operator);\n return l -> unmaskException(() -> operator.applyAsLong(l));\n }\n\n public <R> ThrowingLongFunction<R, X> unmask(LongFunction<R> function) {\n Objects.requireNonNull(function);\n return l -> unmaskException(() -> function.apply(l));\n }\n\n public <T> ThrowingToLongFunction<T, X> unmask(ToLongFunction<T> function) {\n Objects.requireNonNull(function);\n return t -> unmaskException(() -> function.applyAsLong(t));\n }\n\n public ThrowingLongToIntFunction<X> unmask(LongToIntFunction function) {\n Objects.requireNonNull(function);\n return l -> unmaskException(() -> function.applyAsInt(l));\n }\n\n public ThrowingLongToDoubleFunction<X> unmask(LongToDoubleFunction function) {\n Objects.requireNonNull(function);\n return l -> unmaskException(() -> function.applyAsDouble(l));\n }\n\n // double\n\n public ThrowingDoubleConsumer<X> unmask(DoubleConsumer consumer) {\n Objects.requireNonNull(consumer);\n return d -> unmaskException(() -> consumer.accept(d));\n }\n\n public ThrowingDoublePredicate<X> unmask(DoublePredicate predicate) {\n Objects.requireNonNull(predicate);\n return d -> unmaskException(() -> predicate.test(d));\n }\n\n public ThrowingDoubleBinaryOperator<X> unmask(DoubleBinaryOperator operator) {\n Objects.requireNonNull(operator);\n return (d1, d2) -> unmaskException(() -> operator.applyAsDouble(d1, d2));\n }\n\n public <T> ThrowingObjDoubleConsumer<T, X> unmask(ObjDoubleConsumer<T> consumer) {\n Objects.requireNonNull(consumer);\n return (t, d) -> unmaskException(() -> consumer.accept(t, d));\n }\n\n public ThrowingDoubleUnaryOperator<X> unmask(DoubleUnaryOperator operator) {\n Objects.requireNonNull(operator);\n return d -> unmaskException(() -> operator.applyAsDouble(d));\n }\n\n public <R> ThrowingDoubleFunction<R, X> unmask(DoubleFunction<R> function) {\n Objects.requireNonNull(function);\n return d -> unmaskException(() -> function.apply(d));\n }\n\n public <T> ThrowingToDoubleFunction<T, X> unmask(ToDoubleFunction<T> function) {\n Objects.requireNonNull(function);\n return t -> unmaskException(() -> function.applyAsDouble(t));\n }\n\n public ThrowingDoubleToIntFunction<X> unmask(DoubleToIntFunction function) {\n Objects.requireNonNull(function);\n return d -> unmaskException(() -> function.applyAsInt(d));\n }\n\n public ThrowingDoubleToLongFunction<X> unmask(DoubleToLongFunction function) {\n Objects.requireNonNull(function);\n return d -> unmaskException(() -> function.applyAsLong(d));\n }\n}" ]
import java.util.Iterator; import name.falgout.jeffrey.throwing.ThrowingConsumer; import name.falgout.jeffrey.throwing.ThrowingDoubleConsumer; import name.falgout.jeffrey.throwing.ThrowingIntConsumer; import name.falgout.jeffrey.throwing.ThrowingIterator; import name.falgout.jeffrey.throwing.ThrowingLongConsumer; import name.falgout.jeffrey.throwing.adapter.ExceptionMasker;
package name.falgout.jeffrey.throwing.stream.adapter; class CheckedIterator<E, X extends Throwable, D extends Iterator<E>> extends CheckedAdapter<D, X> implements ThrowingIterator<E, X> { static class OfInt<X extends Throwable> extends CheckedIterator<Integer, X, java.util.PrimitiveIterator.OfInt> implements ThrowingIterator.OfInt<X> { OfInt(java.util.PrimitiveIterator.OfInt delegate, ExceptionMasker<X> ExceptionMasker) { super(delegate, ExceptionMasker); } @Override public void forEachRemaining(ThrowingIntConsumer<? extends X> action) throws X { unmaskException(() -> getDelegate().forEachRemaining(getExceptionMasker().mask(action))); } @Override public int nextInt() throws X { return unmaskException(getDelegate()::nextInt); } } static class OfLong<X extends Throwable> extends CheckedIterator<Long, X, java.util.PrimitiveIterator.OfLong> implements ThrowingIterator.OfLong<X> { OfLong(java.util.PrimitiveIterator.OfLong delegate, ExceptionMasker<X> ExceptionMasker) { super(delegate, ExceptionMasker); } @Override
public void forEachRemaining(ThrowingLongConsumer<? extends X> action) throws X {
4
piyell/NeteaseCloudMusic
app/src/main/java/com/zsorg/neteasecloudmusic/utils/AlertUtil.java
[ "public interface OnDeleteListener {\n public void onDelete(boolean isDeleteOnDisk);\n}", "public interface OnItemCLickListener {\n void onItemClick(View view, int position);\n}", "public interface OnTextSubmitListener {\n void onTextSubmit(String text);\n}", "public class PlaylistAdapter extends BaseAdapter<PlaylistHolder> {\n\n private ArrayList<MusicBean> mValues;\n private boolean isHideRightIcon;\n\n public PlaylistAdapter(@NonNull LayoutInflater inflater) {\n super(inflater);\n }\n\n public PlaylistAdapter(@NonNull LayoutInflater inflater,boolean hideRightIcon) {\n super(inflater);\n isHideRightIcon = hideRightIcon;\n }\n\n @Override\n public PlaylistHolder onCreateHolder(ViewGroup parent, int viewType) {\n PlaylistHolder holder = new PlaylistHolder(mInflater.inflate(R.layout.play_list_item, parent, false));\n holder.ivRight.setVisibility(isHideRightIcon? View.GONE:View.VISIBLE);\n holder.setMenuList(GroupSongMenuModel.getInstance(parent.getContext()).getMenuList());\n return holder;\n }\n\n @Override\n public void onBindHolder(final PlaylistHolder holder, final int position) {\n\n final MusicBean bean = mValues.get(position);\n\n final Context context = holder.tvTitle.getContext();\n\n String unknown = \"未知\";\n String count = \"首 \";\n if (null != context) {\n unknown = context.getString(R.string.unknown);\n count = context.getString(R.string.songs_count,bean.getAlbum());\n\n holder.setOnMenuItemClickListener(new OnMenuItemClickListener() {\n @Override\n public void onMenuItemClick(int menuPosition) {\n final PlaylistModel model = new PlaylistModel(context);\n\n final ArrayList<MusicBean> list = (ArrayList<MusicBean>) model.loadPlaylist((int) bean.getDuration());\n if (menuPosition == 0) {\n MusicPlayerService.startActionSet(context, list, 0);\n MusicPlayerService.startActionPlay(context, true);\n } else {\n AlertUtil.showDeletePlaylistDialog(context, new OnDeleteListener() {\n @Override\n public void onDelete(boolean isDeleteOnDisk) {\n int playlistID = (int) bean.getDuration();\n if (playlistID > 0) {\n model.deletePlaylist(playlistID);\n mValues.remove(position);\n notifyItemRemoved(position);\n } else {\n Snackbar.make(holder.iv,R.string.cannot_delete_favorite,Snackbar.LENGTH_SHORT).show();\n }\n }\n });\n }\n }\n });\n } else {\n count = bean.getAlbum()+count;\n }\n\n String title = bean.getName() == null ? unknown : bean.getName();\n\n holder.setTitle(title);\n\n holder.tvTitle.setText(title);\n holder.tvContent.setText(count);\n }\n\n @Override\n public void setDatas(List<MusicBean> list) {\n\n mValues = (ArrayList<MusicBean>) list;\n }\n\n @Override\n public MusicBean getDataAtPosition(int position) {\n return mValues!=null?mValues.get(position-1):null;\n }\n\n @Override\n public ArrayList<MusicBean> getDataList() {\n return mValues;\n }\n\n @Override\n public int getDataCount() {\n return mValues!=null?mValues.size():0;\n }\n\n}", "public class ConfigModel implements IConfigModel{\n\n private static ConfigModel mModel;\n private final SoftReference<Context> mContext;\n\n List<ConfigBean> mList;\n private final SharedPreferences mSP;\n private final String[] orders;\n private int mMusicOrder;\n private ConfigCallback callback;\n\n @Override\n public List<ConfigBean> getConfigList() {\n return mList;\n }\n\n public void setMusicOrder(int musicOrder) {\n mList.get(0).setItemRight(orders[musicOrder]);\n mMusicOrder = musicOrder;\n SharedPreferences.Editor edit = mSP.edit();\n edit.putInt(CONST.SP_MUSIC_ORDER, musicOrder);\n edit.apply();\n if (null != callback) {\n callback.onMusicOrderConfigChanged(musicOrder);\n }\n }\n\n public void setConfigCallback(ConfigCallback callback) {\n this.callback = callback;\n callback.onMusicOrderConfigChanged(mMusicOrder);\n callback.onIsShow60sConfigChanged(isFilter60s());\n }\n\n public void setIsFilter60s(boolean isFilter) {\n mList.get(1).setSwitchChecked(isFilter);\n SharedPreferences.Editor edit = mSP.edit();\n edit.putBoolean(CONST.SP_IS_FILTER_60, isFilter);\n edit.apply();\n if (null != callback) {\n callback.onIsShow60sConfigChanged(isFilter);\n }\n }\n\n public boolean isFilter60s() {\n return mList.get(1).isSwitchChecked();\n }\n\n public String getMusicOrderString() {\n return orders[mMusicOrder];\n }\n\n public int getMusicOrder() {\n return mMusicOrder;\n }\n\n public static ConfigModel getInstance(Context context) {\n if (null == mModel) {\n synchronized (ConfigModel.class) {\n mModel = new ConfigModel(context);\n }\n }\n return mModel;\n }\n\n @Override\n protected void finalize() throws Throwable {\n callback = null;\n super.finalize();\n Log.e(\"tag\", \"ConfigModel finalize\");\n }\n\n private ConfigModel(@NonNull Context context) {\n mContext = new SoftReference<Context>(context);\n mList = new ArrayList<>();\n mSP = PreferenceManager.getDefaultSharedPreferences(context);\n boolean isFilter = mSP.getBoolean(CONST.SP_IS_FILTER_60, true);\n mMusicOrder = mSP.getInt(CONST.SP_MUSIC_ORDER, CONST.SP_MUSIC_ORDER_DEFAULT);\n orders = context.getResources().getStringArray(R.array.array_music_order);\n mList.add(new ConfigBean(getString(R.string.music), getString(R.string.music_play_order), null, orders[mMusicOrder], false, false, true));\n mList.add(new ConfigBean(getString(R.string.scan), getString(R.string.filter_less_than_60), null, null, true, isFilter, false));\n }\n\n private String getString(@StringRes int stringID) {\n Context context = mContext.get();\n if (null != context) {\n return context.getString(stringID);\n }\n return null;\n }\n\n}", "public class PlaylistModel {\n\n private final DiskMusicHelper mDBHelper;\n private final String songsILove;\n\n public PlaylistModel(Context context) {\n mDBHelper = new DiskMusicHelper(context, \"diskMusic\", 1);\n songsILove = context.getString(R.string.songs_i_love);\n }\n\n public void addToPlaylist(int playlistID,String path) {\n SQLiteDatabase db = mDBHelper.getWritableDatabase();\n ContentValues values = new ContentValues();\n values.put(\"list_id\", playlistID);\n values.put(\"path\", path);\n db.insert(\"playlist_detail\", null, values);\n db.close();\n }\n\n public int newPlaylist(String name) {\n SQLiteDatabase db = mDBHelper.getWritableDatabase();\n ContentValues values = new ContentValues();\n values.put(\"name\", name);\n db.insert(\"playlist\", null, values);\n\n Cursor cursor = db.rawQuery(\"select list_id from playlist where rowid==last_insert_rowid();\", null);\n int listID=-2;\n if (cursor.moveToFirst()) {\n listID = cursor.getInt(0);\n }\n cursor.close();\n db.close();\n return listID;\n }\n\n public int findPositionInPlaylist(int playlistID, String path) {\n SQLiteDatabase db = mDBHelper.getWritableDatabase();\n Cursor cursor = db.rawQuery(\"select * from playlist_detail where list_id==? order by playlist_detail.[path] desc;\", new String[]{String.valueOf(playlistID)});\n for (int position = 0; cursor != null && cursor.moveToNext(); position++) {\n String tmp = cursor.getString(1);\n if (path.equals(tmp)) {\n return position;\n }\n }\n return 0;\n }\n\n public int addMusicToTempPlaylist(Context context, final String path) {\n int position = 0;\n final List<MusicBean> list = new DiskMusicDao(context).queryAll();\n for (; position < list.size() && !path.equals(list.get(position).getPath()); position++);\n return position;\n// Flowable.fromIterable(list).filter(new Predicate<MusicBean>() {\n// @Override\n// public boolean test(MusicBean bean) throws Exception {\n// return path.equals(bean.getPath());\n// }\n// }).subscribeOn(Schedulers.io()).subscribe(new Consumer<MusicBean>() {\n// @Override\n// public void accept(MusicBean bean) throws Exception {\n// position= list.indexOf(bean);\n// }\n// });\n }\n\n public void deleteFromPlaylist(int playlistID,String path) {\n SQLiteDatabase db = mDBHelper.getWritableDatabase();\n db.delete(\"playlist_detail\", \"(list_id==?) and (path==?)\", new String[]{String.valueOf(playlistID), path});\n db.close();\n }\n\n public boolean isInPlaylist(int playlistID,String path) {\n SQLiteDatabase db = mDBHelper.getWritableDatabase();\n Cursor cursor = db.rawQuery(\"select * from playlist_detail where (list_id==?) and (path==?);\", new String[]{String.valueOf(playlistID), path});\n boolean value = cursor.moveToFirst();\n cursor.close();\n db.close();\n return value;\n }\n\n public List<MusicBean> loadPlaylistList() {\n SQLiteDatabase db = mDBHelper.getReadableDatabase();\n Cursor cursor = db.rawQuery(\"select playlist.[list_id],playlist.[name],playlist.[path],count(playlist_detail.[path]) from playlist left join playlist_detail on playlist_detail.[list_id]=playlist.[list_id] group by playlist.[list_id] order by playlist.[list_id] asc;\",null);\n\n ArrayList<MusicBean> list = new ArrayList<>();\n\n while (null != cursor && cursor.moveToNext()) {\n int listID = cursor.getInt(0);\n String name = cursor.getString(1);\n String path = cursor.getString(2);\n String count = cursor.getString(3);\n list.add(new MusicBean((listID!=CONST.PLAYLIST_FAVORITE?name:songsILove), null, count, listID, path));\n }\n if (cursor != null) {\n cursor.close();\n }\n db.close();\n\n return list;\n }\n\n public List<MusicBean> loadPlaylist(int playlistID) {\n SQLiteDatabase db = mDBHelper.getReadableDatabase();\n Cursor cursor = db.rawQuery(\"select name,singer,album,duration,diskMusic.[path] from diskMusic left join playlist_detail on playlist_detail.[path]=diskMusic.[path] where playlist_detail.[list_id]=? order by playlist_detail.[path] desc; \"\n ,new String[]{String.valueOf(playlistID)});\n\n ArrayList<MusicBean> list = new ArrayList<>();\n\n while (null != cursor && cursor.moveToNext()) {\n String name = cursor.getString(0);\n String singer = cursor.getString(1);\n String album = cursor.getString(2);\n long duration = cursor.getLong(3);\n String path = cursor.getString(4);\n list.add(new MusicBean(name,singer,album,duration, path));\n }\n if (cursor != null) {\n cursor.close();\n }\n db.close();\n\n return list;\n }\n\n public void deletePlaylist(int playlistID) {\n SQLiteDatabase db = mDBHelper.getWritableDatabase();\n db.delete(\"playlist_detail\", \"(list_id==?)\", new String[]{String.valueOf(playlistID)});\n db.delete(\"playlist\", \"(list_id==?)\", new String[]{String.valueOf(playlistID)});\n db.close();\n }\n}", "public class MusicBean implements Parcelable{\n private final String mSinger;\n private final String mAlbum;\n private String mPath;\n private String mName;\n private long mDuration;\n\n protected MusicBean(Parcel in) {\n mSinger = in.readString();\n mAlbum = in.readString();\n mPath = in.readString();\n mName = in.readString();\n mDuration = in.readLong();\n }\n\n public static final Creator<MusicBean> CREATOR = new Creator<MusicBean>() {\n @Override\n public MusicBean createFromParcel(Parcel in) {\n return new MusicBean(in);\n }\n\n @Override\n public MusicBean[] newArray(int size) {\n return new MusicBean[size];\n }\n };\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel parcel, int i) {\n\n parcel.writeString(mSinger);\n parcel.writeString(mAlbum);\n parcel.writeString(mPath);\n parcel.writeString(mName);\n parcel.writeLong(mDuration);\n }\n\n @Override\n public int hashCode() {\n return mPath==null?0:mPath.hashCode();\n }\n\n @Override\n public boolean equals(Object obj) {\n return obj instanceof MusicBean && (((MusicBean) obj).hashCode()==hashCode());\n }\n\n public MusicBean(String name, String singer, String album, long duration, String path) {\n mPath = path;\n mName = name;\n mSinger = singer;\n mAlbum = album;\n mDuration = duration;\n }\n\n public String getSinger() {\n return mSinger;\n }\n\n public String getAlbum() {\n return mAlbum;\n }\n\n public String getPath() {\n return mPath;\n }\n\n public void setPath(String mPath) {\n this.mPath = mPath;\n }\n\n public String getName() {\n return mName;\n }\n\n public void setName(String mName) {\n this.mName = mName;\n }\n\n public long getDuration() {\n return mDuration;\n }\n\n public void setDuration(long mDuration) {\n this.mDuration = mDuration;\n }\n}" ]
import android.content.Context; import android.content.DialogInterface; import android.support.v7.app.AlertDialog; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.zsorg.neteasecloudmusic.callbacks.OnDeleteListener; import com.zsorg.neteasecloudmusic.callbacks.OnItemCLickListener; import com.zsorg.neteasecloudmusic.callbacks.OnTextSubmitListener; import com.zsorg.neteasecloudmusic.adapters.PlaylistAdapter; import com.zsorg.neteasecloudmusic.R; import com.zsorg.neteasecloudmusic.models.ConfigModel; import com.zsorg.neteasecloudmusic.models.PlaylistModel; import com.zsorg.neteasecloudmusic.models.beans.MusicBean; import java.util.List; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers;
package com.zsorg.neteasecloudmusic.utils; /** * Project:NeteaseCloudMusic * * @Author: piyel_000 * Created on 2017/2/3. * E-mail:[email protected] */ public class AlertUtil { public static void showDeleteDialog(Context context, final OnDeleteListener listener) { final boolean[] isDeleteOnDisk = new boolean[1]; new AlertDialog.Builder(context) .setTitle(R.string.confirm_to_remove_music) .setMultiChoiceItems(R.array.delete_on_disk_choice, new boolean[]{false}, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i, boolean b) { isDeleteOnDisk[0] = b; } }) .setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if (listener != null) { listener.onDelete(isDeleteOnDisk[0]); } } }) .setNegativeButton(R.string.cancel, null) .show(); } public static void showDeletePlaylistDialog(Context context, final OnDeleteListener listener) { final boolean[] isDeleteOnDisk = new boolean[1]; new AlertDialog.Builder(context) .setMessage(R.string.confirm_to_delete_playlist) .setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if (listener != null) { listener.onDelete(isDeleteOnDisk[0]); } } }) .setNegativeButton(R.string.cancel, null) .show(); } public static void showCollectionDialog(final Context context, final MusicBean bean) { final PlaylistModel model = new PlaylistModel(context); final AlertDialog dialog = new AlertDialog.Builder(context) .setTitle(R.string.collect_to_playlist).create(); LayoutInflater inflater = LayoutInflater.from(context); RecyclerView rvPlaylist = (RecyclerView) inflater.inflate(R.layout.dialog_collection_to_playlist, null); rvPlaylist.setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER); rvPlaylist.setLayoutManager(new LinearLayoutManager(context)); final PlaylistAdapter adapter = new PlaylistAdapter(inflater,true); View view = inflater.inflate(R.layout.header_add_playlist, null); adapter.addHeaderView(view); adapter.setOnItemClickListener(new OnItemCLickListener() { @Override public void onItemClick(View view, int position) { switch (position) { case 0:
showNewPlaylistDialog(context, new OnTextSubmitListener() {
2
JoostvDoorn/GlutenVrijApp
app/src/main/java/com/joostvdoorn/glutenvrij/scanner/core/oned/UPCAReader.java
[ "public final class BarcodeFormat {\n\n // No, we can't use an enum here. J2ME doesn't support it.\n\n private static final Hashtable VALUES = new Hashtable();\n\n /** Aztec 2D barcode format. */\n public static final BarcodeFormat AZTEC = new BarcodeFormat(\"AZTEC\");\n\n /** CODABAR 1D format. */\n public static final BarcodeFormat CODABAR = new BarcodeFormat(\"CODABAR\");\n\n /** Code 39 1D format. */\n public static final BarcodeFormat CODE_39 = new BarcodeFormat(\"CODE_39\");\n\n /** Code 93 1D format. */\n public static final BarcodeFormat CODE_93 = new BarcodeFormat(\"CODE_93\");\n\n /** Code 128 1D format. */\n public static final BarcodeFormat CODE_128 = new BarcodeFormat(\"CODE_128\");\n\n /** Data Matrix 2D barcode format. */\n public static final BarcodeFormat DATA_MATRIX = new BarcodeFormat(\"DATA_MATRIX\");\n\n /** EAN-8 1D format. */\n public static final BarcodeFormat EAN_8 = new BarcodeFormat(\"EAN_8\");\n\n /** EAN-13 1D format. */\n public static final BarcodeFormat EAN_13 = new BarcodeFormat(\"EAN_13\");\n\n /** ITF (Interleaved Two of Five) 1D format. */\n public static final BarcodeFormat ITF = new BarcodeFormat(\"ITF\");\n\n /** PDF417 format. */\n public static final BarcodeFormat PDF_417 = new BarcodeFormat(\"PDF_417\");\n\n /** QR Code 2D barcode format. */\n public static final BarcodeFormat QR_CODE = new BarcodeFormat(\"QR_CODE\");\n\n /** RSS 14 */\n public static final BarcodeFormat RSS_14 = new BarcodeFormat(\"RSS_14\");\n\n /** RSS EXPANDED */\n public static final BarcodeFormat RSS_EXPANDED = new BarcodeFormat(\"RSS_EXPANDED\");\n\n /** UPC-A 1D format. */\n public static final BarcodeFormat UPC_A = new BarcodeFormat(\"UPC_A\");\n\n /** UPC-E 1D format. */\n public static final BarcodeFormat UPC_E = new BarcodeFormat(\"UPC_E\");\n\n /** UPC/EAN extension format. Not a stand-alone format. */\n public static final BarcodeFormat UPC_EAN_EXTENSION = new BarcodeFormat(\"UPC_EAN_EXTENSION\");\n\n private final String name;\n\n private BarcodeFormat(String name) {\n this.name = name;\n VALUES.put(name, this);\n }\n\n public String getName() {\n return name;\n }\n\n public String toString() {\n return name;\n }\n\n public static BarcodeFormat valueOf(String name) {\n if (name == null || name.length() == 0) {\n throw new IllegalArgumentException();\n }\n BarcodeFormat format = (BarcodeFormat) VALUES.get(name);\n if (format == null) {\n throw new IllegalArgumentException();\n }\n return format;\n }\n\n}", "public final class BinaryBitmap {\n\n private final Binarizer binarizer;\n private BitMatrix matrix;\n\n public BinaryBitmap(Binarizer binarizer) {\n if (binarizer == null) {\n throw new IllegalArgumentException(\"Binarizer must be non-null.\");\n }\n this.binarizer = binarizer;\n matrix = null;\n }\n\n /**\n * @return The width of the bitmap.\n */\n public int getWidth() {\n return binarizer.getLuminanceSource().getWidth();\n }\n\n /**\n * @return The height of the bitmap.\n */\n public int getHeight() {\n return binarizer.getLuminanceSource().getHeight();\n }\n\n /**\n * Converts one row of luminance data to 1 bit data. May actually do the conversion, or return\n * cached data. Callers should assume this method is expensive and call it as seldom as possible.\n * This method is intended for decoding 1D barcodes and may choose to apply sharpening.\n *\n * @param y The row to fetch, 0 <= y < bitmap height.\n * @param row An optional preallocated array. If null or too small, it will be ignored.\n * If used, the Binarizer will call BitArray.clear(). Always use the returned object.\n * @return The array of bits for this row (true means black).\n */\n public BitArray getBlackRow(int y, BitArray row) throws NotFoundException {\n return binarizer.getBlackRow(y, row);\n }\n\n /**\n * Converts a 2D array of luminance data to 1 bit. As above, assume this method is expensive\n * and do not call it repeatedly. This method is intended for decoding 2D barcodes and may or\n * may not apply sharpening. Therefore, a row from this matrix may not be identical to one\n * fetched using getBlackRow(), so don't mix and match between them.\n *\n * @return The 2D array of bits for the image (true means black).\n */\n public BitMatrix getBlackMatrix() throws NotFoundException {\n // The matrix is created on demand the first time it is requested, then cached. There are two\n // reasons for this:\n // 1. This work will never be done if the caller only installs 1D Reader objects, or if a\n // 1D Reader finds a barcode before the 2D Readers run.\n // 2. This work will only be done once even if the caller installs multiple 2D Readers.\n if (matrix == null) {\n matrix = binarizer.getBlackMatrix();\n }\n return matrix;\n }\n\n /**\n * @return Whether this bitmap can be cropped.\n */\n public boolean isCropSupported() {\n return binarizer.getLuminanceSource().isCropSupported();\n }\n\n /**\n * Returns a new object with cropped image data. Implementations may keep a reference to the\n * original data rather than a copy. Only callable if isCropSupported() is true.\n *\n * @param left The left coordinate, 0 <= left < getWidth().\n * @param top The top coordinate, 0 <= top <= getHeight().\n * @param width The width of the rectangle to crop.\n * @param height The height of the rectangle to crop.\n * @return A cropped version of this object.\n */\n public BinaryBitmap crop(int left, int top, int width, int height) {\n LuminanceSource newSource = binarizer.getLuminanceSource().crop(left, top, width, height);\n return new BinaryBitmap(binarizer.createBinarizer(newSource));\n }\n\n /**\n * @return Whether this bitmap supports counter-clockwise rotation.\n */\n public boolean isRotateSupported() {\n return binarizer.getLuminanceSource().isRotateSupported();\n }\n\n /**\n * Returns a new object with rotated image data. Only callable if isRotateSupported() is true.\n *\n * @return A rotated version of this object.\n */\n public BinaryBitmap rotateCounterClockwise() {\n LuminanceSource newSource = binarizer.getLuminanceSource().rotateCounterClockwise();\n return new BinaryBitmap(binarizer.createBinarizer(newSource));\n }\n\n}", "public final class ChecksumException extends ReaderException {\n\n private static final ChecksumException instance = new ChecksumException();\n\n private ChecksumException() {\n // do nothing\n }\n\n public static ChecksumException getChecksumInstance() {\n return instance;\n }\n\n}", "public final class FormatException extends ReaderException {\n\n private static final FormatException instance = new FormatException();\n\n private FormatException() {\n // do nothing\n }\n\n public static FormatException getFormatInstance() {\n return instance;\n }\n\n}", "public final class NotFoundException extends ReaderException {\n\n private static final NotFoundException instance = new NotFoundException();\n\n private NotFoundException() {\n // do nothing\n }\n\n public static NotFoundException getNotFoundInstance() {\n return instance;\n }\n\n}", "public final class Result {\n\n private final String text;\n private final byte[] rawBytes;\n private ResultPoint[] resultPoints;\n private final BarcodeFormat format;\n private Hashtable resultMetadata;\n private final long timestamp;\n\n public Result(String text,\n byte[] rawBytes,\n ResultPoint[] resultPoints,\n BarcodeFormat format) {\n this(text, rawBytes, resultPoints, format, System.currentTimeMillis());\n }\n\n public Result(String text,\n byte[] rawBytes,\n ResultPoint[] resultPoints,\n BarcodeFormat format,\n long timestamp) {\n if (text == null && rawBytes == null) {\n throw new IllegalArgumentException(\"Text and bytes are null\");\n }\n this.text = text;\n this.rawBytes = rawBytes;\n this.resultPoints = resultPoints;\n this.format = format;\n this.resultMetadata = null;\n this.timestamp = timestamp;\n }\n\n /**\n * @return raw text encoded by the barcode, if applicable, otherwise <code>null</code>\n */\n public String getText() {\n return text;\n }\n\n /**\n * @return raw bytes encoded by the barcode, if applicable, otherwise <code>null</code>\n */\n public byte[] getRawBytes() {\n return rawBytes;\n }\n\n /**\n * @return points related to the barcode in the image. These are typically points\n * identifying finder patterns or the corners of the barcode. The exact meaning is\n * specific to the type of barcode that was decoded.\n */\n public ResultPoint[] getResultPoints() {\n return resultPoints;\n }\n\n /**\n * @return {@link BarcodeFormat} representing the format of the barcode that was decoded\n */\n public BarcodeFormat getBarcodeFormat() {\n return format;\n }\n\n /**\n * @return {@link Hashtable} mapping {@link ResultMetadataType} keys to values. May be\n * <code>null</code>. This contains optional metadata about what was detected about the barcode,\n * like orientation.\n */\n public Hashtable getResultMetadata() {\n return resultMetadata;\n }\n\n public void putMetadata(ResultMetadataType type, Object value) {\n if (resultMetadata == null) {\n resultMetadata = new Hashtable(3);\n }\n resultMetadata.put(type, value);\n }\n\n public void putAllMetadata(Hashtable metadata) {\n if (metadata != null) {\n if (resultMetadata == null) {\n resultMetadata = metadata;\n } else {\n Enumeration e = metadata.keys();\n while (e.hasMoreElements()) {\n ResultMetadataType key = (ResultMetadataType) e.nextElement();\n Object value = metadata.get(key);\n resultMetadata.put(key, value);\n }\n }\n }\n }\n\n public void addResultPoints(ResultPoint[] newPoints) {\n if (resultPoints == null) {\n resultPoints = newPoints;\n } else if (newPoints != null && newPoints.length > 0) {\n ResultPoint[] allPoints = new ResultPoint[resultPoints.length + newPoints.length];\n System.arraycopy(resultPoints, 0, allPoints, 0, resultPoints.length);\n System.arraycopy(newPoints, 0, allPoints, resultPoints.length, newPoints.length);\n resultPoints = allPoints;\n }\n }\n\n public long getTimestamp() {\n return timestamp;\n }\n\n public String toString() {\n if (text == null) {\n return \"[\" + rawBytes.length + \" bytes]\";\n } else {\n return text;\n }\n }\n\n}", "public final class BitArray {\n // I have changed these members to be public so ProGuard can inline get() and set(). Ideally\n // they'd be private and we'd use the -allowaccessmodification flag, but Dalvik rejects the\n // resulting binary at runtime on Android. If we find a solution to this, these should be changed\n // back to private.\n public int[] bits;\n public int size;\n\n public BitArray() {\n this.size = 0;\n this.bits = new int[1];\n }\n\n public BitArray(int size) {\n this.size = size;\n this.bits = makeArray(size);\n }\n\n public int getSize() {\n return size;\n }\n\n public int getSizeInBytes() {\n return (size + 7) >> 3;\n }\n\n private void ensureCapacity(int size) {\n if (size > bits.length << 5) {\n int[] newBits = makeArray(size);\n System.arraycopy(bits, 0, newBits, 0, bits.length);\n this.bits = newBits;\n }\n }\n\n /**\n * @param i bit to get\n * @return true iff bit i is set\n */\n public boolean get(int i) {\n return (bits[i >> 5] & (1 << (i & 0x1F))) != 0;\n }\n\n /**\n * Sets bit i.\n *\n * @param i bit to set\n */\n public void set(int i) {\n bits[i >> 5] |= 1 << (i & 0x1F);\n }\n\n /**\n * Flips bit i.\n *\n * @param i bit to set\n */\n public void flip(int i) {\n bits[i >> 5] ^= 1 << (i & 0x1F);\n }\n\n /**\n * Sets a block of 32 bits, starting at bit i.\n *\n * @param i first bit to set\n * @param newBits the new value of the next 32 bits. Note again that the least-significant bit\n * corresponds to bit i, the next-least-significant to i+1, and so on.\n */\n public void setBulk(int i, int newBits) {\n bits[i >> 5] = newBits;\n }\n\n /**\n * Clears all bits (sets to false).\n */\n public void clear() {\n int max = bits.length;\n for (int i = 0; i < max; i++) {\n bits[i] = 0;\n }\n }\n\n /**\n * Efficient method to check if a range of bits is set, or not set.\n *\n * @param start start of range, inclusive.\n * @param end end of range, exclusive\n * @param value if true, checks that bits in range are set, otherwise checks that they are not set\n * @return true iff all bits are set or not set in range, according to value argument\n * @throws IllegalArgumentException if end is less than or equal to start\n */\n public boolean isRange(int start, int end, boolean value) {\n if (end < start) {\n throw new IllegalArgumentException();\n }\n if (end == start) {\n return true; // empty range matches\n }\n end--; // will be easier to treat this as the last actually set bit -- inclusive\n int firstInt = start >> 5;\n int lastInt = end >> 5;\n for (int i = firstInt; i <= lastInt; i++) {\n int firstBit = i > firstInt ? 0 : start & 0x1F;\n int lastBit = i < lastInt ? 31 : end & 0x1F;\n int mask;\n if (firstBit == 0 && lastBit == 31) {\n mask = -1;\n } else {\n mask = 0;\n for (int j = firstBit; j <= lastBit; j++) {\n mask |= 1 << j;\n }\n }\n\n // Return false if we're looking for 1s and the masked bits[i] isn't all 1s (that is,\n // equals the mask, or we're looking for 0s and the masked portion is not all 0s\n if ((bits[i] & mask) != (value ? mask : 0)) {\n return false;\n }\n }\n return true;\n }\n\n public void appendBit(boolean bit) {\n ensureCapacity(size + 1);\n if (bit) {\n bits[size >> 5] |= (1 << (size & 0x1F));\n }\n size++;\n }\n\n /**\n * Appends the least-significant bits, from value, in order from most-significant to\n * least-significant. For example, appending 6 bits from 0x000001E will append the bits\n * 0, 1, 1, 1, 1, 0 in that order.\n */\n public void appendBits(int value, int numBits) {\n if (numBits < 0 || numBits > 32) {\n throw new IllegalArgumentException(\"Num bits must be between 0 and 32\");\n }\n ensureCapacity(size + numBits);\n for (int numBitsLeft = numBits; numBitsLeft > 0; numBitsLeft--) {\n appendBit(((value >> (numBitsLeft - 1)) & 0x01) == 1);\n }\n }\n\n public void appendBitArray(BitArray other) {\n int otherSize = other.getSize();\n ensureCapacity(size + otherSize);\n for (int i = 0; i < otherSize; i++) {\n appendBit(other.get(i));\n }\n }\n\n public void xor(BitArray other) {\n if (bits.length != other.bits.length) {\n throw new IllegalArgumentException(\"Sizes don't match\");\n }\n for (int i = 0; i < bits.length; i++) {\n // The last byte could be incomplete (i.e. not have 8 bits in\n // it) but there is no problem since 0 XOR 0 == 0.\n bits[i] ^= other.bits[i];\n }\n }\n\n /**\n *\n * @param bitOffset first bit to start writing\n * @param array array to write into. Bytes are written most-significant byte first. This is the opposite\n * of the internal representation, which is exposed by {@link #getBitArray()}\n * @param offset position in array to start writing\n * @param numBytes how many bytes to write\n */\n public void toBytes(int bitOffset, byte[] array, int offset, int numBytes) {\n for (int i = 0; i < numBytes; i++) {\n int theByte = 0;\n for (int j = 0; j < 8; j++) {\n if (get(bitOffset)) {\n theByte |= 1 << (7 - j);\n }\n bitOffset++;\n }\n array[offset + i] = (byte) theByte;\n }\n }\n\n /**\n * @return underlying array of ints. The first element holds the first 32 bits, and the least\n * significant bit is bit 0.\n */\n public int[] getBitArray() {\n return bits;\n }\n\n /**\n * Reverses all bits in the array.\n */\n public void reverse() {\n int[] newBits = new int[bits.length];\n int size = this.size;\n for (int i = 0; i < size; i++) {\n if (get(size - i - 1)) {\n newBits[i >> 5] |= 1 << (i & 0x1F);\n }\n }\n bits = newBits;\n }\n\n private static int[] makeArray(int size) {\n return new int[(size + 31) >> 5];\n }\n\n public String toString() {\n StringBuffer result = new StringBuffer(size);\n for (int i = 0; i < size; i++) {\n if ((i & 0x07) == 0) {\n result.append(' ');\n }\n result.append(get(i) ? 'X' : '.');\n }\n return result.toString();\n }\n\n}" ]
import com.joostvdoorn.glutenvrij.scanner.core.BarcodeFormat; import com.joostvdoorn.glutenvrij.scanner.core.BinaryBitmap; import com.joostvdoorn.glutenvrij.scanner.core.ChecksumException; import com.joostvdoorn.glutenvrij.scanner.core.FormatException; import com.joostvdoorn.glutenvrij.scanner.core.NotFoundException; import com.joostvdoorn.glutenvrij.scanner.core.Result; import com.joostvdoorn.glutenvrij.scanner.core.common.BitArray; import java.util.Hashtable;
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.joostvdoorn.glutenvrij.scanner.core.oned; /** * <p>Implements decoding of the UPC-A format.</p> * * @author [email protected] (Daniel Switkin) * @author Sean Owen */ public final class UPCAReader extends UPCEANReader { private final UPCEANReader ean13Reader = new EAN13Reader(); public Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange, Hashtable hints)
throws NotFoundException, FormatException, ChecksumException {
4
heroku/heroku.jar
heroku-api/src/main/java/com/heroku/api/request/addon/AddonList.java
[ "public class Addon implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n String name;\n String description;\n URL url;\n String state;\n String id;\n Plan plan;\n\n public Plan getPlan() {\n return plan;\n }\n\n public void setPlan(Plan plan) {\n this.plan = plan;\n }\n\n public String getId() {\n return id;\n }\n\n private void setId(String id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n private void setName(String name) {\n this.name = name;\n }\n\n public String getDescription() {\n return description;\n }\n\n private void setDescription(String description) {\n this.description = description;\n }\n\n public URL getUrl() {\n return url;\n }\n\n private void setUrl(URL url) {\n this.url = url;\n }\n\n public String getState() {\n return state;\n }\n\n private void setState(String state) {\n this.state = state;\n }\n\n public static class Plan implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n String id;\n\n String name;\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n }\n}", "public class Heroku {\n\n\n public enum Config {\n ENDPOINT(\"HEROKU_HOST\", \"heroku.host\", \"heroku.com\");\n public final String environmentVariable;\n public final String systemProperty;\n public final String defaultValue;\n public final String value;\n\n Config(String environmentVariable, String systemProperty, String defaultValue) {\n this.environmentVariable = environmentVariable;\n this.systemProperty = systemProperty;\n this.defaultValue = defaultValue;\n String envVal = System.getenv(environmentVariable);\n String configVal = System.getProperty(systemProperty, envVal == null ? defaultValue : envVal);\n this.value = configVal.matches(\"^https?:\\\\/\\\\/.*\") ? configVal : \"https://api.\" + configVal;\n }\n\n public boolean isDefault() {\n return defaultValue.equals(value);\n }\n\n }\n\n public static enum JarProperties {\n ;\n\n static final Properties properties = new Properties();\n\n static {\n try {\n InputStream jarProps = JarProperties.class.getResourceAsStream(\"/heroku.jar.properties\");\n properties.load(jarProps);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n \n public static String getProperty(String propName) {\n return properties.getProperty(propName);\n }\n\n public static Properties getProperties() {\n return properties;\n }\n }\n\n public static SSLContext herokuSSLContext() {\n return sslContext(Config.ENDPOINT.isDefault());\n }\n\n public static SSLContext sslContext(boolean verify) {\n try {\n SSLContext ctx = SSLContext.getInstance(\"TLS\");\n TrustManager[] tmgrs = null;\n if (!verify) {\n tmgrs = trustAllTrustManagers();\n }\n /*\nInitializes this context.\nEither of the first two parameters may be null in which case the installed security providers will be searched\nfor the highest priority implementation of the appropriate factory.\nLikewise, the secure random parameter may be null in which case the default implementation will be used.\n */\n ctx.init(null, tmgrs, null);\n return ctx;\n } catch (NoSuchAlgorithmException e) {\n throw new HerokuAPIException(\"NoSuchAlgorithmException while trying to setup SSLContext\", e);\n } catch (KeyManagementException e) {\n throw new HerokuAPIException(\"KeyManagementException while trying to setup SSLContext\", e);\n }\n }\n\n public static HostnameVerifier hostnameVerifier(boolean verify) {\n HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();\n if (!verify) {\n verifier = new HostnameVerifier() {\n @Override\n public boolean verify(String s, SSLSession sslSession) {\n return true;\n }\n };\n }\n return verifier;\n }\n\n public static HostnameVerifier herokuHostnameVerifier() {\n return hostnameVerifier(Config.ENDPOINT.isDefault());\n }\n\n public static enum ResponseKey {\n Name(\"name\"),\n DomainName(\"domain_name\"),\n CreateStatus(\"create_status\"),\n Stack(\"stack\"),\n SlugSize(\"slug_size\"),\n RequestedStack(\"requested_stack\"),\n CreatedAt(\"created_at\"),\n WebUrl(\"web_url\"),\n RepoMigrateStatus(\"repo_migrate_status\"),\n Id(\"id\"),\n GitUrl(\"git_url\"),\n RepoSize(\"repo_size\"),\n Dynos(\"dynos\"),\n Workers(\"workers\");\n\n public final String value;\n \n // From Effective Java, Second Edition\n private static final Map<String, ResponseKey> stringToResponseKey = new HashMap<String, ResponseKey>();\n static {\n for (ResponseKey key : values())\n stringToResponseKey.put(key.toString(), key);\n }\n \n ResponseKey(String value) {\n this.value = value;\n }\n\n @Override\n public String toString() {\n return value;\n }\n \n public static ResponseKey fromString(String keyName) {\n return stringToResponseKey.get(keyName);\n }\n }\n\n public static enum RequestKey {\n Slug(\"slug\"),\n StackName(\"name\"),\n Stack(\"stack\"),\n AppMaintenance(\"maintenance\"),\n AddonName(\"addon\"),\n AddonPlan(\"plan\"),\n AddonConfig(\"config\"),\n AddonAttachment(\"attachment\"),\n AddonAttachmentName(\"name\"),\n AppName(\"name\"),\n SSHKey(\"public_key\"),\n Collaborator(\"user\"),\n TransferAppName(\"app\"),\n TransferOwner(\"recipient\"),\n Release(\"release\"),\n CreateDomain(\"hostname\"),\n DeleteDomain(\"hostname\"),\n ProcessTypes(\"process_types\"),\n Dyno(\"dyno\"),\n LogLines(\"lines\"),\n LogSource(\"source\"),\n LogTail(\"tail\"),\n SourceBlob(\"source_blob\"),\n SourceBlobUrl(\"url\"),\n SourceBlobChecksum(\"checksum\"),\n SourceBlobVersion(\"version\"),\n Buildpacks(\"buildpacks\"),\n BuildpackUrl(\"url\"),\n Space(\"space\"),\n SpaceId(\"id\"),\n SpaceName(\"name\"),\n SpaceShield(\"shield\"),\n Quantity(\"quantity\"),\n Team(\"team\"),\n TeamName(\"name\");\n\n public final String queryParameter;\n\n RequestKey(String queryParameter) {\n this.queryParameter = queryParameter;\n }\n }\n\n\n public static enum Stack {\n Cedar14(\"cedar-14\"),\n Container(\"container\"),\n Heroku16(\"heroku-16\"),\n Heroku18(\"heroku-18\");\n\n public final String value;\n\n // From Effective Java, Second Edition\n private static final Map<String, Stack> stringToEnum = new HashMap<String, Stack>();\n static {\n for (Stack s : values())\n stringToEnum.put(s.toString(), s);\n }\n\n Stack(String value) {\n this.value = value;\n }\n\n @Override\n public String toString() {\n return value;\n }\n\n public static Stack fromString(String stackName) {\n return stringToEnum.get(stackName);\n }\n }\n\n\n public static enum Resource {\n Apps(\"/apps\"),\n App(\"/apps/%s\"),\n AppTransfer(\"/account/app-transfers\"),\n Addons(\"/addons\"),\n AppAddons(App.value + \"/addons\"),\n AppAddon(AppAddons.value + \"/%s\"),\n Builds(\"/apps/%s/builds\"),\n BuildInfo(\"/apps/%s/builds/%s\"),\n BuildResult(\"/apps/%s/builds/%s/result\"),\n User(\"/account\"),\n Key(User.value + \"/keys/%s\"),\n Keys(User.value + \"/keys\"),\n Collaborators(App.value + \"/collaborators\"),\n Collaborator(Collaborators.value + \"/%s\"),\n ConfigVars(App.value + \"/config-vars\"),\n Logs(App.value + \"/log-sessions\"),\n Process(App.value + \"/ps\"),\n Restart(Process.value + \"/restart\"),\n Stop(Process.value + \"/stop\"),\n Scale(Process.value + \"/scale\"),\n Releases(App.value + \"/releases\"),\n Release(Releases.value + \"/%s\"),\n Slugs(App.value + \"/slugs\"),\n Slug(Slugs.value + \"/%s\"),\n Sources(\"/sources\"),\n Status(App.value + \"/status\"),\n Stacks(\"/stacks\"),\n Domains(App.value + \"/domains\"),\n Domain(Domains.value + \"/%s\"),\n Dynos(\"/apps/%s/dynos\"),\n Dyno(Dynos.value + \"/%s\"),\n Formations(App.value + \"/formation\"),\n Formation(Formations.value + \"/%s\"),\n BuildpackInstalltions(\"/apps/%s/buildpack-installations\"),\n TeamApps(\"/teams/%s/apps\"),\n TeamAppsAll(\"/teams/apps\"),\n TeamApp(\"/teams/apps/%s\"),\n Team(\"/teams/%s\"),\n Teams(\"/teams\"),\n TeamInvoices(\"/teams/%s/invoices\"),\n TeamInvoice(\"/teams/%s/invoices/%s\"),;\n\n public final String value;\n\n Resource(String value) {\n this.value = value;\n }\n\n public String format(String... values) {\n return String.format(value, values);\n }\n }\n\n public enum ApiVersion implements Http.Header {\n\n v2(2), v3(3);\n\n public static final String HEADER = \"Accept\";\n\n public final int version;\n\n ApiVersion(int version) {\n this.version = version;\n }\n\n @Override\n public String getHeaderName() {\n return HEADER;\n }\n\n @Override\n public String getHeaderValue() {\n return \"application/vnd.heroku+json; version=\" + Integer.toString(version);\n }\n }\n\n public static TrustManager[] trustAllTrustManagers() {\n return new TrustManager[]{new X509TrustManager() {\n @Override\n public void checkClientTrusted(final X509Certificate[] chain, final String authType) {\n }\n\n @Override\n public void checkServerTrusted(final X509Certificate[] chain, final String authType) {\n }\n\n @Override\n public X509Certificate[] getAcceptedIssuers() {\n return null;\n }\n }};\n }\n}", "public class RequestFailedException extends HerokuAPIException {\n\n String responseBody;\n int statusCode;\n\n public RequestFailedException(String msg, int code, byte[] in) {\n this(msg, code, getBodyFromInput(in));\n\n }\n\n private static String getBodyFromInput(byte[] in) {\n try {\n return HttpUtil.getUTF8String(in);\n } catch (Exception e) {\n return \"There was also an error reading the response body.\";\n }\n }\n\n public RequestFailedException(String msg, int code, String body) {\n super(msg + \" statuscode:\" + code + \" responseBody:\" + body);\n responseBody = body;\n statusCode = code;\n }\n\n\n public String getResponseBody() {\n return responseBody;\n }\n\n public int getStatusCode() {\n return statusCode;\n }\n}", "public class Http {\n /**\n * HTTP Accept header model.\n */\n public static enum Accept implements Header {\n JSON(\"application/json\"),\n TEXT(\"text/plain\");\n\n private String value;\n static String ACCEPT = \"Accept\";\n\n Accept(String val) {\n this.value = val;\n }\n\n @Override\n public String getHeaderName() {\n return ACCEPT;\n }\n\n @Override\n public String getHeaderValue() {\n return value;\n }\n\n }\n\n /**\n * HTTP Content-Type header model.\n */\n public static enum ContentType implements Header {\n JSON(\"application/json\"),\n FORM_URLENCODED(\"application/x-www-form-urlencoded\"),\n SSH_AUTHKEY(\"text/ssh-authkey\");\n\n private String value;\n static String CONTENT_TYPE = \"Content-Type\";\n\n ContentType(String val) {\n this.value = val;\n }\n\n @Override\n public String getHeaderName() {\n return CONTENT_TYPE;\n }\n\n @Override\n public String getHeaderValue() {\n return value;\n }\n\n }\n\n /**\n * HTTP User-Agent header model.\n *\n * @see UserAgentValueProvider\n */\n public static enum UserAgent implements Header {\n LATEST(loadValueProvider());\n\n static final String USER_AGENT = \"User-Agent\";\n private final UserAgentValueProvider userAgentValueProvider;\n\n UserAgent(UserAgentValueProvider userAgentValueProvider) {\n this.userAgentValueProvider = userAgentValueProvider;\n }\n\n @Override\n public String getHeaderName() {\n return USER_AGENT;\n }\n\n @Override\n public String getHeaderValue() {\n return userAgentValueProvider.getHeaderValue();\n }\n\n public String getHeaderValue(String customPart) {\n return userAgentValueProvider.getHeaderValue(customPart);\n }\n\n private static UserAgentValueProvider loadValueProvider() {\n final Iterator<UserAgentValueProvider> customProviders =\n ServiceLoader.load(UserAgentValueProvider.class, UserAgent.class.getClassLoader()).iterator();\n\n if (customProviders.hasNext()) {\n return customProviders.next();\n } else {\n return new UserAgentValueProvider.DEFAULT();\n }\n }\n }\n\n /**\n * Represent a name/value pair for a HTTP header. Not all are implemented. Only those used by the Heroku API.\n */\n public static interface Header {\n\n public static class Util {\n public static Map<String, String> setHeaders(Header... headers) {\n Map<String, String> headerMap = new HashMap<String, String>();\n for (Header h : headers) {\n headerMap.put(h.getHeaderName(), h.getHeaderValue());\n }\n return headerMap;\n }\n }\n\n String getHeaderName();\n\n String getHeaderValue();\n\n }\n\n /**\n * HTTP Methods. Not all are implemented. Only those used by the Heroku API.\n */\n public static enum Method {GET, PUT, POST, DELETE, PATCH}\n\n /**\n * HTTP Status codes. Not all are implemented. Only those used by the Heroku API.\n */\n public static enum Status {\n OK(200), CREATED(201), ACCEPTED(202), PAYMENT_REQUIRED(402), FORBIDDEN(403), NOT_FOUND(404), UNPROCESSABLE_ENTITY(422), INTERNAL_SERVER_ERROR(500), SERVICE_UNAVAILABLE(503);\n\n public final int statusCode;\n\n Status(int statusCode) {\n this.statusCode = statusCode;\n }\n\n public boolean equals(int code) {\n return statusCode == code;\n }\n }\n}", "public interface Request<T> {\n\n\n /**\n * HTTP method. e.g. GET, POST, PUT, DELETE\n * @return The HTTP method used in the request.\n */\n Http.Method getHttpMethod();\n\n /**\n * Path and query parameters of a URL.\n * @return The path and query parameters as a String.\n */\n String getEndpoint();\n\n /**\n * Whether or not the request has a body.\n * @return true if it has a request body, otherwise false\n */\n boolean hasBody();\n\n /**\n * Value of the request body.\n * @return Body\n * @throws UnsupportedOperationException Generally thrown if {@link #hasBody()} returns false\n */\n String getBody();\n\n /**\n * Value of the request body as a Map.\n * @return Body\n * @throws UnsupportedOperationException Generally thrown if {@link #hasBody()} returns false\n */\n Map<String, ?> getBodyAsMap();\n\n /**\n * HTTP Accept header.\n * @return The Accept header to be used in the request. Typically \"application/json\" or \"text/xml\"\n * @see com.heroku.api.http.Http.Accept\n */\n Http.Accept getResponseType();\n\n /**\n * {@link Map} of request-specific HTTP headers.\n * @return Name/value pairs of HTTP headers.\n */\n Map<String, String> getHeaders();\n\n /**\n * Response handler.\n * @param bytes Data returned from the request.\n * @param status HTTP status code.\n * @return The type {@link T} as specified by an individual request.\n * @throws com.heroku.api.exception.RequestFailedException Generally thrown when the HTTP status code is 4XX.\n */\n T getResponse(byte[] bytes, int status, Map<String,String> headers);\n\n}", "public static UnsupportedOperationException noBody() {\n return new UnsupportedOperationException(\"This request does not have a body. Use hasBody() to check for a body.\");\n}", "public static <T> T parse(byte[] data, Type type) {\n return Holder.parser.parse(data, type);\n}" ]
import com.heroku.api.Addon; import com.heroku.api.Heroku; import com.heroku.api.exception.RequestFailedException; import com.heroku.api.http.Http; import com.heroku.api.request.Request; import java.util.Collections; import java.util.List; import java.util.Map; import static com.heroku.api.http.HttpUtil.noBody; import static com.heroku.api.parser.Json.parse;
package com.heroku.api.request.addon; /** * TODO: Javadoc * * @author Naaman Newbold */ public class AddonList implements Request<List<Addon>> { @Override public Http.Method getHttpMethod() { return Http.Method.GET; } @Override public String getEndpoint() { return Heroku.Resource.Addons.value; } @Override public boolean hasBody() { return false; } @Override public String getBody() {
throw noBody();
5
Tonius/SimplyJetpacks
src/main/java/tonius/simplyjetpacks/handler/LivingTickHandler.java
[ "public static class ItemJetpack extends ItemPack<Jetpack> {\n \n public ItemJetpack(ModType modType, String registryName) {\n super(modType, registryName);\n }\n \n}", "public class Jetpack extends PackBase {\n \n protected static final String TAG_HOVERMODE_ON = \"JetpackHoverModeOn\";\n protected static final String TAG_EHOVER_ON = \"JetpackEHoverOn\";\n protected static final String TAG_PARTICLE = \"JetpackParticleType\";\n \n public double speedVertical = 0.0D;\n public double accelVertical = 0.0D;\n public double speedVerticalHover = 0.0D;\n public double speedVerticalHoverSlow = 0.0D;\n public double speedSideways = 0.0D;\n public double sprintSpeedModifier = 0.0D;\n public double sprintFuelModifier = 0.0D;\n public boolean emergencyHoverMode = false;\n \n public ParticleType defaultParticleType = ParticleType.DEFAULT;\n \n public Jetpack(int tier, EnumRarity rarity, String defaultConfigKey) {\n super(\"jetpack\", tier, rarity, defaultConfigKey);\n this.setArmorModel(PackModelType.JETPACK);\n }\n \n public Jetpack setDefaultParticleType(ParticleType defaultParticleType) {\n this.defaultParticleType = defaultParticleType;\n return this;\n }\n \n @Override\n public void tickArmor(World world, EntityPlayer player, ItemStack stack, ItemPack item) {\n this.flyUser(player, stack, item, false);\n }\n \n public void flyUser(EntityLivingBase user, ItemStack stack, ItemPack item, boolean force) {\n if (this.isOn(stack)) {\n boolean hoverMode = this.isHoverModeOn(stack);\n double hoverSpeed = Config.invertHoverSneakingBehavior == SyncHandler.isDescendKeyDown(user) ? this.speedVerticalHoverSlow : this.speedVerticalHover;\n boolean flyKeyDown = force || SyncHandler.isFlyKeyDown(user);\n boolean descendKeyDown = SyncHandler.isDescendKeyDown(user);\n double currentAccel = this.accelVertical * (user.motionY < 0.3D ? 2.5D : 1.0D);\n double currentSpeedVertical = this.speedVertical * (user.isInWater() ? 0.4D : 1.0D);\n \n if (flyKeyDown || hoverMode && !user.onGround) {\n if (this.usesFuel) {\n item.useFuel(stack, (int) (user.isSprinting() ? Math.round(this.getFuelUsage(stack) * this.sprintFuelModifier) : this.getFuelUsage(stack)), false);\n }\n \n if (item.getFuelStored(stack) > 0) {\n if (flyKeyDown) {\n if (!hoverMode) {\n user.motionY = Math.min(user.motionY + currentAccel, currentSpeedVertical);\n } else {\n if (descendKeyDown) {\n user.motionY = Math.min(user.motionY + currentAccel, -this.speedVerticalHoverSlow);\n } else {\n user.motionY = Math.min(user.motionY + currentAccel, this.speedVerticalHover);\n }\n }\n } else {\n user.motionY = Math.min(user.motionY + currentAccel, -hoverSpeed);\n }\n \n float speedSideways = (float) (user.isSneaking() ? this.speedSideways * 0.5F : this.speedSideways);\n float speedForward = (float) (user.isSprinting() ? speedSideways * this.sprintSpeedModifier : speedSideways);\n if (SyncHandler.isForwardKeyDown(user)) {\n user.moveFlying(0, speedForward, speedForward);\n }\n if (SyncHandler.isBackwardKeyDown(user)) {\n user.moveFlying(0, -speedSideways, speedSideways * 0.8F);\n }\n if (SyncHandler.isLeftKeyDown(user)) {\n user.moveFlying(speedSideways, 0, speedSideways);\n }\n if (SyncHandler.isRightKeyDown(user)) {\n user.moveFlying(-speedSideways, 0, speedSideways);\n }\n \n if (!user.worldObj.isRemote) {\n user.fallDistance = 0.0F;\n if (user instanceof EntityPlayerMP) {\n ((EntityPlayerMP) user).playerNetServerHandler.floatingTickCount = 0;\n }\n \n if (Config.flammableFluidsExplode) {\n if (!(user instanceof EntityPlayer) || !((EntityPlayer) user).capabilities.isCreativeMode) {\n int x = Math.round((float) user.posX - 0.5F);\n int y = Math.round((float) user.posY);\n int z = Math.round((float) user.posZ - 0.5F);\n Block fluidBlock = user.worldObj.getBlock(x, y, z);\n if (fluidBlock instanceof IFluidBlock && fluidBlock.isFlammable(user.worldObj, x, y, z, ForgeDirection.UNKNOWN)) {\n user.worldObj.playSoundAtEntity(user, \"mob.ghast.fireball\", 2.0F, 1.0F);\n user.worldObj.createExplosion(user, user.posX, user.posY, user.posZ, 3.5F, false);\n user.attackEntityFrom(new EntityDamageSource(\"jetpackexplode\", user), 100.0F);\n }\n }\n }\n }\n }\n }\n }\n \n if (!user.worldObj.isRemote && this.emergencyHoverMode && this.isEHoverOn(stack)) {\n if (item.getEnergyStored(stack) > 0 && (!this.isHoverModeOn(stack) || !this.isOn(stack))) {\n if (user.posY < -5) {\n this.doEHover(stack, user);\n } else if (user instanceof EntityPlayer) {\n if (!((EntityPlayer) user).capabilities.isCreativeMode && user.fallDistance - 1.2F >= user.getHealth()) {\n for (int i = 0; i <= 16; i++) {\n int x = Math.round((float) user.posX - 0.5F);\n int y = Math.round((float) user.posY) - i;\n int z = Math.round((float) user.posZ - 0.5F);\n if (!user.worldObj.isAirBlock(x, y, z)) {\n this.doEHover(stack, user);\n break;\n }\n }\n }\n }\n }\n }\n }\n \n protected int getFuelUsage(ItemStack stack) {\n if (ModEnchantments.fuelEffeciency == null) {\n return this.fuelUsage;\n }\n \n int fuelEfficiencyLevel = MathHelper.clampI(EnchantmentHelper.getEnchantmentLevel(ModEnchantments.fuelEffeciency.effectId, stack), 0, 4);\n return (int) Math.round(this.fuelUsage * (20 - fuelEfficiencyLevel) / 20.0D);\n }\n \n public void doEHover(ItemStack armor, EntityLivingBase user) {\n NBTHelper.getNBT(armor).setBoolean(TAG_ON, true);\n NBTHelper.getNBT(armor).setBoolean(TAG_HOVERMODE_ON, true);\n if (user instanceof EntityPlayer) {\n ((EntityPlayer) user).addChatMessage(new ChatComponentText(StringHelper.LIGHT_RED + SJStringHelper.localize(\"chat.jetpack.emergencyHoverMode.msg\")));\n }\n }\n \n public void setMobMode(ItemStack itemStack) {\n itemStack.stackTagCompound.setBoolean(TAG_ON, true);\n itemStack.stackTagCompound.setBoolean(TAG_HOVERMODE_ON, false);\n }\n \n public boolean isHoverModeOn(ItemStack stack) {\n return NBTHelper.getNBTBoolean(stack, TAG_HOVERMODE_ON, false);\n }\n \n public boolean isEHoverOn(ItemStack stack) {\n return NBTHelper.getNBTBoolean(stack, TAG_EHOVER_ON, true);\n }\n \n @Override\n public void switchModePrimary(ItemStack stack, EntityPlayer player, boolean showInChat) {\n this.switchHoverMode(stack, player, showInChat);\n }\n \n @Override\n public void switchModeSecondary(ItemStack stack, EntityPlayer player, boolean showInChat) {\n if (this.emergencyHoverMode) {\n this.switchEHover(stack, player, showInChat);\n }\n }\n \n protected void switchHoverMode(ItemStack stack, EntityPlayer player, boolean showInChat) {\n this.toggleState(this.isHoverModeOn(stack), stack, \"hoverMode\", TAG_HOVERMODE_ON, player, showInChat);\n }\n \n public void switchEHover(ItemStack stack, EntityPlayer player, boolean showInChat) {\n this.toggleState(this.isEHoverOn(stack), stack, \"emergencyHoverMode\", TAG_EHOVER_ON, player, showInChat);\n }\n \n public void setParticleType(ItemStack stack, ParticleType particle) {\n NBTHelper.getNBT(stack).setInteger(TAG_PARTICLE, particle.ordinal());\n }\n \n protected ParticleType getParticleType(ItemStack stack) {\n if (stack.stackTagCompound != null && stack.stackTagCompound.hasKey(TAG_PARTICLE)) {\n int particle = NBTHelper.getNBT(stack).getInteger(TAG_PARTICLE);\n ParticleType particleType = ParticleType.values()[particle];\n if (particleType != null) {\n return particleType;\n }\n }\n NBTHelper.getNBT(stack).setInteger(TAG_PARTICLE, this.defaultParticleType.ordinal());\n return this.defaultParticleType;\n }\n \n public ParticleType getDisplayParticleType(ItemStack stack, ItemPack item, EntityLivingBase user) {\n boolean flyKeyDown = SyncHandler.isFlyKeyDown(user);\n if (this.isOn(stack) && item.getFuelStored(stack) > 0 && (flyKeyDown || this.isHoverModeOn(stack) && !user.onGround && user.motionY < 0)) {\n return this.getParticleType(stack);\n }\n return null;\n }\n \n @Override\n public String getGuiTitlePrefix() {\n return \"gui.jetpack\";\n }\n \n @Override\n public ModKey[] getGuiControls() {\n if (this.emergencyHoverMode) {\n return new ModKey[] { ModKey.TOGGLE_PRIMARY, ModKey.MODE_PRIMARY, ModKey.MODE_SECONDARY };\n } else {\n return new ModKey[] { ModKey.TOGGLE_PRIMARY, ModKey.MODE_PRIMARY };\n }\n }\n \n @Override\n @SideOnly(Side.CLIENT)\n @SuppressWarnings(\"unchecked\")\n public void addShiftInformation(ItemStack stack, ItemPack item, EntityPlayer player, List list) {\n list.add(SJStringHelper.getStateText(this.isOn(stack)));\n list.add(SJStringHelper.getHoverModeText(this.isHoverModeOn(stack)));\n if (this.fuelType == FuelType.FLUID && this.fuelFluid != null) {\n list.add(SJStringHelper.getFuelFluidText(this.fuelFluid));\n }\n if (this.fuelUsage > 0) {\n list.add(SJStringHelper.getFuelUsageText(this.fuelType, this.getFuelUsage(stack)));\n }\n list.add(SJStringHelper.getParticlesText(this.getParticleType(stack)));\n SJStringHelper.addDescriptionLines(list, \"jetpack\", StringHelper.BRIGHT_GREEN);\n String key = SimplyJetpacks.proxy.getPackGUIKey();\n if (key != null) {\n list.add(SJStringHelper.getPackGUIText(key));\n }\n }\n \n @Override\n @SideOnly(Side.CLIENT)\n public String getHUDStatesInfo(ItemStack stack, ItemPack item) {\n Boolean engine = this.isOn(stack);\n Boolean hover = this.isHoverModeOn(stack);\n return SJStringHelper.getHUDStateText(engine, hover, null);\n }\n \n @Override\n protected void loadConfig(Configuration config) {\n super.loadConfig(config);\n \n if (this.defaults.speedVertical != null) {\n this.speedVertical = config.get(this.defaults.section.name, \"Vertical Speed\", this.defaults.speedVertical, \"The maximum vertical speed of this jetpack when flying.\").setMinValue(0.0D).getDouble(this.defaults.speedVertical);\n }\n if (this.defaults.accelVertical != null) {\n this.accelVertical = config.get(this.defaults.section.name, \"Vertical Acceleration\", this.defaults.accelVertical, \"The vertical acceleration of this jetpack when flying; every tick, this amount of vertical speed will be added until maximum speed is reached.\").setMinValue(0.0D).getDouble(this.defaults.accelVertical);\n }\n if (this.defaults.speedVerticalHover != null) {\n this.speedVerticalHover = config.get(this.defaults.section.name, \"Vertical Speed (Hover Mode)\", this.defaults.speedVerticalHover, \"The maximum vertical speed of this jetpack when flying in hover mode.\").setMinValue(0.0D).getDouble(this.defaults.speedVerticalHover);\n }\n if (this.defaults.speedVerticalHoverSlow != null) {\n this.speedVerticalHoverSlow = config.get(this.defaults.section.name, \"Vertical Speed (Hover Mode / Slow Descent)\", this.defaults.speedVerticalHoverSlow, \"The maximum vertical speed of this jetpack when slowly descending in hover mode.\").setMinValue(0.0D).getDouble(this.defaults.speedVerticalHoverSlow);\n }\n if (this.defaults.speedSideways != null) {\n this.speedSideways = config.get(this.defaults.section.name, \"Sideways Speed\", this.defaults.speedSideways, \"The speed of this jetpack when flying sideways. This is mostly noticeable in hover mode.\").setMinValue(0.0D).getDouble(this.defaults.speedSideways);\n }\n if (this.defaults.sprintSpeedModifier != null) {\n this.sprintSpeedModifier = config.get(this.defaults.section.name, \"Sprint Speed Multiplier\", this.defaults.sprintSpeedModifier, \"How much faster this jetpack will fly forward when sprinting. Setting this to 1.0 will make sprinting have no effect apart from the added speed from vanilla.\").setMinValue(0.0D).getDouble(this.defaults.sprintSpeedModifier);\n }\n if (this.defaults.sprintFuelModifier != null) {\n this.sprintFuelModifier = config.get(this.defaults.section.name, \"Sprint Fuel Usage Multiplier\", this.defaults.sprintFuelModifier, \"How much more energy this jetpack will use when sprinting. Setting this to 1.0 will make sprinting have no effect on energy usage.\").setMinValue(0.0D).getDouble(this.defaults.sprintFuelModifier);\n }\n if (this.defaults.emergencyHoverMode != null) {\n this.emergencyHoverMode = config.get(this.defaults.section.name, \"Emergency Hover Mode\", this.defaults.emergencyHoverMode, \"When enabled, this jetpack will activate hover mode automatically when the wearer is about to die from a fall.\").getBoolean(this.defaults.emergencyHoverMode);\n }\n }\n \n @Override\n protected void writeConfigToNBT(NBTTagCompound tag) {\n super.writeConfigToNBT(tag);\n \n if (this.defaults.speedVertical != null) {\n tag.setDouble(\"SpeedVertical\", this.speedVertical);\n }\n if (this.defaults.accelVertical != null) {\n tag.setDouble(\"AccelVertical\", this.accelVertical);\n }\n if (this.defaults.speedVerticalHover != null) {\n tag.setDouble(\"SpeedVerticalHover\", this.speedVerticalHover);\n }\n if (this.defaults.speedVerticalHoverSlow != null) {\n tag.setDouble(\"SpeedVerticalHoverSlow\", this.speedVerticalHoverSlow);\n }\n if (this.defaults.speedSideways != null) {\n tag.setDouble(\"SpeedSideways\", this.speedSideways);\n }\n if (this.defaults.sprintSpeedModifier != null) {\n tag.setDouble(\"SprintSpeedModifier\", this.sprintSpeedModifier);\n }\n if (this.defaults.sprintFuelModifier != null) {\n tag.setDouble(\"SprintFuelModifier\", this.sprintFuelModifier);\n }\n if (this.defaults.emergencyHoverMode != null) {\n tag.setBoolean(\"EmergencyHoverMode\", this.emergencyHoverMode);\n }\n }\n \n @Override\n protected void readConfigFromNBT(NBTTagCompound tag) {\n super.readConfigFromNBT(tag);\n \n if (this.defaults.speedVertical != null) {\n this.speedVertical = tag.getDouble(\"SpeedVertical\");\n }\n if (this.defaults.accelVertical != null) {\n this.accelVertical = tag.getDouble(\"AccelVertical\");\n }\n if (this.defaults.speedVerticalHover != null) {\n this.speedVerticalHover = tag.getDouble(\"SpeedVerticalHover\");\n }\n if (this.defaults.speedVerticalHoverSlow != null) {\n this.speedVerticalHoverSlow = tag.getDouble(\"SpeedVerticalHoverSlow\");\n }\n if (this.defaults.speedSideways != null) {\n this.speedSideways = tag.getDouble(\"SpeedSideways\");\n }\n if (this.defaults.sprintSpeedModifier != null) {\n this.sprintSpeedModifier = tag.getDouble(\"SprintSpeedModifier\");\n }\n if (this.defaults.sprintFuelModifier != null) {\n this.sprintFuelModifier = tag.getDouble(\"SprintFuelModifier\");\n }\n if (this.defaults.emergencyHoverMode != null) {\n this.emergencyHoverMode = tag.getBoolean(\"EmergencyHoverMode\");\n }\n }\n \n}", "public class JetpackPotato extends Jetpack {\n \n protected static final String TAG_FIRED = \"JetpackPotatoFired\";\n protected static final String TAG_ROCKET_TIMER = \"JetpackPotatoRocketTimer\";\n protected static final String TAG_ROCKET_TIMER_SET = \"JetpackPotatoRocketTimerSet\";\n \n public JetpackPotato(int tier, EnumRarity rarity, String defaultConfigKey) {\n super(tier, rarity, defaultConfigKey);\n this.setHasStateIndicators(false);\n this.setShowEmptyInCreativeTab(false);\n this.setArmorModel(PackModelType.FLAT);\n }\n \n @Override\n public void flyUser(EntityLivingBase user, ItemStack stack, ItemPack item, boolean force) {\n if (this.isFired(stack)) {\n super.flyUser(user, stack, item, true);\n user.rotationYawHead += 37.5F;\n if (item.getFuelStored(stack) <= 0) {\n user.setCurrentItemOrArmor(3, null);\n if (!user.worldObj.isRemote) {\n user.worldObj.createExplosion(user, user.posX, user.posY, user.posZ, 4.0F, false);\n for (int i = 0; i <= MathHelper.RANDOM.nextInt(3) + 4; i++) {\n ItemStack firework = FireworksHelper.getRandomFireworks(0, 1, MathHelper.RANDOM.nextInt(6) + 1, 1);\n user.worldObj.spawnEntityInWorld(new EntityFireworkRocket(user.worldObj, user.posX + MathHelper.RANDOM.nextDouble() * 6.0D - 3.0D, user.posY, user.posZ + MathHelper.RANDOM.nextDouble() * 6.0D - 3.0D, firework));\n }\n user.attackEntityFrom(new EntityDamageSource(\"jetpackpotato\", user), 100.0F);\n if (user instanceof EntityPlayer) {\n user.dropItem(Items.baked_potato, 1);\n }\n }\n }\n } else {\n if (force || SyncHandler.isFlyKeyDown(user)) {\n if (this.isTimerSet(stack)) {\n this.decrementTimer(stack, user);\n } else {\n this.setTimer(stack, 50);\n }\n }\n }\n }\n \n @Override\n public boolean isOn(ItemStack stack) {\n return true;\n }\n \n @Override\n public boolean isHoverModeOn(ItemStack stack) {\n return false;\n }\n \n @Override\n public void togglePrimary(ItemStack stack, EntityPlayer player, boolean showInChat) {\n }\n \n @Override\n public void switchModePrimary(ItemStack stack, EntityPlayer player, boolean showInChat) {\n }\n \n @Override\n public ModKey[] getGuiControls() {\n return new ModKey[0];\n }\n \n @Override\n public ParticleType getDisplayParticleType(ItemStack itemStack, ItemPack item, EntityLivingBase user) {\n if (!this.isFired(itemStack) && SyncHandler.isFlyKeyDown(user)) {\n return user.getRNG().nextInt(5) == 0 ? ParticleType.SMOKE : null;\n } else if (this.isFired(itemStack)) {\n return this.getParticleType(itemStack);\n }\n return null;\n }\n \n @Override\n @SideOnly(Side.CLIENT)\n @SuppressWarnings(\"unchecked\")\n public void addShiftInformation(ItemStack stack, ItemPack item, EntityPlayer player, List list) {\n super.addShiftInformation(stack, item, player, list);\n list.add(StringHelper.LIGHT_RED + StringHelper.ITALIC + SJStringHelper.localize(\"tooltip.jetpackPotato.warning\"));\n }\n \n protected boolean isFired(ItemStack itemStack) {\n return NBTHelper.getNBT(itemStack).getBoolean(TAG_FIRED);\n }\n \n protected void setFired(ItemStack itemStack) {\n NBTHelper.getNBT(itemStack).setBoolean(TAG_FIRED, true);\n }\n \n protected void setTimer(ItemStack itemStack, int timer) {\n NBTHelper.getNBT(itemStack).setInteger(TAG_ROCKET_TIMER, timer);\n NBTHelper.getNBT(itemStack).setBoolean(TAG_ROCKET_TIMER_SET, true);\n }\n \n protected boolean isTimerSet(ItemStack itemStack) {\n return NBTHelper.getNBT(itemStack).getBoolean(TAG_ROCKET_TIMER_SET);\n }\n \n protected void decrementTimer(ItemStack itemStack, EntityLivingBase user) {\n int timer = NBTHelper.getNBT(itemStack).getInteger(TAG_ROCKET_TIMER);\n timer = timer > 0 ? timer - 1 : 0;\n NBTHelper.getNBT(itemStack).setInteger(TAG_ROCKET_TIMER, timer);\n if (timer == 0) {\n this.setFired(itemStack);\n user.worldObj.playSoundAtEntity(user, SimplyJetpacks.RESOURCE_PREFIX + \"rocket\", 1.0F, 1.0F);\n }\n }\n \n}", "public abstract class PacketHandler {\n \n public static final SimpleNetworkWrapper instance = NetworkRegistry.INSTANCE.newSimpleChannel(\"SimplyJetpacks\");\n \n public static void init() {\n SimplyJetpacks.logger.info(\"Registering network messages\");\n instance.registerMessage(MessageJetpackSync.class, MessageJetpackSync.class, 0, Side.CLIENT);\n instance.registerMessage(MessageConfigSync.class, MessageConfigSync.class, 1, Side.CLIENT);\n instance.registerMessage(MessageKeyboardSync.class, MessageKeyboardSync.class, 2, Side.SERVER);\n instance.registerMessage(MessageModKey.class, MessageModKey.class, 3, Side.SERVER);\n }\n}", "public class MessageJetpackSync implements IMessage, IMessageHandler<MessageJetpackSync, IMessage> {\n \n public int entityId;\n public int particleId;\n \n public MessageJetpackSync() {\n }\n \n public MessageJetpackSync(int entityId, int particleId) {\n this.entityId = entityId;\n this.particleId = particleId;\n }\n \n @Override\n public void fromBytes(ByteBuf buf) {\n this.entityId = buf.readInt();\n this.particleId = buf.readInt();\n }\n \n @Override\n public void toBytes(ByteBuf buf) {\n buf.writeInt(this.entityId);\n buf.writeInt(this.particleId);\n }\n \n @Override\n public IMessage onMessage(MessageJetpackSync msg, MessageContext ctx) {\n Entity entity = FMLClientHandler.instance().getClient().theWorld.getEntityByID(msg.entityId);\n if (entity != null && entity instanceof EntityLivingBase && entity != FMLClientHandler.instance().getClient().thePlayer) {\n if (msg.particleId >= 0) {\n ParticleType particle = ParticleType.values()[msg.particleId];\n SyncHandler.processJetpackUpdate(msg.entityId, particle);\n } else {\n SyncHandler.processJetpackUpdate(msg.entityId, null);\n }\n }\n return null;\n }\n}", "public enum ParticleType {\n DEFAULT,\n NONE,\n SMOKE,\n RAINBOW_SMOKE,\n BUBBLE\n}" ]
import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import net.minecraft.entity.monster.EntityMob; import net.minecraft.item.ItemStack; import net.minecraft.util.DamageSource; import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent; import tonius.simplyjetpacks.item.ItemPack.ItemJetpack; import tonius.simplyjetpacks.item.meta.Jetpack; import tonius.simplyjetpacks.item.meta.JetpackPotato; import tonius.simplyjetpacks.network.PacketHandler; import tonius.simplyjetpacks.network.message.MessageJetpackSync; import tonius.simplyjetpacks.setup.ParticleType; import cofh.lib.util.helpers.MathHelper; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.network.NetworkRegistry.TargetPoint;
package tonius.simplyjetpacks.handler; public class LivingTickHandler { private static final Map<Integer, ParticleType> lastJetpackState = new ConcurrentHashMap<Integer, ParticleType>(); @SubscribeEvent public void onLivingTick(LivingUpdateEvent evt) { if (!evt.entityLiving.worldObj.isRemote) { ParticleType jetpackState = null; ItemStack armor = evt.entityLiving.getEquipmentInSlot(3); Jetpack jetpack = null;
if (armor != null && armor.getItem() instanceof ItemJetpack) {
0
karthicks/gremlin-ogm
gremlin-objects/src/test/java/org/apache/tinkerpop/gremlin/object/reflect/PrimitivesTest.java
[ "public interface Graph {\n\n /**\n * Add an given {@link Vertex} to the graph.\n */\n <V extends Vertex> Graph addVertex(V vertex);\n\n /**\n * Remove the given {@link Vertex} from the graph.\n */\n <V extends Vertex> Graph removeVertex(V vertex);\n\n /**\n * Add an {@link Edge} from the current vertex to the vertex referenced by the given alias.\n */\n <E extends Edge,\n V extends Vertex> Graph addEdge(E edge, String toVertexAlias);\n\n /**\n * Add an {@link Edge} from the current vertex to the given {@link Vertex}\n */\n <E extends Edge,\n V extends Vertex> Graph addEdge(E edge, V toVertex);\n\n /**\n * Add an {@link Edge} from the given from and to vertices specified by their aliases.\n */\n <E extends Edge,\n V extends Vertex> Graph addEdge(E edge, String fromVertexAlias, String toVertexAlias);\n\n /**\n * Add an {@link Edge} between the given vertices.\n */\n <E extends Edge,\n V extends Vertex> Graph addEdge(E edge, V fromVertex, V toVertex);\n\n /**\n * Add an {@link Edge} form the aliased vertex to the given vertex.\n */\n <E extends Edge,\n V extends Vertex> Graph addEdge(E edge, String fromVertexAlias, V toVertex);\n\n /**\n * Add an {@link Edge} from the given vertex to the aliased vertex.\n */\n <E extends Edge,\n V extends Vertex> Graph addEdge(E edge, Vertex fromVertex, String toVertexAlias);\n\n /**\n * Add an {@link Edge} from the given vertex to the vertices returned by the {@link\n * AnyTraversal}.\n */\n <E extends Edge,\n V extends Vertex> Graph addEdge(E edge, Vertex fromVertex, AnyTraversal toAnyTraversal);\n\n /**\n * Add an {@link Edge} from the given vertex to the vertices returned by the {@link\n * SubTraversal}s.\n */\n <E extends Edge,\n V extends Vertex> Graph addEdge(E edge, Vertex fromVertex, SubTraversal... toVertexQueries);\n\n /**\n * Add an {@link Edge} to the vertices returned by the given {@link AnyTraversal}.\n */\n <E extends Edge> Graph addEdge(E edge, AnyTraversal toAnyTraversal);\n\n /**\n * Add an {@link Edge} to the vertices returned by the given {@link SubTraversal}s.\n */\n @SuppressWarnings(\"rawtypes\")\n <E extends Edge> Graph addEdge(E edge, SubTraversal... toVertexQueries);\n\n /**\n * Remove the given edge.\n */\n <E extends Edge> Graph removeEdge(E edge);\n\n /**\n * Get the {@link Element} tied to the given alias.\n *\n * This is a materialization of the element provided to this graph, and may not reflect what's\n * actually in the graph. To see the actual element, use the {@link Query} interface.\n */\n @SuppressWarnings({\"PMD.ShortMethodName\"})\n Graph as(String alias);\n\n /**\n * Supply the {@link Element} tied to the given consumer.\n *\n * This is a materialization of the element provided to this graph, and may not reflect what's\n * actually in the graph. To see the actual element, use the {@link Query} interface.\n */\n @SuppressWarnings({\"PMD.ShortMethodName\"})\n <E extends Element> Graph as(Consumer<E> consumer);\n\n /**\n * Get the last added {@link Element} in the form of the given type.\n *\n * This is a materialization of the element provided to this graph, and may not reflect what's\n * actually in the graph. To see the actual element, use the {@link Query} interface.\n */\n @SuppressWarnings({\"PMD.ShortMethodName\"})\n <E extends Element> E as(Class<E> elementType);\n\n /**\n * How {@link Should} the {@link Graph} try to add vertices and edges?\n */\n Graph should(Should should);\n\n /**\n * What is the {@link Should} mode currently set to?\n */\n Should should();\n\n /**\n * Should primitive required keys be allowed to have their primitive default values?\n */\n Graph defaultKeys(boolean allow);\n\n /**\n * Verify if the graph has the given feature.\n */\n boolean verify(HasFeature hasFeature);\n\n /**\n * Get the element of the given type stored against the given alias.\n */\n <E extends Element> E get(String alias, Class<E> elementType);\n\n /**\n * Return the associated {@link Query} instance.\n */\n Query query();\n\n /**\n * Drop the elements in the graph.\n */\n void drop();\n\n /**\n * Release the resources in the graph.\n */\n void close();\n\n /**\n * Reset the state of the graph, including any aliases, and element mappings.\n */\n void reset();\n\n /**\n * How should the graph add elements, considering that an element with that id or key might\n * already exist?\n */\n enum Should {\n /**\n * The default, which is to merge properties of the new and existing element, if any.\n */\n MERGE,\n /**\n * If it exists, replace all its (mutable) properties. Otherwise {@link #INSERT}.\n */\n REPLACE,\n /**\n * If the graph supports user ids, then {@link #INSERT}. Otherwise, {@link #MERGE}.\n */\n CREATE,\n /**\n * Add the element if and only if there is no existing element.\n */\n IGNORE,\n /**\n * Add the element, raising an exception if it already exists, and a key violation occurs.\n */\n INSERT;\n\n public String label() {\n return name().toLowerCase();\n }\n }\n\n /**\n * An interface that defines graph update events.\n */\n interface Observer {\n\n <V extends Vertex> void vertexAdded(V given, V stored);\n\n <V extends Vertex> void vertexRemoved(V given);\n\n <E extends Edge> void edgeAdded(E given, E stored);\n\n <E extends Edge> void edgeRemoved(E given);\n }\n\n /**\n * {@link Observer}s can register interest in the graph through this class.\n */\n @SuppressWarnings(\"PMD.ShortClassName\")\n class O extends Observable<Observer> {\n\n private static final O INSTANCE = new O();\n\n public static O get() {\n return INSTANCE;\n }\n }\n}", "public static Instant year(int value) {\n Instant instant = years.get(value);\n if (instant != null) {\n return instant;\n }\n instant = LocalDate.parse(String.format(\"%s-01-01\", value)).atStartOfDay()\n .toInstant(ZoneOffset.UTC);\n years.put(value, instant);\n return instant;\n}", "public static boolean isPrimitive(Field field) {\n return isPrimitive(field.getType());\n}", "public static boolean isTimeType(Class clazz) {\n return clazz.equals(Date.class) || clazz.equals(Instant.class) || clazz.equals(Long.class);\n}", "@SuppressWarnings(\"unchecked\")\npublic static <T> T toTimeType(Object timeValue, Class<T> targetTimeType) {\n Class valueClass = timeValue.getClass();\n Function<Object, Object> timeConverter =\n TIME_CONVERTERS.get(new Pair(valueClass, targetTimeType));\n if (timeConverter == null) {\n throw Element.Exceptions.invalidTimeType(targetTimeType, timeValue);\n }\n return (T) timeConverter.apply(timeValue);\n}" ]
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.apache.tinkerpop.gremlin.object.structure.Graph; import org.junit.Before; import org.junit.Test; import java.time.Instant; import java.util.Date; import java.util.Set; import static org.apache.tinkerpop.gremlin.object.vertices.Location.year; import static org.apache.tinkerpop.gremlin.object.reflect.Primitives.isPrimitive; import static org.apache.tinkerpop.gremlin.object.reflect.Primitives.isTimeType; import static org.apache.tinkerpop.gremlin.object.reflect.Primitives.toTimeType;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.tinkerpop.gremlin.object.reflect; /** * Assert that {@link Primitives} identifies the registered primitive types properly. It also tests * that time properties can be converted between compatible types. * * @author Karthick Sankarachary (http://github.com/karthicks) */ public class PrimitivesTest extends ReflectTest { private Instant now; @Before public void setUp() { now = year(2017); } @Test public void testIsPrimitiveType() { assertTrue(isPrimitive(String.class));
assertTrue(isPrimitive(Graph.Should.class));
0
bonigarcia/dualsub
src/test/java/io/github/bonigarcia/dualsub/test/TestSynchronization.java
[ "public class DualSrt {\n\n\tprivate static final Logger log = LoggerFactory.getLogger(DualSrt.class);\n\n\tprivate TreeMap<String, Entry[]> subtitles;\n\n\tprivate int signatureGap;\n\tprivate int signatureTime;\n\tprivate int gap;\n\tprivate int desync;\n\tprivate int extension;\n\tprivate boolean extend;\n\tprivate boolean progressive;\n\n\tprivate final String SPACE_HTML = \"&nbsp;\";\n\n\tpublic DualSrt(Properties properties, int desync, boolean extend,\n\t\t\tint extension, boolean progressive) {\n\t\tthis.extend = extend;\n\t\tthis.extension = extension;\n\t\tthis.progressive = progressive;\n\n\t\tthis.subtitles = new TreeMap<String, Entry[]>();\n\n\t\tthis.signatureGap = Integer\n\t\t\t\t.parseInt(properties.getProperty(\"signatureGap\")); // seconds\n\t\tthis.signatureTime = Integer\n\t\t\t\t.parseInt(properties.getProperty(\"signatureTime\")); // seconds\n\t\tthis.gap = Integer.parseInt(properties.getProperty(\"gap\")); // milliseconds\n\t\tthis.desync = desync;\n\t}\n\n\tpublic void addEntry(String time, Entry[] entries) {\n\t\tthis.subtitles.put(time, entries);\n\t}\n\n\tpublic void addAll(Map<String, Entry> allSubs) {\n\t\tfor (String t : allSubs.keySet()) {\n\t\t\taddEntry(t, new Entry[] { allSubs.get(t) });\n\t\t}\n\t}\n\n\tpublic void log() {\n\t\tString left = null, right = null, line = \"\";\n\t\tfor (String time : subtitles.keySet()) {\n\t\t\tfor (int i = 0; i < Math.max(subtitles.get(time)[0].size(),\n\t\t\t\t\tsubtitles.get(time)[1].size()); i++) {\n\t\t\t\tleft = i < subtitles.get(time)[0].size()\n\t\t\t\t\t\t? subtitles.get(time)[0].get(i)\n\t\t\t\t\t\t: SrtUtils.getBlankLine();\n\t\t\t\tright = i < subtitles.get(time)[1].size()\n\t\t\t\t\t\t? subtitles.get(time)[1].get(i)\n\t\t\t\t\t\t: SrtUtils.getBlankLine();\n\t\t\t\tline = left + right;\n\t\t\t\tlog.info(time + \" \" + line + \" \" + SrtUtils.getWidth(line));\n\t\t\t}\n\t\t\tlog.info(\"\");\n\t\t}\n\t}\n\n\tprivate void addPadding() {\n\t\tMap<String, Entry[]> output = new TreeMap<String, Entry[]>();\n\t\tEntry[] newEntry;\n\n\t\tfor (String t : subtitles.keySet()) {\n\t\t\tnewEntry = new Entry[2];\n\t\t\tfor (int i = 0; i < 2; i++) {\n\t\t\t\tif (isLong(subtitles.get(t)[i])) {\n\t\t\t\t\tnewEntry[i] = this.splitEntry(subtitles.get(t)[i]);\n\t\t\t\t} else {\n\t\t\t\t\tnewEntry[i] = this.noSplitEntry(subtitles.get(t)[i]);\n\t\t\t\t}\n\t\t\t\toutput.put(t, newEntry);\n\t\t\t}\n\t\t}\n\t\tsubtitles = new TreeMap<String, Entry[]>(output);\n\t}\n\n\t/**\n\t * It checks whether or not an entry (collection of entries) is long (width\n\t * upper than half_width)\n\t * \n\t * @param entry\n\t * @return\n\t */\n\tprivate boolean isLong(Entry entry) {\n\t\tboolean split = false;\n\t\tfloat width;\n\t\tfor (int i = 0; i < entry.size(); i++) {\n\t\t\twidth = SrtUtils.getWidth(entry.get(i));\n\t\t\tif (width > SrtUtils.getHalfWidth()) {\n\t\t\t\tsplit = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn split;\n\t}\n\n\t/**\n\t * It converts and entry adding the padding and splitting lines.\n\t * \n\t * @param entry\n\t * @return\n\t */\n\tprivate Entry splitEntry(Entry entry) {\n\t\tEntry newEntry = new Entry();\n\n\t\tString append = \"\";\n\t\tfor (int i = 0; i < entry.size(); i++) {\n\t\t\tappend += entry.get(i) + SrtUtils.getSpace();\n\t\t}\n\t\tappend = append.trim();\n\t\tString[] words = append.split(SrtUtils.getSpace());\n\n\t\tList<String> ensuredArray = ensureArray(words);\n\n\t\tString newLine = \"\";\n\t\tfor (int i = 0; i < ensuredArray.size(); i++) {\n\t\t\tif (SrtUtils.getWidth(newLine + ensuredArray.get(i)) < SrtUtils\n\t\t\t\t\t.getHalfWidth()) {\n\t\t\t\tnewLine += ensuredArray.get(i) + SrtUtils.getSpace();\n\t\t\t} else {\n\t\t\t\tnewEntry.add(convertLine(newLine.trim()));\n\t\t\t\tnewLine = ensuredArray.get(i) + SrtUtils.getSpace();\n\t\t\t}\n\t\t}\n\t\tif (!newLine.isEmpty()) {\n\t\t\tnewEntry.add(convertLine(newLine.trim()));\n\t\t}\n\n\t\treturn newEntry;\n\t}\n\n\t/**\n\t * It converts and entry adding the padding but without splitting lines.\n\t * \n\t * @param entry\n\t * @return\n\t */\n\tprivate Entry noSplitEntry(Entry entry) {\n\t\tEntry newEntry = new Entry(entry);\n\t\tfor (int i = 0; i < entry.size(); i++) {\n\t\t\tnewEntry.set(i, convertLine(entry.get(i)));\n\t\t}\n\t\treturn newEntry;\n\t}\n\n\t/**\n\t * Ensures that each word in the arrays in no longer than MAXWIDTH\n\t * \n\t * @param words\n\t * @return\n\t */\n\tprivate List<String> ensureArray(String[] words) {\n\t\tList<String> ensured = new LinkedList<String>();\n\t\tfor (String s : words) {\n\t\t\tif (SrtUtils.getWidth(s) <= SrtUtils.getHalfWidth()) {\n\t\t\t\tensured.add(s);\n\t\t\t} else {\n\t\t\t\tint sLength = s.length();\n\t\t\t\tensured.add(s.substring(0, sLength / 2));\n\t\t\t\tensured.add(s.substring(sLength / 2, sLength / 2));\n\t\t\t}\n\t\t}\n\t\treturn ensured;\n\t}\n\n\t/**\n\t * It adds the padding (SEPARATOR + SPACEs) to a single line.\n\t * \n\t * @param line\n\t * @return\n\t */\n\tprivate String convertLine(String line) {\n\t\tfloat width = SrtUtils.getWidth(line);\n\t\tdouble diff = ((SrtUtils.getHalfWidth() - width)\n\t\t\t\t/ SrtUtils.getSpaceWidth()) / 2;\n\t\tdouble rest = diff % 1;\n\t\tint numSpaces = (int) Math.floor(diff);\n\t\tString additional = (rest >= 0.5) ? SrtUtils.getPadding() : \"\";\n\n\t\tif (numSpaces < 0) {\n\t\t\tnumSpaces = 0;\n\t\t}\n\t\tString newLine = SrtUtils.getSeparator()\n\t\t\t\t+ SrtUtils.repeat(SrtUtils.getPadding(), numSpaces + 1)\n\t\t\t\t+ additional + line\n\t\t\t\t+ SrtUtils.repeat(SrtUtils.getPadding(), numSpaces + 1)\n\t\t\t\t+ SrtUtils.getSeparator();\n\n\t\treturn newLine;\n\t}\n\n\tpublic void processDesync(String time, Entry desyncEntry)\n\t\t\tthrows ParseException {\n\t\tTreeMap<String, Entry[]> newSubtitles = new TreeMap<String, Entry[]>();\n\n\t\tDate inTime = SrtUtils.getInitTime(time);\n\t\tDate enTime = SrtUtils.getEndTime(time);\n\t\tlong initTime = inTime != null ? inTime.getTime() : 0;\n\t\tlong endTime = enTime != null ? enTime.getTime() : 0;\n\t\tlong iTime, jTime;\n\t\tint top = 0, down = subtitles.keySet().size();\n\t\tboolean topOver = false, downOver = false;\n\t\tint from, to;\n\n\t\tfor (String t : subtitles.keySet()) {\n\t\t\tinTime = SrtUtils.getInitTime(time);\n\t\t\tenTime = SrtUtils.getEndTime(time);\n\n\t\t\t// Added to ensure format\n\t\t\tif (!t.contains(\"-->\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tiTime = inTime != null ? SrtUtils.getInitTime(t).getTime() : 0;\n\t\t\tjTime = enTime != null ? SrtUtils.getEndTime(t).getTime() : 0;\n\n\t\t\tif (iTime <= initTime) {\n\t\t\t\ttop++;\n\t\t\t}\n\t\t\tif (jTime >= endTime) {\n\t\t\t\tdown--;\n\t\t\t}\n\t\t\tif (iTime <= initTime && jTime >= initTime) {\n\t\t\t\ttopOver = true;\n\t\t\t}\n\t\t\tif (iTime <= endTime && jTime >= endTime) {\n\t\t\t\tdownOver = true;\n\t\t\t}\n\t\t}\n\t\tfrom = top - 1 + (topOver ? 0 : 1);\n\t\tto = down - (downOver ? 0 : 1);\n\n\t\tlog.debug(time + \" TOP \" + top + \" DOWN \" + down + \" TOPOVER \" + topOver\n\t\t\t\t+ \" DOWNOVER \" + downOver + \" SIZE \" + subtitles.size()\n\t\t\t\t+ \" FROM \" + from + \" TO \" + to + \" \"\n\t\t\t\t+ desyncEntry.getSubtitleLines());\n\t\tString mixedTime = mixTime(initTime, endTime, from, to);\n\t\tlog.debug(mixedTime);\n\n\t\tEntry newEntryLeft = new Entry();\n\t\tEntry newEntryRight = new Entry();\n\t\tfor (int i = from; i <= to; i++) {\n\t\t\tnewEntryLeft\n\t\t\t\t\t.addAll(subtitles.get(subtitles.keySet().toArray()[i])[0]);\n\t\t\tnewEntryRight\n\t\t\t\t\t.addAll(subtitles.get(subtitles.keySet().toArray()[i])[1]);\n\t\t}\n\t\tnewEntryRight.addAll(desyncEntry);\n\n\t\tif (top != 0) {\n\t\t\tnewSubtitles.putAll(subtitles.subMap(subtitles.firstKey(), true,\n\t\t\t\t\t(String) subtitles.keySet().toArray()[top - 1], !topOver));\n\t\t}\n\t\tnewSubtitles.put(mixedTime,\n\t\t\t\tnew Entry[] { newEntryLeft, newEntryRight });\n\t\tif (down != subtitles.size()) {\n\t\t\tnewSubtitles.putAll(subtitles.subMap(\n\t\t\t\t\t(String) subtitles.keySet().toArray()[down], !downOver,\n\t\t\t\t\tsubtitles.lastKey(), true));\n\t\t}\n\n\t\tsubtitles = newSubtitles;\n\t}\n\n\tprivate String mixTime(long initTime, long endTime, int from, int to)\n\t\t\tthrows ParseException {\n\n\t\tlong initCandidate = initTime;\n\t\tlong endCandidate = endTime;\n\t\tlong initFromTime = initTime;\n\t\tlong endToTime = endTime;\n\n\t\tif (to > 0 && to >= from) {\n\t\t\tif (from < subtitles.size()) {\n\t\t\t\tDate iTime = SrtUtils.getInitTime(\n\t\t\t\t\t\t(String) subtitles.keySet().toArray()[from]);\n\t\t\t\tif (iTime != null) {\n\t\t\t\t\tinitFromTime = iTime.getTime();\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (to < subtitles.size()) {\n\t\t\t\tDate eTime = SrtUtils\n\t\t\t\t\t\t.getEndTime((String) subtitles.keySet().toArray()[to]);\n\t\t\t\tif (eTime != null) {\n\t\t\t\t\tendToTime = eTime.getTime();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tswitch (getDesync()) {\n\t\t\tcase 0:\n\t\t\t\t// Left\n\t\t\t\tinitCandidate = initFromTime;\n\t\t\t\tendCandidate = endToTime;\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\t// Right\n\t\t\t\tinitCandidate = initTime;\n\t\t\t\tendCandidate = endTime;\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\t// Max\n\t\t\t\tinitCandidate = Math.min(initTime, initFromTime);\n\t\t\t\tendCandidate = Math.max(endTime, endToTime);\n\t\t\t\tbreak;\n\t\t\tcase 3:\n\t\t\t\t// Min\n\t\t\t\tinitCandidate = Math.max(initTime, initFromTime);\n\t\t\t\tendCandidate = Math.min(endTime, endToTime);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn SrtUtils.createSrtTime(new Date(initCandidate),\n\t\t\t\tnew Date(endCandidate));\n\t}\n\n\t/**\n\t * It writes a new subtitle file (SRT) from a subtitle map.\n\t * \n\t * @param subs\n\t * @param fileOuput\n\t * @throws IOException\n\t * @throws ParseException\n\t */\n\tpublic void writeSrt(String fileOuput, String charsetStr, boolean translate,\n\t\t\tboolean merge) throws IOException, ParseException {\n\n\t\tboolean horizontal = SrtUtils.isHorizontal();\n\t\tif (!horizontal && (!translate || (translate & merge))) {\n\t\t\taddPadding();\n\t\t}\n\t\tif (extend) {\n\t\t\tshiftSubs(extension, progressive);\n\t\t}\n\n\t\tString blankLine = horizontal ? \"\" : SrtUtils.getBlankLine();\n\n\t\tFileOutputStream fileOutputStream = new FileOutputStream(\n\t\t\t\tnew File(fileOuput));\n\t\tFileChannel fileChannel = fileOutputStream.getChannel();\n\n\t\tCharset charset = Charset.forName(charsetStr);\n\t\tCharsetEncoder encoder = charset.newEncoder();\n\t\tencoder.onMalformedInput(CodingErrorAction.IGNORE);\n\t\tencoder.onUnmappableCharacter(CodingErrorAction.IGNORE);\n\n\t\tCharBuffer uCharBuffer;\n\t\tByteBuffer byteBuffer;\n\n\t\tif (horizontal) {\n\t\t\tfor (String key : subtitles.keySet()) {\n\t\t\t\tEntry[] entries = subtitles.get(key);\n\t\t\t\tfor (int j = 0; j < entries.length; j++) {\n\t\t\t\t\tList<String> subtitleLines = entries[j].getSubtitleLines();\n\t\t\t\t\tString newLine = \"\";\n\t\t\t\t\tfor (String s : subtitleLines) {\n\t\t\t\t\t\tnewLine += s + \" \";\n\t\t\t\t\t}\n\t\t\t\t\tsubtitleLines.clear();\n\t\t\t\t\tsubtitleLines.add(newLine.trim());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tString left = \"\", right = \"\", time = \"\";\n\t\tString separator = SrtUtils.getSeparator().trim().isEmpty() ? SPACE_HTML\n\t\t\t\t: SrtUtils.getSeparator();\n\t\tString horizontalSeparator = SrtUtils.EOL\n\t\t\t\t+ (SrtUtils.isUsingSeparator() ? separator + SrtUtils.EOL : \"\");\n\t\tfor (int j = 0; j < subtitles.keySet().size(); j++) {\n\t\t\ttime = (String) subtitles.keySet().toArray()[j];\n\t\t\tbyteBuffer = ByteBuffer.wrap((String.valueOf(j + 1) + SrtUtils.EOL)\n\t\t\t\t\t.getBytes(Charset.forName(charsetStr)));\n\t\t\tfileChannel.write(byteBuffer);\n\t\t\tbyteBuffer = ByteBuffer.wrap((time + SrtUtils.EOL)\n\t\t\t\t\t.getBytes(Charset.forName(charsetStr)));\n\t\t\tfileChannel.write(byteBuffer);\n\n\t\t\tint limit = subtitles.get(time).length > 1\n\t\t\t\t\t? Math.max(subtitles.get(time)[0].size(),\n\t\t\t\t\t\t\tsubtitles.get(time)[1].size())\n\t\t\t\t\t: subtitles.get(time)[0].size();\n\t\t\tfor (int i = 0; i < limit; i++) {\n\t\t\t\tleft = i < subtitles.get(time)[0].size()\n\t\t\t\t\t\t? subtitles.get(time)[0].get(i) : blankLine;\n\t\t\t\tif (subtitles.get(time).length > 1) {\n\t\t\t\t\tright = i < subtitles.get(time)[1].size()\n\t\t\t\t\t\t\t? subtitles.get(time)[1].get(i) : blankLine;\n\t\t\t\t}\n\n\t\t\t\tString leftColor = SrtUtils.getParsedLeftColor();\n\t\t\t\tif (leftColor != null) {\n\t\t\t\t\tleft = String.format(leftColor, left);\n\t\t\t\t}\n\t\t\t\tString rightColor = SrtUtils.getParsedRightColor();\n\t\t\t\tif (rightColor != null) {\n\t\t\t\t\tright = String.format(rightColor, right);\n\t\t\t\t}\n\n\t\t\t\tif (horizontal) {\n\t\t\t\t\tuCharBuffer = CharBuffer.wrap(\n\t\t\t\t\t\t\tleft + horizontalSeparator + right + SrtUtils.EOL);\n\t\t\t\t} else {\n\t\t\t\t\tuCharBuffer = CharBuffer.wrap(left + right + SrtUtils.EOL);\n\t\t\t\t}\n\t\t\t\tbyteBuffer = encoder.encode(uCharBuffer);\n\n\t\t\t\tlog.debug(new String(byteBuffer.array(),\n\t\t\t\t\t\tCharset.forName(charsetStr)));\n\n\t\t\t\tfileChannel.write(byteBuffer);\n\t\t\t}\n\t\t\tbyteBuffer = ByteBuffer\n\t\t\t\t\t.wrap(SrtUtils.EOL.getBytes(Charset.forName(charsetStr)));\n\t\t\tfileChannel.write(byteBuffer);\n\t\t}\n\n\t\tfor (String s : signature(translate, merge)) {\n\t\t\tbyteBuffer = ByteBuffer.wrap(\n\t\t\t\t\t(s + SrtUtils.EOL).getBytes(Charset.forName(charsetStr)));\n\t\t\tfileChannel.write(byteBuffer);\n\t\t}\n\t\tbyteBuffer = ByteBuffer\n\t\t\t\t.wrap(SrtUtils.EOL.getBytes(Charset.forName(charsetStr)));\n\t\tfileChannel.write(byteBuffer);\n\t\tfileChannel.close();\n\n\t\tfileOutputStream.close();\n\t}\n\n\t/**\n\t * Adds an entry in the end of the merged subtitles with the program author.\n\t * \n\t * @param subs\n\t * @throws ParseException\n\t */\n\tprivate List<String> signature(boolean translate, boolean merge)\n\t\t\tthrows ParseException {\n\t\tString lastEntryTime = (String) subtitles.keySet()\n\t\t\t\t.toArray()[subtitles.keySet().size() - 1];\n\t\tDate end = SrtUtils.getEndTime(lastEntryTime);\n\t\tfinal Date newDateInit = new Date(end.getTime() + signatureGap);\n\t\tfinal Date newDateEnd = new Date(end.getTime() + signatureTime);\n\t\tString newTime = SrtUtils.createSrtTime(newDateInit, newDateEnd);\n\t\tList<String> signature = new LinkedList<String>();\n\t\tsignature.add(String.valueOf(subtitles.size() + 1));\n\t\tsignature.add(newTime);\n\t\tString signatureText = \"\";\n\t\tif (translate & merge) {\n\t\t\tsignatureText = I18N.getText(\"Merger.signatureboth.text\");\n\t\t} else if (translate & !merge) {\n\t\t\tsignatureText = I18N.getText(\"Merger.signaturetranslated.text\");\n\t\t} else {\n\t\t\tsignatureText = I18N.getText(\"Merger.signature.text\");\n\t\t}\n\t\tsignature.add(signatureText);\n\t\tsignature.add(I18N.getText(\"Merger.signature.url\"));\n\t\treturn signature;\n\t}\n\n\t/**\n\t * This method extends the duration of each subtitle 1 second (EXTENSION).\n\t * If the following subtitle is located inside that extension, the extension\n\t * will be only until the beginning of this next subtitle minus 20\n\t * milliseconds (GAP).\n\t * \n\t * @throws ParseException\n\t */\n\tpublic void shiftSubs(int extension, boolean progressive)\n\t\t\tthrows ParseException {\n\t\tTreeMap<String, Entry[]> newSubtitles = new TreeMap<String, Entry[]>();\n\n\t\tString timeBefore = \"\";\n\t\tDate init;\n\t\tDate tsBeforeInit = new Date();\n\t\tDate tsBeforeEnd = new Date();\n\t\tString newTime = \"\";\n\t\tEntry[] entries;\n\t\tint shiftTime = extension;\n\n\t\tfor (String t : subtitles.keySet()) {\n\t\t\tif (!timeBefore.isEmpty()) {\n\t\t\t\tinit = SrtUtils.getInitTime(t);\n\t\t\t\tif (init != null) {\n\t\t\t\t\tentries = subtitles.get(timeBefore);\n\t\t\t\t\tif (progressive) {\n\t\t\t\t\t\tshiftTime = entries.length > 1 ? extension\n\t\t\t\t\t\t\t\t* Math.max(entries[0].size(), entries[1].size())\n\t\t\t\t\t\t\t\t: entries[0].size();\n\t\t\t\t\t}\n\t\t\t\t\tif (tsBeforeEnd.getTime() + shiftTime < init.getTime()) {\n\t\t\t\t\t\tnewTime = SrtUtils.createSrtTime(tsBeforeInit,\n\t\t\t\t\t\t\t\tnew Date(tsBeforeEnd.getTime() + shiftTime));\n\t\t\t\t\t\tlog.debug(\"Shift \" + timeBefore + \" to \" + newTime\n\t\t\t\t\t\t\t\t+ \" ... extension \" + shiftTime);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnewTime = SrtUtils.createSrtTime(tsBeforeInit,\n\t\t\t\t\t\t\t\tnew Date(init.getTime() - gap));\n\t\t\t\t\t\tlog.debug(\"Shift \" + timeBefore + \" to \" + newTime);\n\t\t\t\t\t}\n\t\t\t\t\tnewSubtitles.put(newTime, entries);\n\t\t\t\t}\n\t\t\t}\n\t\t\ttimeBefore = t;\n\t\t\ttsBeforeInit = SrtUtils.getInitTime(timeBefore);\n\t\t\ttsBeforeEnd = SrtUtils.getEndTime(timeBefore);\n\t\t\tif (tsBeforeInit == null || tsBeforeEnd == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\t// Last entry\n\t\tentries = subtitles.get(timeBefore);\n\t\tif (entries != null && tsBeforeInit != null && tsBeforeEnd != null) {\n\t\t\tif (progressive) {\n\t\t\t\textension *= entries.length > 1\n\t\t\t\t\t\t? Math.max(entries[0].size(), entries[1].size())\n\t\t\t\t\t\t: entries[0].size();\n\t\t\t}\n\t\t\tnewTime = SrtUtils.createSrtTime(tsBeforeInit,\n\t\t\t\t\tnew Date(tsBeforeEnd.getTime() + extension));\n\t\t\tnewSubtitles.put(newTime, entries);\n\t\t}\n\n\t\tsubtitles = newSubtitles;\n\t}\n\n\tpublic int size() {\n\t\treturn subtitles.size();\n\t}\n\n\tpublic int getDesync() {\n\t\treturn desync;\n\t}\n\n}", "public class Merger {\n\n\tprivate static final Logger log = LoggerFactory.getLogger(Merger.class);\n\n\tprivate String outputFolder;\n\tprivate int extension;\n\tprivate boolean extend;\n\tprivate boolean progressive;\n\tprivate Properties properties;\n\tprivate String charset;\n\tprivate int desynch;\n\tprivate boolean translate;\n\tprivate boolean merge;\n\n\tpublic Merger(String outputFolder, boolean extend, int extension,\n\t\t\tboolean progressive, Properties properties, String charset,\n\t\t\tint desynch, boolean translate, boolean merge) {\n\t\tthis.outputFolder = outputFolder;\n\t\tthis.extend = extend;\n\t\t// Extension should be in ms, and GUI asks for it in seconds\n\t\tthis.extension = 1000 * extension;\n\t\tthis.progressive = progressive;\n\t\tthis.properties = properties;\n\t\tthis.charset = charset;\n\t\tthis.desynch = desynch;\n\t\tthis.translate = translate;\n\t\tthis.merge = merge;\n\t}\n\n\tpublic DualSrt mergeSubs(Srt srtLeft, Srt srtRigth) throws ParseException {\n\t\tDualSrt dualSrt = new DualSrt(properties, getDesynch(), extend,\n\t\t\t\textension, progressive);\n\n\t\tMap<String, Entry> subtitlesLeft = new TreeMap<String, Entry>(\n\t\t\t\tsrtLeft.getSubtitles());\n\t\tMap<String, Entry> subtitlesRight = new TreeMap<String, Entry>(\n\t\t\t\tsrtRigth.getSubtitles());\n\n\t\tif (subtitlesLeft.isEmpty() || subtitlesRight.isEmpty()) {\n\t\t\tif (subtitlesLeft.isEmpty()) {\n\t\t\t\tdualSrt.addAll(subtitlesRight);\n\t\t\t} else if (subtitlesRight.isEmpty()) {\n\t\t\t\tdualSrt.addAll(subtitlesLeft);\n\t\t\t}\n\t\t} else {\n\t\t\tfor (String t : subtitlesLeft.keySet()) {\n\t\t\t\tif (subtitlesRight.containsKey(t)) {\n\t\t\t\t\tdualSrt.addEntry(t, new Entry[] { subtitlesLeft.get(t),\n\t\t\t\t\t\t\tsubtitlesRight.get(t) });\n\t\t\t\t\tsubtitlesRight.remove(t);\n\t\t\t\t} else {\n\t\t\t\t\tdualSrt.addEntry(t, new Entry[] { subtitlesLeft.get(t),\n\t\t\t\t\t\t\tnew Entry() });\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!subtitlesRight.isEmpty()) {\n\t\t\t\tfor (String t : subtitlesRight.keySet()) {\n\t\t\t\t\tlog.debug(\"Desynchronization on \" + t + \" \"\n\t\t\t\t\t\t\t+ subtitlesRight.get(t).subtitleLines);\n\t\t\t\t\tdualSrt.processDesync(t, subtitlesRight.get(t));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn dualSrt;\n\t}\n\n\tpublic String getMergedFileName(Srt subs1, Srt subs2) {\n\t\tString mergedFileName = \"\";\n\t\tif (translate) {\n\t\t\tSrt srt = subs1.getFileName() == null ? subs2 : subs1;\n\t\t\tFile file = new File(srt.getFileName());\n\t\t\tString fileName = file.getName();\n\t\t\tint i = fileName.lastIndexOf('.');\n\t\t\ti = i == -1 ? fileName.length() - 1 : i;\n\t\t\tString extension = fileName.substring(i);\n\t\t\tmergedFileName = getOutputFolder() + File.separator\n\t\t\t\t\t+ fileName.substring(0, i);\n\t\t\tif (merge) {\n\t\t\t\tmergedFileName += \" \" + I18N.getText(\"Merger.merged.text\");\n\t\t\t} else {\n\t\t\t\tmergedFileName += \" \" + I18N.getText(\"Merger.translated.text\");\n\t\t\t}\n\t\t\tmergedFileName += extension;\n\t\t} else {\n\t\t\tmergedFileName = getOutputFolder() + File.separator\n\t\t\t\t\t+ compareNames(subs1.getFileName(), subs2.getFileName());\n\t\t}\n\t\treturn mergedFileName;\n\t}\n\n\t/**\n\t * It compares the input names of the SRTs (files) and get the part of those\n\t * name which is the same.\n\t * \n\t * @param str1\n\t * @param str2\n\t * @return\n\t */\n\tprivate String compareNames(String str1, String str2) {\n\t\tstr1 = str1.substring(str1.lastIndexOf(File.separator) + 1).replaceAll(\n\t\t\t\tSrtUtils.SRT_EXT, \"\");\n\t\tstr2 = str2.substring(str2.lastIndexOf(File.separator) + 1).replaceAll(\n\t\t\t\tSrtUtils.SRT_EXT, \"\");\n\n\t\tList<String> set1 = new ArrayList<String>(Arrays.asList(str1\n\t\t\t\t.split(\" |_|\\\\.\")));\n\t\tList<String> set2 = new ArrayList<String>(Arrays.asList(str2\n\t\t\t\t.split(\" |_|\\\\.\")));\n\t\tset1.retainAll(set2);\n\n\t\tStringBuilder sb = new StringBuilder();\n\t\tfor (String s : set1) {\n\t\t\tsb.append(s).append(SrtUtils.getSpace());\n\t\t}\n\t\tString finalName = sb.toString().trim();\n\t\tif (finalName.isEmpty()) {\n\t\t\tfinalName = I18N.getText(\"Merger.finalName.text\").trim();\n\t\t}\n\t\treturn finalName + SrtUtils.SRT_EXT;\n\t}\n\n\tpublic String getOutputFolder() {\n\t\treturn outputFolder;\n\t}\n\n\tpublic boolean isProgressive() {\n\t\treturn progressive;\n\t}\n\n\tpublic void setCharset(String charset) {\n\t\tthis.charset = charset;\n\t}\n\n\tpublic String getCharset() {\n\t\treturn charset;\n\t}\n\n\tpublic boolean isTranslate() {\n\t\treturn translate;\n\t}\n\n\tpublic boolean isMerge() {\n\t\treturn merge;\n\t}\n\n\t/**\n\t * 0 = left; 1 = right; 2 = max; 3 = min\n\t * \n\t * @return\n\t */\n\tpublic int getDesynch() {\n\t\treturn desynch;\n\t}\n\n}", "public class Srt {\n\n\tprivate static final Logger log = LoggerFactory.getLogger(Merger.class);\n\n\tprivate Map<String, Entry> subtitles;\n\tprivate String fileName;\n\tprivate String charset;\n\n\tpublic Srt(String fileName) throws IOException {\n\t\tthis.fileName = fileName;\n\t\tthis.subtitles = new TreeMap<String, Entry>();\n\t\tthis.readSrt(fileName);\n\t}\n\n\tpublic Srt(Srt inputSrt, String fromLang, String toLang, String charset,\n\t\t\tDualSub parent) throws IOException {\n\t\tthis.subtitles = new TreeMap<String, Entry>();\n\t\tMap<String, Entry> subtitlesToTranslate = inputSrt.getSubtitles();\n\t\tString lineToTranslate;\n\t\tEntry translatedEntry;\n\n\t\tPreferences preferences;\n\t\tProperties properties;\n\n\t\tif (parent != null) {\n\t\t\tpreferences = parent.getPreferences();\n\t\t\tproperties = parent.getProperties();\n\t\t} else {\n\t\t\tpreferences = Preferences.userNodeForPackage(DualSub.class);\n\n\t\t\tproperties = new Properties();\n\t\t\tInputStream inputStream = Thread.currentThread()\n\t\t\t\t\t.getContextClassLoader()\n\t\t\t\t\t.getResourceAsStream(\"dualsub.properties\");\n\t\t\tReader reader = new InputStreamReader(inputStream,\n\t\t\t\t\tCharset.ISO88591);\n\t\t\tproperties.load(reader);\n\t\t}\n\n\t\tTranslator.getInstance().setPreferences(preferences);\n\n\t\tList<String> inputLines = new ArrayList<String>();\n\n\t\tfor (String time : subtitlesToTranslate.keySet()) {\n\t\t\tlineToTranslate = \"\";\n\t\t\tfor (String line : subtitlesToTranslate.get(time)\n\t\t\t\t\t.getSubtitleLines()) {\n\t\t\t\tlineToTranslate += line + \" \";\n\t\t\t}\n\t\t\tinputLines.add(lineToTranslate);\n\t\t}\n\n\t\tint max = Integer\n\t\t\t\t.parseInt(properties.getProperty(\"maxTranslationBatch\"));\n\t\tint size = inputLines.size();\n\t\tint rounds = 1 + (size / max);\n\t\tlog.trace(\"Number of rounds {} (total lines {})\", rounds, size);\n\n\t\tList<String> translations = new ArrayList<String>();\n\t\tfor (int i = 0; i < rounds; i++) {\n\t\t\tint fromIndex = i * max;\n\t\t\tint toIndex = fromIndex + max;\n\t\t\tif (toIndex > size) {\n\t\t\t\ttoIndex = size;\n\t\t\t}\n\n\t\t\tlog.trace(\"Round {}/{} ... from {} to {}\", i + 1, rounds, fromIndex,\n\t\t\t\t\ttoIndex);\n\n\t\t\tList<String> roundTranslation = Translator.getInstance().translate(\n\t\t\t\t\tinputLines.subList(fromIndex, toIndex), fromLang, toLang);\n\n\t\t\tlog.trace(\"Adding {} translation to result\",\n\t\t\t\t\troundTranslation.size());\n\t\t\tlog.trace(\"Translation list {} \", roundTranslation);\n\t\t\ttranslations.addAll(roundTranslation);\n\t\t}\n\n\t\tIterator<String> iterator = translations.iterator();\n\n\t\tfor (String time : subtitlesToTranslate.keySet()) {\n\t\t\ttranslatedEntry = new Entry();\n\t\t\ttranslatedEntry.add(iterator.next());\n\t\t\tsubtitles.put(time, translatedEntry);\n\t\t}\n\n\t}\n\n\t/**\n\t * Converts a subtitle file (SRT) into a Map, in which key in the timing of\n\t * each subtitle entry, and the value is a List of String with the content\n\t * of the entry.\n\t * \n\t * @param file\n\t * @throws IOException\n\t */\n\tprivate void readSrt(String file) throws IOException {\n\t\tEntry entry = new Entry();\n\t\tint i = 0;\n\t\tString time = \"\";\n\t\tInputStream isForDetection = readSrtInputStream(file);\n\t\tInputStream isForReading = readSrtInputStream(file);\n\t\tcharset = Charset.detect(isForDetection);\n\t\tlog.info(file + \" detected charset \" + charset);\n\n\t\tBufferedReader br = new BufferedReader(\n\t\t\t\tnew InputStreamReader(isForReading, charset));\n\t\ttry {\n\t\t\tString line = br.readLine();\n\t\t\twhile (line != null) {\n\t\t\t\tif (line.isEmpty()) {\n\t\t\t\t\tif (entry.size() > 0) {\n\t\t\t\t\t\tsubtitles.put(time, entry);\n\t\t\t\t\t\tentry = new Entry();\n\t\t\t\t\t\ti = 0;\n\t\t\t\t\t\ttime = \"\";\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (i == 1) {\n\t\t\t\t\t\ttime = line;\n\t\t\t\t\t}\n\t\t\t\t\tif (i >= 2) {\n\t\t\t\t\t\t// Not adding first two lines of subtitles (index and\n\t\t\t\t\t\t// time)\n\t\t\t\t\t\tif (line.indexOf(SrtUtils.TAG_INIT) != -1\n\t\t\t\t\t\t\t\t&& line.indexOf(SrtUtils.TAG_END) != -1) {\n\t\t\t\t\t\t\tline = removeTags(line);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tentry.add(line);\n\t\t\t\t\t\tlog.debug(line);\n\t\t\t\t\t}\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\tline = br.readLine();\n\t\t\t}\n\t\t} finally {\n\t\t\tbr.close();\n\t\t\tisForReading.close();\n\t\t}\n\t}\n\n\tpublic InputStream readSrtInputStream(String file)\n\t\t\tthrows FileNotFoundException {\n\t\tInputStream inputStream = Thread.currentThread().getContextClassLoader()\n\t\t\t\t.getResourceAsStream(file);\n\t\tif (inputStream == null) {\n\t\t\tinputStream = new BufferedInputStream(new FileInputStream(file));\n\t\t}\n\t\treturn inputStream;\n\t}\n\n\tpublic static String removeTags(String line) {\n\t\tPattern pattern = Pattern.compile(\"<([^>]+)>\");\n\t\tMatcher matcher = pattern.matcher(line);\n\t\treturn matcher.replaceAll(\"\");\n\t}\n\n\tpublic void log() {\n\t\tEntry list;\n\t\tfor (String time : subtitles.keySet()) {\n\t\t\tlist = subtitles.get(time);\n\t\t\tfor (int i = 0; i < list.size(); i++) {\n\t\t\t\tlog.info(time + \" \" + list.get(i) + \" \");\n\t\t\t}\n\t\t\tlog.info(\"\");\n\t\t}\n\t}\n\n\tpublic Map<String, Entry> getSubtitles() {\n\t\treturn subtitles;\n\t}\n\n\tpublic void resetSubtitles() {\n\t\tsubtitles.clear();\n\t}\n\n\tpublic String getFileName() {\n\t\treturn fileName;\n\t}\n\n\tpublic String getCharset() {\n\t\treturn charset;\n\t}\n\n}", "public class SrtUtils {\n\n\tprivate static final Logger log = LoggerFactory.getLogger(Merger.class);\n\n\tprivate static final String SPACE = \" \";\n\tprivate static final String HARD_SPACE = \"\\\\h\";\n\n\tpublic static final String SEP_SRT = \" --> \";\n\tpublic static final String SRT_EXT = \".srt\";\n\tpublic static final String TAG_INIT = \"<\";\n\tpublic static final String TAG_END = \">\";\n\tpublic static final String EOL = \"\\r\\n\";\n\tpublic static final String FONT_INIT = \"<font color=\\\"%s\\\">\";\n\tpublic static final String FONT_END = \"%s</font>\";\n\n\tprivate Font font;\n\tprivate FontMetrics fontMetrics;\n\tprivate float maxWidth;\n\tprivate float separatorWidth;\n\tprivate float spaceWidth;\n\tprivate float halfWidth;\n\tprivate String blankLine;\n\tprivate SimpleDateFormat simpleDateFormat;\n\tprivate String padding;\n\tprivate String separator;\n\tprivate boolean usingSpace;\n\tprivate boolean usingSeparator;\n\tprivate boolean horizontal;\n\tprivate String leftColor;\n\tprivate String rightColor;\n\n\tprivate static SrtUtils singleton = null;\n\n\tpublic static SrtUtils getSingleton() {\n\t\tif (singleton == null) {\n\t\t\tsingleton = new SrtUtils();\n\t\t}\n\t\treturn singleton;\n\t}\n\n\t// Default constructor\n\tpublic SrtUtils() {\n\t}\n\n\t@SuppressWarnings(\"deprecation\")\n\tpublic static void init(String maxWidth, String fontFamily, int fontSize,\n\t\t\tboolean space, boolean separator, String separatorChar, int guard,\n\t\t\tboolean horizontal, String leftColor, String rightColor) {\n\t\tlog.debug(\"maxWidth \" + maxWidth + \" fontFamily \" + fontFamily\n\t\t\t\t+ \" fontSize \" + fontSize + \" space \" + space + \" separator \"\n\t\t\t\t+ separator + \" separatorChar \" + separatorChar + \" guard \"\n\t\t\t\t+ guard);\n\t\tSrtUtils srtUtils = getSingleton();\n\t\tsrtUtils.font = new Font(fontFamily, Font.PLAIN, fontSize);\n\t\tsrtUtils.maxWidth = Float.parseFloat(maxWidth) - guard;\n\t\tsrtUtils.fontMetrics = Toolkit.getDefaultToolkit().getFontMetrics(\n\t\t\t\tsrtUtils.font);\n\t\tsrtUtils.simpleDateFormat = new SimpleDateFormat(\"HH:mm:ss,SSS\");\n\t\tsrtUtils.separator = separator ? separatorChar : \"\";\n\t\tsrtUtils.padding = space ? SrtUtils.SPACE : SrtUtils.HARD_SPACE;\n\t\tsrtUtils.usingSpace = space;\n\t\tsrtUtils.usingSeparator = separator;\n\t\tsrtUtils.horizontal = horizontal;\n\t\tsrtUtils.separatorWidth = separator & !horizontal ? getWidth(srtUtils.separator)\n\t\t\t\t: 0;\n\n\t\t// Even if hard space is used, the width of the padding is the same\n\t\t// as the normal space\n\t\tsrtUtils.spaceWidth = getWidth(SPACE);\n\n\t\t// Gap of two characters (space + separator)\n\t\tsrtUtils.halfWidth = (srtUtils.maxWidth / 2) - 2\n\t\t\t\t* (srtUtils.spaceWidth + srtUtils.separatorWidth);\n\n\t\t// Blank line\n\t\tint numSpaces = (int) Math.round(srtUtils.halfWidth / getSpaceWidth());\n\n\t\tif (separator) {\n\t\t\tsrtUtils.blankLine = SrtUtils.getSeparator()\n\t\t\t\t\t+ repeat(SrtUtils.getPadding(), numSpaces)\n\t\t\t\t\t+ SrtUtils.getSeparator();\n\t\t} else {\n\t\t\tsrtUtils.blankLine = repeat(SrtUtils.getPadding(), numSpaces);\n\t\t}\n\t}\n\n\tpublic static int getWidth(String message) {\n\t\tfinal int width = SrtUtils.getSingleton().fontMetrics\n\t\t\t\t.stringWidth(message);\n\t\tlog.debug(\"getWidth \" + message + \" \" + width);\n\t\treturn width;\n\t}\n\n\t/**\n\t * \n\t * @param str\n\t * @param times\n\t * @return\n\t */\n\tpublic static String repeat(String str, int times) {\n\t\treturn new String(new char[times]).replace(\"\\0\", str);\n\t}\n\n\t/**\n\t * It reads the initial time of a subtitle entry\n\t * \n\t * @param line\n\t * @return\n\t * @throws ParseException\n\t */\n\tpublic static Date getInitTime(String line) throws ParseException {\n\t\tDate out = null;\n\t\tint i = line.indexOf(SrtUtils.SEP_SRT);\n\t\tif (i != -1) {\n\t\t\tString time = line.substring(0, i).trim();\n\t\t\tif (time.length() == 8) {\n\t\t\t\t// Time without milliseconds (e.g. 01:27:40)\n\t\t\t\ttime += \",000\";\n\t\t\t}\n\t\t\tout = SrtUtils.getSingleton().parse(time);\n\t\t}\n\t\treturn out;\n\t}\n\n\t/**\n\t * It reads the ending time of a subtitle entry\n\t * \n\t * @param line\n\t * @return\n\t * @throws ParseException\n\t */\n\tpublic static Date getEndTime(String line) throws ParseException {\n\t\tDate out = null;\n\t\tint i = line.indexOf(SrtUtils.SEP_SRT);\n\t\tif (i != -1) {\n\t\t\tString time = line.substring(i + SrtUtils.SEP_SRT.length());\n\t\t\tif (time.length() == 8) {\n\t\t\t\t// Time without milliseconds (e.g. 01:27:40)\n\t\t\t\ttime += \",000\";\n\t\t\t}\n\t\t\tout = SrtUtils.getSingleton().parse(time);\n\n\t\t}\n\t\treturn out;\n\t}\n\n\tpublic static String createSrtTime(Date dateFrom, Date dateTo) {\n\t\treturn SrtUtils.format(dateFrom) + SrtUtils.SEP_SRT\n\t\t\t\t+ SrtUtils.format(dateTo);\n\t}\n\n\tpublic static Font getFont() {\n\t\treturn SrtUtils.getSingleton().font;\n\t}\n\n\tpublic static float getMaxWidth() {\n\t\treturn SrtUtils.getSingleton().maxWidth;\n\t}\n\n\tpublic static FontMetrics getFontMetrics() {\n\t\treturn SrtUtils.getSingleton().fontMetrics;\n\t}\n\n\tpublic static float getSeparatorWidth() {\n\t\treturn SrtUtils.getSingleton().separatorWidth;\n\t}\n\n\tpublic static float getSpaceWidth() {\n\t\treturn SrtUtils.getSingleton().spaceWidth;\n\t}\n\n\tpublic static float getHalfWidth() {\n\t\treturn SrtUtils.getSingleton().halfWidth;\n\t}\n\n\tpublic static String format(Date date) {\n\t\treturn SrtUtils.getSingleton().simpleDateFormat.format(date);\n\t}\n\n\tpublic Date parse(String date) throws ParseException {\n\t\tDate out = null;\n\t\ttry {\n\t\t\tout = SrtUtils.getSingleton().simpleDateFormat.parse(date);\n\t\t} catch (ParseException e) {\n\t\t\tout = new SimpleDateFormat(\"HH:mm:ss.SSS\").parse(date);\n\t\t}\n\t\treturn out;\n\t}\n\n\tpublic static String getBlankLine() {\n\t\treturn SrtUtils.getSingleton().blankLine;\n\t}\n\n\tpublic static String getSeparator() {\n\t\treturn SrtUtils.getSingleton().separator;\n\t}\n\n\tpublic static String getPadding() {\n\t\treturn SrtUtils.getSingleton().padding;\n\t}\n\n\tpublic static boolean isUsingSpace() {\n\t\treturn SrtUtils.getSingleton().usingSpace;\n\t}\n\n\tpublic static boolean isUsingSeparator() {\n\t\treturn SrtUtils.getSingleton().usingSeparator;\n\t}\n\n\tpublic static String getSpace() {\n\t\treturn SrtUtils.SPACE;\n\t}\n\n\tpublic static boolean isHorizontal() {\n\t\treturn SrtUtils.getSingleton().horizontal;\n\t}\n\n\tpublic static String getLeftColor() {\n\t\treturn SrtUtils.getSingleton().leftColor;\n\t}\n\n\tpublic static String getParsedLeftColor() {\n\t\treturn getLeftColor() != null ? String\n\t\t\t\t.format(FONT_INIT, getLeftColor()) + FONT_END : \"%s\";\n\t}\n\n\tpublic static String getRightColor() {\n\t\treturn SrtUtils.getSingleton().rightColor;\n\t}\n\n\tpublic static String getParsedRightColor() {\n\t\treturn getRightColor() != null ? String.format(FONT_INIT,\n\t\t\t\tgetRightColor()) + FONT_END : \"%s\";\n\t}\n\n\tpublic static void setLeftColor(String leftColor) {\n\t\tSrtUtils.getSingleton().leftColor = leftColor;\n\t}\n\n\tpublic static void setRightColor(String rightColor) {\n\t\tSrtUtils.getSingleton().rightColor = rightColor;\n\t}\n\n}", "public class Charset {\n\n\tpublic static String ISO88591 = \"ISO-8859-1\";\n\tpublic static String UTF8 = \"UTF-8\";\n\n\tprivate static Charset singleton = null;\n\n\tprivate UniversalDetector detector;\n\n\tpublic Charset() {\n\t\tdetector = new UniversalDetector(null);\n\t}\n\n\tpublic static Charset getSingleton() {\n\t\tif (singleton == null) {\n\t\t\tsingleton = new Charset();\n\t\t}\n\t\treturn singleton;\n\t}\n\n\tpublic static String detect(String file) throws IOException {\n\t\tInputStream inputStream = Thread.currentThread()\n\t\t\t\t.getContextClassLoader().getResourceAsStream(file);\n\t\tif (inputStream == null) {\n\t\t\tinputStream = new BufferedInputStream(new FileInputStream(file));\n\t\t}\n\t\treturn Charset.detect(inputStream);\n\t}\n\n\tpublic static String detect(InputStream inputStream) throws IOException {\n\t\tUniversalDetector detector = Charset.getSingleton()\n\t\t\t\t.getCharsetDetector();\n\t\tbyte[] buf = new byte[4096];\n\t\tint nread;\n\t\twhile ((nread = inputStream.read(buf)) > 0 && !detector.isDone()) {\n\t\t\tdetector.handleData(buf, 0, nread);\n\t\t}\n\t\tdetector.dataEnd();\n\t\tString encoding = detector.getDetectedCharset();\n\t\tdetector.reset();\n\t\tinputStream.close();\n\t\tif (encoding == null) {\n\t\t\t// If none encoding is detected, we assume UTF-8\n\t\t\tencoding = UTF8;\n\t\t}\n\t\treturn encoding;\n\t}\n\n\tpublic UniversalDetector getCharsetDetector() {\n\t\treturn detector;\n\t}\n\n}" ]
import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.github.bonigarcia.dualsub.srt.DualSrt; import io.github.bonigarcia.dualsub.srt.Merger; import io.github.bonigarcia.dualsub.srt.Srt; import io.github.bonigarcia.dualsub.srt.SrtUtils; import io.github.bonigarcia.dualsub.util.Charset; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.util.Properties; import org.junit.Assert; import org.junit.Before;
/* * (C) Copyright 2014 Boni Garcia (http://bonigarcia.github.io/) * * 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 io.github.bonigarcia.dualsub.test; /** * TestSynchronization. * * @author Boni Garcia ([email protected]) * @since 1.0.0 */ public class TestSynchronization { private static final Logger log = LoggerFactory .getLogger(TestSynchronization.class); private Properties properties; @Before public void setup() throws IOException { properties = new Properties(); InputStream inputStream = Thread.currentThread() .getContextClassLoader() .getResourceAsStream("dualsub.properties"); properties.load(inputStream); } @Test public void testDesynchronization() throws ParseException, IOException { // Initial configuration SrtUtils.init("624", "Tahoma", 17, true, true, ".", 50, false, null, null); // Input subtitles
Srt srtLeft = new Srt("Exceptions (English).srt");
2